text:
(function($) {
	var DOLPHIN = {};
	var thisTool = DOLPHIN;

	// 基础配置
	DOLPHIN.defaults =  {
		ajax : {
			param : {
				type : 'get',
				dataType : "json",
				data : {},
				contentType : "application/json; charset=UTF-8",
				async : true,
				cache : false,
				loading : false,
				mockPathData : null
			},
			requestHeader : {},
			formatterRequestData : null,
            originalPath : "/data",
			mockPath : "/mockData",
			returnMsgKey : 'msg'
		},
		compare : function(a, b){
			return a == b;
		},

		array : {
			separator : ',',
			formatter : null
		},
		date : {
			dateFormat : 'yyyy-MM-dd',
			dateTimeFormat : 'yyyy-MM-dd hh:mm:ss'
		},

		modalWin : {
			title : '系统提示',
			content : null,
			footer : null,

			defaultHidden : false,

			//event
			init : null,
			hide : null,
			hidden : null
		},
		alert : {
			width : '300px',
			title : '系统提示',
			countDownFlag : true,
			countDownTime : 3
		},
		confirm : {
			width : '300px',
			title : '系统提示'
		},
		prompt : {
			width : '300px',
			title : '系统提示',
			mustFlag : false,

			type : 'text',

			placeholder : '',
			defaultValue : '',

			items : null,															//type = radio, checkbox, select,
			idField : 'code',
			textField : 'name'
		},
		img : {
			mockPath : "/public/mockImg",
			param : {
				prefixPath : "/public/mockImg",
				suffixPath : ".png",
				style : {}
			}
		},
		url : {
			viewPrefix : ""
		},
		mockFlag : false
	};
	DOLPHIN.template = {};

	// 浏览器信息
	DOLPHIN.browser = function() {
		var browser = {
			appName : 'unknown',
			version : 0,
			isMobile : false,
			msIe : false,
			firefox : false,
			opera : false,
			safari : false,
			chrome : false,
			netscape : false
		};
		var userAgent = window.navigator.userAgent;
		if (/(msie|firefox|opera|chrome|netscape)\D+(\d[\d.]*)/.test(userAgent.toLowerCase())) {
			browser[RegExp.$1] = true;
			browser.appname = RegExp.$1;
			browser.version = RegExp.$2;
		} else if (/version\D+(\d[\d.]*).*safari/.test(userAgent.toLowerCase())) { // safari
			browser.safari = true;
			browser.appname = 'safari';
			browser.version = RegExp.$2;
		}

		browser.isMobile = /mobile|Mobile/.test(userAgent);
		browser.language = navigator.language;

		return browser;
	}();

	// 常用路径
	DOLPHIN.path = (function(){
		var obj = {},key;
		for(key in location){
			if(typeof location[key] !== 'function'){
				obj[key] = location[key];
			}
		}
		var pathname = obj.pathname.split('/');
		obj.contextPath = "/" + pathname[1];

		return obj;
	})();

	//常用变量
	DOLPHIN.requestMethod = {
		GET : "get",
		POST : "post",
		PUT : "put",
		DELETE : "delete"
	};

	//数据操作
	DOLPHIN.emptyObj = function (data) {
		for(var key in data){
			delete data[key];
		}
		return data;
	};
	DOLPHIN.isPrime = function(i) {
		var ones = "";
		while(--i >= 0) ones += "1";
		return !/^1?$|^(11+?)\1+$/.test(ones);
	};
	DOLPHIN.isInt = function(num){
		return num == parseInt(num);
	};
	DOLPHIN.isNumber = function(num){
		return num == parseFloat(num);
	};
	DOLPHIN.isPositiveNumber = function(num, flag){
		return (num > 0 || (!flag && num == 0));
	};
	DOLPHIN.compareDate = function(date1, date2){
		return date1.getTime() - date2.getTime();
	};
	DOLPHIN.urlAddParam = function(url, params){
		var newUrl = url,key;
		switch (this.typeof(params)){
			case "array":
				for(var i = 0; i < params.length; i++){
					newUrl = this.urlAddParam(newUrl, params[i]);
				}
				break;
			case "object":
				for(key in params){
					newUrl += (newUrl.indexOf('?') > 0 ? "&" : "?");
					newUrl += key + "=" + params[key] ;
				}
				break;
			default :
		}
		return newUrl;
	};
	DOLPHIN.typeof = function(obj){
		if($.isArray(obj)){
			return "array";
		}else{
			return typeof obj;
		}
	};
	DOLPHIN.objInArray = function(o, a, func){
		var check = func || this.defaults.compare;

		for(var i = 0; i < a.length; i++){
			if(check(o, a[i])){
				return true;
			}
		}
		return false;
	};
	DOLPHIN.objIndexOfArray = function(o, a, func){
		var check = func || this.defaults.compare;

		for(var i = 0; i < a.length; i++){
			if(check(o, a[i])){
				return i;
			}
		}
		return -1;
	};
	DOLPHIN.random = function(length){
		var _Length = length || 6;
		var randomNumber = Math.round(Math.random() * Math.pow(10, _Length));
		var randomStr = randomNumber + "";
		if(randomStr.length < _Length){
			for(var i = 0; i < _Length - randomStr.length;){
				randomStr = "0" + randomStr;
			}
		}
		return randomStr;
	};
	DOLPHIN.dateDifference = function (date1, date2) {
		var difference = [], timeDifference, differenceText,
			differenceUnit = ['毫秒', '秒', '分钟', '小时', '天'],
			divisorArr = [1000, 60, 60, 24],
			level = 0, i;
		try{
			timeDifference = Math.abs(date1.getTime() - date2.getTime());

			if(timeDifference == 0){
				differenceText = 0;
			}else{
				differenceText = "";
				while(timeDifference > 0 && level < divisorArr.length){
					difference.push(timeDifference % divisorArr[level]);
					timeDifference = Math.floor(timeDifference / divisorArr[level]);
					level++;
				}
				if(timeDifference > 0){
					difference.push(timeDifference);
				}

				for(i = 0; i < difference.length; i++){
					differenceText = difference[i] + differenceUnit[i] + differenceText;
				}
			}
		}catch(e){
			console.log(e);
			return differenceText;
		}

		return differenceText;
	};

	//数据间转换
	//string <--> array
	DOLPHIN.splitString = function(string, param){
		var opts = $.extend({}, this.defaults.array, param);
		var data = string.split(opts.separator);
		if(typeof opts.formatter == 'function'){
			for(var i = 0; i < data.length; i++){
				data[i] = opts.formatter(data[i], data);
			}
		}

		return data;
	};
	DOLPHIN.joinArray = function(array, param){
		var opts = $.extend({}, this.defaults.array, param);
		var string = "";
		if(typeof opts.formatter == 'function'){
			for(var i = 0; i < array.length; i++){
				if(i != 0){
					string += opts.separator;
				}
				string += opts.formatter(array[i]);
			}
		}else{
			string = array.join(opts.separator);
		}
		return string;
	};
	//json <--> string
	DOLPHIN.string2json = function(str){
		var o = null;
		try{
			o = jQuery.parseJSON(str);
		}catch(e){
			console.warn(e);
			o = str;
		}
		return o;
	};
	DOLPHIN.json2string = function(json, quote){
		try{
			if(quote == "single"){
				return JSON.stringify(json).replace(/\"/g,"\\\'");
			}else if(quote == "double"){
				return JSON.stringify(json).replace(/\"/g,"\\\"");
			}else{
				return JSON.stringify(json);
			}
		}catch(e){
			console.warn(e);
			return json;
		}
	};
	//form --> json
	DOLPHIN.form2json = function(formId){
		var _form;
		if(typeof formId === 'string'){
			_form = $("#"+formId);
		}else{
			_form = formId;
		}
		var obj = {}, control,
			nameTree, namePointer,
			i, j, k;

		//select,input,textarea,checkbox,radio
		var item = _form.find('select[name], input[name][type!="checkbox"][type!="radio"], textarea[name], input[name][type="checkbox"]:checked, input[name][type="radio"]:checked');
		for(i = 0; i < item.length; i++){
			control = item.eq(i);
			if(control.closest('.table-edit').length > 0 || control.attr('type') == 'file'){
				continue;
			}
			if(control.attr('name').indexOf('.') > 0){
				nameTree = control.attr('name').split('.');
				namePointer = obj;
				for(j = 0; j < nameTree.length; j++){
					if(j != (nameTree.length -1)){
						if(!namePointer[nameTree[j]]){
							namePointer[nameTree[j]] = {};
						}
						namePointer = namePointer[nameTree[j]];
					}else{
						namePointer[nameTree[j]] = control.val();
					}
				}
			}else{
				obj[control.attr('name')] = control.val();
			}
		}

		//list
		var editList = _form.find('.table-edit');
		for(i = 0; i < editList.length; i++){
			obj[editList.eq(i).attr('tableName')] = editList.data('dolphin').data.rows;

			//TODO i18n 处理多语言问题 待优化
			var i18n_box = editList.eq(i).find('.list_body').children('tr').eq(0).find('.dolphin_i18n_box');
			for(j = 0; j < i18n_box.length; j++){
				var field_name = i18n_box.eq(j).attr('controlName');
				for(k = 0; k < obj[editList.eq(i).attr('tableName')].length; k++){
					obj[editList.eq(i).attr('tableName')][k][field_name] = translateI18n(obj[editList.eq(i).attr('tableName')][k][field_name]);
				}
			}
		}

		//TODO i18n 处理多语言问题 待优化
		_form.find('.dolphin_i18n_box').each(function (i) {
			var control = $(this);
			if(control.closest('.table-edit').length > 0 || control.attr('type') == 'file'){
				return true;
			}else{
				var name = control.attr('controlName');
				obj[name] = translateI18n(obj[name]);
			}
		});
		function translateI18n(data){
			var i18nData = "";
			for(var key in data){
				if(i18nData != ""){
					i18nData += ","
				}
				i18nData += "\"" + key + "\"" + ":" + (data[key]?"\"" + data[key] + "\"":"\"\"");
			}

			return i18nData;
		}

		return obj;
	};
	//date
	DOLPHIN.string2date = function(string, format){
		format = format || thisTool.defaults.date.dateFormat;
		var y = string.substring(format.indexOf('y'),format.lastIndexOf('y')+1);//年
		var M = string.substring(format.indexOf('M'),format.lastIndexOf('M')+1);//月
		var d = string.substring(format.indexOf('d'),format.lastIndexOf('d')+1);//日
		var h = string.substring(format.indexOf('h'),format.lastIndexOf('h')+1);//时
		var m = string.substring(format.indexOf('m'),format.lastIndexOf('m')+1);//分
		var s = string.substring(format.indexOf('s'),format.lastIndexOf('s')+1);//秒

		if(s == null ||s == "" || isNaN(s)) {s = new Date().getSeconds();}
		if(m == null ||m == "" || isNaN(m)) {m = new Date().getMinutes();}
		if(h == null ||h == "" || isNaN(h)) {h = new Date().getHours();}
		if(d == null ||d == "" || isNaN(d)) {d = new Date().getDate();}
		if(M == null ||M == "" || isNaN(M)) {M = new Date().getMonth()+1;}
		if(y == null ||y == "" || isNaN(y)) {y = new Date().getFullYear();}
		var dt = null ;
		eval ("dt = new Date('"+ y+"', '"+(M-1)+"','"+ d+"','"+ h+"','"+ m+"','"+ s +"')");
		return dt;
	};
	DOLPHIN.date2string = function(date, format){
		format = format || thisTool.defaults.date.dateFormat;
		var o = {
			"M+" : date.getMonth() + 1, //month
			"d+" : date.getDate(),      //day
			"h+" : date.getHours(),     //hour
			"m+" : date.getMinutes(),   //minute
			"s+" : date.getSeconds(),   //second
			"w+" : "天一二三四五六".charAt(date.getDay()),   //week
			"q+" : Math.floor((date.getMonth() + 3) / 3),  //quarter
			"S"  : date.getMilliseconds() //millisecond
		};
		if(/(y+)/.test(format)) {
			format = format.replace(RegExp.$1,
				(date.getFullYear() + "").substr(4 - RegExp.$1.length));
		}
		for(var k in o){
			if(new RegExp("("+ k +")").test(format)){
				format = format.replace(RegExp.$1,
					RegExp.$1.length == 1 ? o[k] :
						("00" + o[k]).substr(("" + o[k]).length));
			}
		}
		return format;
	};
	DOLPHIN.longDate2string = function(long, format){
		if(long) {
			var date = new Date(long);
			return this.date2string(date, format);
		} else {
			return "";
		}
	};
	DOLPHIN.jsonDate2string = function(json, format){
		var jsonObj = null;
		var jsonStr = null;
		var date = null;

		if(typeof json == "string"){
			jsonStr = json;
			jsonObj = this.string2json(json);
		}else{
			jsonStr = this.json2string(json);
			jsonObj = json;
		}
		if(jsonObj && jsonObj.time){
			date = new Date(jsonObj.time);
			return this.date2string(date, format);
		}else{
			return this.i18n.get('core_jsonDate2string_error', jsonStr);
		}
	};

	//require
	DOLPHIN.require = function (url, pageFlag) {
		var _u = Dolphin.path.contextPath + "/public" + Dolphin.systemConfig.pageScript +(Dolphin.browser.ismobile?"/mobile":"/desktop") + url + ".js";
		document.write('


text:
<?php
class MessageController extends Controller{

	private $has_user=false;
	function __construct(){
		$login = new LoginController();
		$login->index();
		if(App::$user instanceof User) {
			$this->has_user=true;
		} else {
			$this->has_user=false;
		}
	}

	function index(){
		if($this->has_user) {
	//		$this->display('load_dialog');
	//		echo"<pre>";
	//		echo"options: editfile, printfile, message, listmessage\n";
			//		echo"</pre>";
			//
		}
		$this->list_all();
	}

	private function createfile($params) {
		$filename = $params['p'];
		$out = "Creating file";
		exec("touch " . Config::$data_dir . '/' . $filename);
		$this->text = $out;
		$this->display('pre_content');
	}

	function printfile($params) {
		$filename = $params['p'];
		$this->text = file_get_contents(Config::$data_dir . '/' .$filename);
		$this->display('pre_content');
	}

	private function editfile($params){
		if($this->has_user) {
			$filename = Config::$data_dir . '/' .$params['p'];
			if (!file_exists($filename)) {
				$this->createfile($params);
			}
			$this->text = file_get_contents($filename);
			$this->filename = $params['p'];
			$this->display('editbox');
		}
	}

	function message($params){
		if($this->has_user) {
			if(isset($params['id'])){
				/*get existing post*/
			/*	$filename = Config::$data_dir . '/posts/' .$params['id'];
				$this->text = file_get_contents($filename);
				$json=json_decode($this->text);
				foreach($json as $k=>$v){
					$this->$k = $v;
				}
			 */
				$this->post= new Post();
				$this->post->load($params['id']);
			}
			if (empty($this->post->user) || (App::$user->username == $this->post->user)&& isset($params['edit']) ) {
				$this->display('postmessage');
				//	$this->display('pre_content');
			} else if ($this->has_user && isset($params['reply'])){
				$this->post->posted="";
				$this->post->topic = $this->post->id;
				unset($this->post->id);
				//$this->post->id = $this->post->getUniqueId();
				$this->post->user = App::$user->username;
				$this->display('postmessage');
			} else {
				$this->view($params);
			}
		} elseif(isset($params['id'])){
			//$this->display('pre_content');
			$this->view($params);
		} else {
			$this->list_all();
		}
	}

	function view($params){
		$this->post= new Post();
		$this->post->load($params['id']);
//		if isset($params['edit']) {
			$this->display('viewsinglemsg');
//		} else {
//			$this->display('');
//		}
	}

	private function cmp_posted($a, $b){
		if($a['posted'] == $b['posted']){
			return 0;
		} else {
			return $a['posted'] < $b['posted'] ? 1 : -1; // reverse order
		}

	}

	function list_all($params=''){
		//read all data from data dir / posts
		//print all contents from newest to oldest.

		$dir = Config::$data_dir . '/posts/'; //FIXME file handling is not controllers duty!
		$this->text=""; //FIXME ennen kuin tän korjaan ei saa posteja näkymään viimeksi kommentoitu-järjsksä
		$this->messages=array();
		$this->post = new Post("", "");
		if ($dh = opendir($dir)) {
			while (($file = readdir($dh)) !== false) {
				//	$this->text .= "filename: $file : filetype: " . filetype($dir . $file) . "\n";
				if (substr($file, -4)=="json"){
					$this->post->load($file);
					if($this->addThisMessage($params, $this->post)) {
						$this->messages[] = array(
							'index'=>$this->post->id,
							'id'=>$file,
							'user'=>$this->post->user,
							'body'=>$this->post->body,
							'title'=>$this->post->title,
							'posted'=>$this->post->posted);
					}
				}
			}
			uasort($this->messages, array( $this, 'cmp_posted'));
			if (isset($params['long']) || isset($params['topic'])) {
				if (isset($params['topic'])) {
					$this->topic = $params['topic'];
					sort($this->messages);
				}
				$this->display('threadview');
			} else {
				$this->display('messagelist');
			}
			closedir($dh);
		}
	}

	private function addThisMessage($params, $post) {
		if (isset($params['topic'])){
			if($post->id == $params['topic'] || $post->topic == $params['topic']) return true;
			return false;

		} else if (empty($post->topic)){
			return true;
		} else {
			return false;
		}
	}

	function postfile($params){
		if($this->has_user) {
			$post = new Post(app::$user->username, $this->sanitize($params['body']));
			//if(!empty($params['posted'])){
			foreach($params as $k=>$v){
				$post->$k=$this->sanitize($v);
			}
			//}
			if(!empty($params['title'])) {
				$post->setTitle($this->sanitize($params['title']));
			}
			if (!empty($params['body'])) $post->save();
			$this->list_all();
		}
	}

	function writefile($params)
	{
		if($this->has_user) {
			$filename = Config::$data_dir . '/' .$params['p'];
			//$this->text = file_get_contents($filename);
			$this->text = $params['text'];
			//var_dump($this->text);
			file_put_contents($filename, $this->text, FILE_TEXT);
			//$this->display('pre_content');
			$this->printfile($params);
		}
	}

	function sanitize($input){
		$output="";
		$alist=array('ö', 'ä', 'å', 'Ö', 'Ä', 'Å', chr(128), "\t");
		$blist=array('ö', 'ä', 'å', 'Ö', 'Ä', 'Å', '€', ' ');
		$output=str_replace($alist, $blist, $input);
		return $output;
	}

}

?>

redpajama_set_name: RedPajamaGithub


text:
<?
	$text = $_GET['text'];
	$image = @ImageCreateFrompng("../images/empty.png");
    $text_color = ImageColorAllocate($image, 255, 255, 255);
    Header("Content-type: image/png");
    ImageString ($image, 3, imagesx($image)/2-strlen($text)* imagefontwidth(3) / 2, 1, $text, $text_color);
    //$tmpfname="temp/testpng3.png";
    Imagepng($image);
	ImageDestroy($image);
?>


text:
<?php
if($_GET['err_code']) {
	echo 'Error was given, error code: '.$_GET['err_code'];
	return false;
}


text:
<?php

namespace Dock\Cli\IO;

use Dock\IO\ProcessRunner;
use Dock\IO\UserInteraction;
use Symfony\Component\Process\Process;

class InteractiveProcessRunner implements ProcessRunner
{
    /**
     * @var UserInteraction
     */
    private $userInteraction;

    /**
     * @param UserInteraction $userInteraction
     */
    public function __construct(UserInteraction $userInteraction)
    {
        $this->userInteraction = $userInteraction;
    }

    /**
     * {@inheritdoc}
     */
    public function run($command, $mustSucceed = true)
    {
        $process = new Process($command);

        $this->userInteraction->write('<info>RUN</info> '.$process->getCommandLine());

        if ($mustSucceed) {
            $process->setTimeout(null);

            return $process->mustRun($this->getRunningProcessCallback($mustSucceed));
        }

        $process->run($this->getRunningProcessCallback($mustSucceed));

        return $process;
    }

    /**
     * {@inheritdoc}
     */
    public function followsUpWith($command, array $arguments = [])
    {
        $this->userInteraction->write(sprintf(
            '<info>RUN</info> %s %s',
            $command,
            implode(' ', $arguments)
        ));

        pcntl_exec($command, $arguments);
    }

    /**
     * @param bool $highlightErrors
     *
     * @return callable
     */
    private function getRunningProcessCallback($highlightErrors = true)
    {
        return function ($type, $buffer) use ($highlightErrors) {
            $lines = explode("\n", $buffer);
            $prefix = Process::ERR === $type ?
                ($highlightErrors ? '<error>ERR</error>' : 'ERR')
                : '<question>OUT</question>';

            foreach ($lines as $line) {
                $line = trim($line);
                if (!empty($line)) {
                    $this->userInteraction->write($prefix.' '.$line);
                }
            }
        };
    }
}


text:
package de.greenrobot.event;

import android.util.Log;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

class SubscriberMethodFinder {
    private static final String ON_EVENT_METHOD_NAME = "onEvent";

    /*
     * In newer class files, compilers may add methods. Those are called bridge or synthetic methods.
     * EventBus must ignore both. There modifiers are not public but defined in the Java class file format:
     * http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.6-200-A.1
     */
    private static final int BRIDGE = 0x40;
    private static final int SYNTHETIC = 0x1000;

    private static final int MODIFIERS_IGNORE = Modifier.ABSTRACT | Modifier.STATIC | BRIDGE | SYNTHETIC;
    private static final Map<String, List<SubscriberMethod>> methodCache = new HashMap<String, List<SubscriberMethod>>();

    private final Map<Class<?>, Class<?>> skipMethodVerificationForClasses;

    SubscriberMethodFinder(List<Class<?>> skipMethodVerificationForClassesList) {
        skipMethodVerificationForClasses = new ConcurrentHashMap<Class<?>, Class<?>>();
        if (skipMethodVerificationForClassesList != null) {
            for (Class<?> clazz : skipMethodVerificationForClassesList) {
                skipMethodVerificationForClasses.put(clazz, clazz);
            }
        }
    }

    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        String key = subscriberClass.getName();
        List<SubscriberMethod> subscriberMethods;
        synchronized (methodCache) {
            subscriberMethods = methodCache.get(key);
        }
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
        subscriberMethods = new ArrayList<SubscriberMethod>();
        Class<?> clazz = subscriberClass;
        HashSet<String> eventTypesFound = new HashSet<String>();
        StringBuilder methodKeyBuilder = new StringBuilder();
        while (clazz != null) {
            String name = clazz.getName();
            if (name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("android.")) {
                // Skip system classes, this just degrades performance
                break;
            }

            // Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)
            Method[] methods = clazz.getDeclaredMethods();
            for (Method method : methods) {
                String methodName = method.getName();
                if (methodName.startsWith(ON_EVENT_METHOD_NAME)) {
                    int modifiers = method.getModifiers();
                    if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                        Class<?>[] parameterTypes = method.getParameterTypes();
                        if (parameterTypes.length == 1) {
                            String modifierString = methodName.substring(ON_EVENT_METHOD_NAME.length());
                            ThreadMode threadMode;
                            if (modifierString.length() == 0) {
                                threadMode = ThreadMode.PostThread;
                            } else if (modifierString.equals("MainThread")) {
                                threadMode = ThreadMode.MainThread;
                            } else if (modifierString.equals("BackgroundThread")) {
                                threadMode = ThreadMode.BackgroundThread;
                            } else if (modifierString.equals("Async")) {
                                threadMode = ThreadMode.Async;
                            } else {
                                if (skipMethodVerificationForClasses.containsKey(clazz)) {
                                    continue;
                                } else {
                                    throw new EventBusException("Illegal onEvent method, check for typos: " + method);
                                }
                            }
                            Class<?> eventType = parameterTypes[0];
                            methodKeyBuilder.setLength(0);
                            methodKeyBuilder.append(methodName);
                            methodKeyBuilder.append('>').append(eventType.getName());
                            String methodKey = methodKeyBuilder.toString();
                            if (eventTypesFound.add(methodKey)) {
                                // Only add if not already found in a sub class
                                subscriberMethods.add(new SubscriberMethod(method, threadMode, eventType));
                            }
                        }
                    } else if (!skipMethodVerificationForClasses.containsKey(clazz)) {
                        Log.d(EventBus.TAG, "Skipping method (not public, static or abstract): " + clazz + "."
                                + methodName);
                    }
                }
            }
            clazz = clazz.getSuperclass();
        }
        if (subscriberMethods.isEmpty()) {
            throw new EventBusException("Subscriber " + subscriberClass + " has no public methods called "
                    + ON_EVENT_METHOD_NAME);
        } else {
            synchronized (methodCache) {
                methodCache.put(key, subscriberMethods);
            }
            return subscriberMethods;
        }
    }

    static void clearCaches() {
        synchronized (methodCache) {
            methodCache.clear();
        }
    }

}


text:
Wraps a function of any arity (including nullary) in a function that accepts
exactly 2 parameters. Any extraneous parameters will not be passed to the
supplied function.

@func
@memberOf R
@since v0.2.0
@category Function
@sig (* -> c) -> (a, b -> c)
@param {Function} fn The function to wrap.
@return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
        arity 2.
@see R.nAry, R.unary
@example

     var takesThreeArgs = function(a, b, c) {
       return [a, b, c];
     };
     takesThreeArgs.length; //=> 3
     takesThreeArgs(1, 2, 3); //=> [1, 2, 3]

     var takesTwoArgs = R.binary(takesThreeArgs);
     takesTwoArgs.length; //=> 2
     // Only 2 arguments are passed to the wrapped function
     takesTwoArgs(1, 2, 3); //=> [1, 2, undefined]
@symb R.binary(f)(a, b, c) = f(a, b)


text:
/********************************************************************************/
/*										*/
/*			     	TPM Get the signed audit digest			*/
/*			     Written by S. Berger				*/
/*		       IBM Thomas J. Watson Research Center			*/
/*	      $Id: getauditdigestsigned.c 4702 2013-01-03 21:26:29Z kgoldman $	*/
/*										*/
/* (c) Copyright IBM Corporation 2006, 2010.					*/
/*										*/
/* All rights reserved.								*/
/* 										*/
/* Redistribution and use in source and binary forms, with or without		*/
/* modification, are permitted provided that the following conditions are	*/
/* met:										*/
/* 										*/
/* Redistributions of source code must retain the above copyright notice,	*/
/* this list of conditions and the following disclaimer.			*/
/* 										*/
/* Redistributions in binary form must reproduce the above copyright		*/
/* notice, this list of conditions and the following disclaimer in the		*/
/* documentation and/or other materials provided with the distribution.		*/
/* 										*/
/* Neither the names of the IBM Corporation nor the names of its		*/
/* contributors may be used to endorse or promote products derived from		*/
/* this software without specific prior written permission.			*/
/* 										*/
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS		*/
/* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT		*/
/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR	*/
/* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT		*/
/* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,	*/
/* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT		*/
/* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,	*/
/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY	*/
/* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT		*/
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE	*/
/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.		*/
/********************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef TPM_POSIX
#include <netinet/in.h>
#endif
#ifdef TPM_WINDOWS
#include <winsock2.h>
#endif
#include <openssl/rsa.h>

#include "tpm.h"
#include "tpmutil.h"
#include <tpmfunc.h>

static void usage() {
	printf("Usage: getauditdigestsigned -h <key handle> [-p <key password>] -s <start ordinal>  [-v]\n"
	       "\n"
	       "-s    : option to pass the start ordinal for the audit\n"
	       "-v    : turns on verbose mode\n"
	       "\n");
	exit(-1);
}

int main(int argc, char *argv[])
{
	uint32_t startOrdinal = -1;
	int ret;
	int verbose = FALSE;
	TPM_COUNTER_VALUE counter;
	int i = 1;
	char * keypass = NULL;
	unsigned char keyAuth[TPM_HASH_SIZE];
	unsigned char * keyAuthPtr = NULL;
	uint32_t keyhandle = -1;
	STACK_TPM_BUFFER(signature);
	unsigned char digest[TPM_DIGEST_SIZE];
	unsigned char ordinalDigest[TPM_DIGEST_SIZE];
	unsigned char antiReplay[TPM_NONCE_SIZE];

	TPM_setlog(0);
	TSS_gennonce(antiReplay);

	while (i < argc) {
		if (!strcmp("-s",argv[i])) {
			i++;
			if (i < argc) {
				sscanf(argv[i],"%d",&startOrdinal);
			} else {
				printf("Missing parameter for -s.\n");
				usage();
			}
		} else
		if (!strcmp("-h",argv[i])) {
			i++;
			if (i < argc) {
				sscanf(argv[i],"%x",&keyhandle);
			} else {
				printf("Missing parameter for -h.\n");
				usage();
			}
		} else
		if (!strcmp("-p",argv[i])) {
			i++;
			if (i < argc) {
				keypass = argv[i];
			} else {
				printf("Missing parameter for -p.\n");
				usage();
			}
		} else
		if (!strcmp("-v",argv[i])) {
			verbose = TRUE;
			TPM_setlog(1);
		} else {
		        printf("\n%s is not a valid option\n", argv[i]);
			usage();
		}
		i++;
	}
	(void)verbose;

	if (-1 == (int)startOrdinal ||
	    -1 == (int)keyhandle) {
		printf("Missing command line parameter.\n");
		usage();
	}

	if (NULL != keypass) {
		TSS_sha1(keypass,strlen(keypass),keyAuth);
		keyAuthPtr = keyAuth;
	}
	ret = TPM_GetAuditDigestSigned(keyhandle,
	                               FALSE,
	                               keyAuthPtr,
	                               antiReplay,
	                               &counter,
	                               digest,
	                               ordinalDigest,
	                               &signature);

	if (0 != ret) {
		printf("Error %s from GetAuditDigestSigned.\n",
		       TPM_GetErrMsg(ret));
	} else {
		TPM_SIGN_INFO tsi;
		STACK_TPM_BUFFER(tsi_ser);
		STACK_TPM_BUFFER(serial);
		STACK_TPM_BUFFER(ctr_ser);
		pubkeydata pubkey;
		RSA *rsa;

		i = 0;
		printf("AuditDigest   : ");
		while (i < (int)sizeof(digest)) {
			printf("%02X",digest[i]);
			i++;
		}
		printf("\n");

		i = 0;
		printf("OrdinalDigest : ");
		while (i < (int)sizeof(digest)) {
			printf("%02X",ordinalDigest[i]);
			i++;
		}
		printf("\n");

		ret = TPM_GetPubKey(keyhandle, keyAuthPtr, &pubkey);
		if (ret != 0) {
			printf("Could not get public key of signing key.\n");
			exit(-1);
		}
		rsa = TSS_convpubkey(&pubkey);
		if (!rsa) {
			printf("Could not convert public key.\n");
			exit(-1);
		}

		tsi.tag = TPM_TAG_SIGNINFO;
		memcpy(tsi.fixed, "ADIG", 4);
		memcpy(tsi.replay, antiReplay, sizeof(antiReplay));
		/* D4=ordinalDigest */
		TPM_WriteCounterValue(&ctr_ser, &counter);
		memcpy(&serial.buffer[0], digest, sizeof(digest));
		memcpy(&serial.buffer[sizeof(digest)],
		                          ctr_ser.buffer, ctr_ser.used);
		memcpy(&serial.buffer[sizeof(digest)+ctr_ser.used],
		                          ordinalDigest, sizeof(ordinalDigest));
		serial.used = sizeof(digest) + ctr_ser.used + sizeof(ordinalDigest);
		tsi.data.size = serial.used;
		tsi.data.buffer = serial.buffer;
		ret = TPM_WriteSignInfo(&tsi_ser, &tsi);
		if ((ret & ERR_MASK)) {
			printf("Error serializing TPM_SIGN_INFO.\n");
			exit(-1);
		}
		ret = TPM_ValidateSignature(TPM_SS_RSASSAPKCS1v15_SHA1,
		                            &tsi_ser,
		                            &signature,
		                            rsa);
		if (ret != 0) {
			printf("Error validating signature.\n");
			exit(-1);
		}
		printf("Signature verification successful.\n");
	}
	exit(ret);
}


text:
\subsection{Scheduling: Non-Preemptive, Size-Based}
\label{sec:Scheduling-Non-Preemptive-Size-Based}

The most common non-preemptive size-based scheduling policies are

\begin{description}

	\item [Shortest-Job-First (SJF)] the server chooses the job with the smallest size.

\end{description}

It is convenient to evaluate size-based policies as \textit{non-preemptive priority queueing}, where priority classes are job sizes and a job has higher priority if it has lower job size.

\subsection{Non-Preemptive Priority Queueing}
\label{sec:NP-Priority}

For non-preemptive priority queueing (NP-Priority), we have that

\begin{equation}
\label{eqn:NP-Priority-Queue-Time-Size}
\expected{T_{Q}(x)}^{\mathit{NP-Priority}}=
\frac{\varrho\expected{S^{2}}}{2\expected{S}}
\frac{1}{\Big(1-\sum_{i=1}^{x}\varrho_{i}\Big)\cdot\Big(1-\sum_{i=1}^{x-1}\varrho_{i}\Big)}
\end{equation}

The first factor of the denominator can be seen as the contribution due to waiting for jobs in queue with higher or equal priority.
The second factor of the denominator can be seen as the contribution due to those jobs arriving later with strictly higher priority.

Recall that $\expected{T_{Q}}^{\mathit{FCFS}}=\frac{\varrho\frac{\expected{S^{2}}}{\expected{S}}}{1-\varrho}$.

If $k$ is low, $\expected{T_{Q}(x)}^{\mathit{NP-Priority}}<\expected{T_{Q}^{\mathit{FCFS}}}$.
If $k$ is high and job size distribution is heavy-tailed, $\expected{T_{Q}(x)}^{\mathit{NP-Priority}}<\expected{T_{Q}}^{\mathit{FCFS}}$.

The above results hold because $\sum_{i=1}^{k}\varrho_{i}<<\varrho$.

We determine the mean queue time as follow

\begin{equation}
\label{eqn:NP-Priority-Queue-Time}
\expected{T_{Q}}^{\mathit{NP-Priority}}=\sum_{i=1}^{n}\expected{T_{Q}(i)}\cdot p_{i}=\sum_{i=1}^{n}\expected{T_{Q}(i)}\cdot\frac{\lambda_{i}}{\lambda}
\end{equation}

where $p_{i}$ is the fraction of jobs belonging to class $i$.

We will use these results to analyze SJF.

\subsection{Scheduling: SJF}
\label{sec:Scheduling-SJF}

We model SJF as NP-Priority with infinite priority classes, where the smaller the job, the higher the priority.

By applying \Cref{eqn:NP-Priority-Queue-Time-Size,eqn:NP-Priority-Queue-Time}, we obtain:

\begin{equation}
\label{eqn:SJF-Queue-Time-Size}
\expected{T_{Q}(x)}^{\mathit{SJF}}=
\frac{\varrho\expected{S^{2}}}{2\expected{S}}\cdot\frac{1}{\Big(1-\varrho_{x}\Big)^{2}}
\end{equation}

where $\varrho_{x}=\lambda F(x)\cdot\int_{t=0}^{x}t\frac{f(t)}{F(t)}\partial t$ is the arrival rate of jobs of size no more than $x$, namely $\lambda F(x)$, multiplied by the expected size of jobs of size no more than $x$, namely $\int_{t=0}^{x}t\frac{f(t)}{F(t)}\partial t$.

We also obtain:

\begin{equation}
\label{eqn:SJF-Queue-Time}
\expected{T_{Q}}^{\mathit{SJF}}=
\frac{\varrho\expected{S^{2}}}{2\expected{S}}\cdot\int_{x=0}^{x_{n}}\frac{f(x)\partial x}{\Big(1-\lambda\int_{t=0}^{x}tf(t)\partial t\Big)^{2}}
\end{equation}

By comparing $\expected{T_{Q}}^{\mathit{SJF}}$ with $\expected{T_{Q}}^{\mathit{FCFS}}$, we have that SJF is a poor choice for (i) very large jobs (see term $\varrho_{x}$) and (ii) high-variable job sizes \footnote{Since real workload are heavy-tailed, most jobs are small, hence we may think not to worry about very large jobs. This is a wrong idea. Heavy-tailed distribution have also high variability.} (see term $\expected{S^{2}}$).

When using SJF under high-variable job size, it is more efficient to kill long-running jobs, given that there are some other jobs in queue. In fact, if there are many jobs in queue, they are likely to include many short jobs, thus mean response time would improve. This is the idea behind TAGS policy in \cite{harchol2000task}.

The only way to get good performance out of SJF under real workload is to provide preemption.


text:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using SVNSlackNotifier.Helpers;
using SVNSlackNotifier.Models;

namespace SVNSlackNotifier
{
    public class SlackNotifier
    {
        public event EventHandler OnFinished = null;

        public async Task<bool> PostNotificationAsync(Notification notification)
        {
            var isSuccess = false;

            try
            {
                if (string.IsNullOrEmpty(ConfigurationHelper.SlackWebhookURL))
                    Logger.Shared.WriteError("Missing Slack Webhook URL");
                else if(ConfigurationHelper.SlackWebhookURL == "https://hooks.slack.com/services/foo/bar/baz")
                    Logger.Shared.WriteError("Found default Slack Webhook URL in config file. Ensure you've replaced it with your own.");
                else if (string.IsNullOrEmpty(notification.RepositoryPath))
                    Logger.Shared.WriteError("Missing repo path");
                else if (string.IsNullOrEmpty(notification.Revision))
                    Logger.Shared.WriteError("Missing revision number");
                else
                {
                    // Post to Slack
                    using (var client = new HttpClient())
                    {
                        var request = new HttpRequestMessage(HttpMethod.Post, ConfigurationHelper.SlackWebhookURL);
                        var keyValues = new List<KeyValuePair<string, string>>();
                        var payload = BuildPayload(notification);
                        keyValues.Add(new KeyValuePair<string, string>("payload", payload));
                        request.Content = new FormUrlEncodedContent(keyValues);
                        using (var response = await client.SendAsync(request))
                        using (var content = response.Content)
                        {
                            if (!response.IsSuccessStatusCode)
                            {
                                var result = await content.ReadAsStringAsync();
                                Logger.Shared.WriteError("Failed to send notification: " + response.StatusCode + " => " + result);
                                if (result == "Payload was not valid JSON")
                                    Logger.Shared.WriteError("payload = " + payload);
                            }
                        }
                    }
                }
            }
            catch(Exception e)
            {
                Logger.Shared.WriteError(e);
            }

            if (OnFinished != null)
                OnFinished(this, null);

            return isSuccess;
        }

        private string BuildPayload(Notification notification)
        {
            // Get some more data about this commit via "svnlook"
            notification.CommitMessage = CommandLineHelper.ExecuteProcess(ConfigurationHelper.SVNLookProcessPath, string.Format("log -r {0} {1}", notification.Revision, notification.RepositoryPath));
            notification.CommitAuthor = CommandLineHelper.ExecuteProcess(ConfigurationHelper.SVNLookProcessPath, string.Format("author -r {0} {1}", notification.Revision, notification.RepositoryPath));

            // Ensure valid formatting of message
            if(notification.CommitMessage.Contains("\""))
                notification.CommitMessage = notification.CommitMessage.Replace("\"", "\\\"");
            if (notification.CommitAuthor.Contains("\""))
                notification.CommitAuthor = notification.CommitAuthor.Replace("\"", "\\\"");
            // Trim off unnecessary trailing CRLFs
            notification.CommitMessage = notification.CommitMessage.TrimEnd(new char[] { '\r', '\n' });
            notification.CommitAuthor = notification.CommitAuthor.TrimEnd(new char[] { '\r', '\n' });

            // Use advanced message formatting for incoming webhooks
            var payloadBody = new StringBuilder();
            payloadBody.Append("{");    // begin payload
            payloadBody.Append(" \"username\" : \"VisualSVN Server\", ");
            payloadBody.Append(" \"icon_url\" : \"http://s3.amazonaws.com/scs-public/visualsvn_96.png\", ");
            if (!string.IsNullOrEmpty(notification.Channel))
                payloadBody.Append(string.Format(" \"channel\" : \"{0}\", ", notification.Channel));
            payloadBody.Append(" \"attachments\" : [ { ");  // begin attachments
            if (!string.IsNullOrEmpty(notification.RepositoryName))
            {
                payloadBody.Append(string.Format(" \"fallback\" : \"[{0}] New commit by {1}: r{2}: {3}\", ", notification.RepositoryName, notification.CommitAuthor, notification.Revision, notification.CommitMessage));
                payloadBody.Append(string.Format(" \"pretext\" : \"[{0}] New commit by {1}\", ", notification.RepositoryName, notification.CommitAuthor));
            }
            else
            {
                payloadBody.Append(string.Format(" \"fallback\" : \"New commit by {0}: r{1}: {2}\", ", notification.CommitAuthor, notification.Revision, notification.CommitMessage));
                payloadBody.Append(string.Format(" \"pretext\" : \"New commit by {0}\", ", notification.CommitAuthor));
            }
            if (!string.IsNullOrEmpty(notification.RepositoryURL))
            {
                if (notification.RepositoryURL.Contains("/svn/"))
                    notification.RepositoryURL = notification.RepositoryURL.Replace("/svn/", "/!/#");
                notification.RepositoryURL += "/commit/r" + notification.Revision;
                payloadBody.Append(string.Format(" \"text\" : \"<{0}|r{1}>: {2}\", ", notification.RepositoryURL, notification.Revision, notification.CommitMessage));
            }
            else
                payloadBody.Append(string.Format(" \"text\" : \"r{0}: {1}\", ", notification.Revision, notification.CommitMessage));
            payloadBody.Append(" \"color\" : \"#3886C0\" ");
            payloadBody.Append("} ]"); // end attachments
            payloadBody.Append("}"); // end payload

            return payloadBody.ToString();
        }
    }
}


text:
package com.example.buck;

public class Lib2 {
    public void changeMe() { }
}


text: TODO https://docs.mongodb.com/manual/text-search/


text:
package com.macro.mall.controller;

import com.macro.mall.common.api.CommonResult;
import com.macro.mall.model.CmsPrefrenceArea;
import com.macro.mall.service.CmsPrefrenceAreaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 商品优选管理Controller
 * Created by macro on 2018/6/1.
 */
@Controller
@Api(tags = "CmsPrefrenceAreaController")
@Tag(name = "CmsPrefrenceAreaController", description = "商品优选管理")
@RequestMapping("/prefrenceArea")
public class CmsPrefrenceAreaController {
    @Autowired
    private CmsPrefrenceAreaService prefrenceAreaService;

    @ApiOperation("获取所有商品优选")
    @RequestMapping(value = "/listAll", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<CmsPrefrenceArea>> listAll() {
        List<CmsPrefrenceArea> prefrenceAreaList = prefrenceAreaService.listAll();
        return CommonResult.success(prefrenceAreaList);
    }
}


text:
<!DOCTYPE html>

	<title>jQuery Plugin Slideshow</title>
	<link rel="stylesheet" href="SlidesJS/css/example.css">
	<link rel="stylesheet" href="SlidesJS/css/font-awesome.min.css">
	<link rel="stylesheet" href="script03.css">


text:
package com.datatorrent.contrib.hive;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ExecutionException;

import javax.validation.constraints.Min;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.commons.lang3.mutable.MutableInt;

import com.datatorrent.api.Context.OperatorContext;
import com.datatorrent.api.DAG;
import com.datatorrent.api.DefaultOutputPort;
import com.datatorrent.api.Operator.CheckpointListener;
import com.datatorrent.api.annotation.Stateless;
import com.datatorrent.lib.io.fs.AbstractFileOutputOperator;
import com.datatorrent.netlet.util.DTThrowable;

/**
 * An implementation of FS Writer that writes text files to hdfs which are
 * inserted into hive on committed window callback. HiveStreamCodec is used to
 * make sure that data being sent to a particular hive partition goes to a
 * specific operator partition by passing FSRollingOutputOperator to the stream
 * codec. Also filename is determined uniquely for each tuple going to a
 * specific hive partition.
 *
 * @since 2.1.0
 */
public abstract class AbstractFSRollingOutputOperator<T> extends AbstractFileOutputOperator<T>
    implements CheckpointListener
{
  private transient String outputFilePath;
  protected MutableInt partNumber;
  protected HashMap<Long, ArrayList<String>> mapFilenames = new HashMap<Long, ArrayList<String>>();
  protected HashMap<String, ArrayList<String>> mapPartition = new HashMap<String, ArrayList<String>>();
  protected Queue<Long> queueWindows = new LinkedList<Long>();
  protected long windowIDOfCompletedPart = Stateless.WINDOW_ID;
  protected long committedWindowId = Stateless.WINDOW_ID;
  private boolean isEmptyWindow;
  private transient int operatorId;
  private int countEmptyWindow;
  private ArrayList<String> partition = new ArrayList<String>();

  //This variable is user configurable.
  @Min(0)
  private long maxWindowsWithNoData = 100;

  /**
   * The output port that will emit a POJO containing file which is committed
   * and specific hive partitions in which this file should be loaded to
   * HiveOperator.
   */
  public final transient DefaultOutputPort<FilePartitionMapping> outputPort = new DefaultOutputPort<FilePartitionMapping>();

  public AbstractFSRollingOutputOperator()
  {
    countEmptyWindow = 0;
    HiveStreamCodec<T> hiveCodec = new HiveStreamCodec<T>();
    hiveCodec.rollingOperator = this;
    streamCodec = hiveCodec;
  }

  @Override
  public void setup(OperatorContext context)
  {
    String appId = context.getValue(DAG.APPLICATION_ID);
    operatorId = context.getId();
    outputFilePath = File.separator + appId + File.separator + operatorId;
    super.setup(context);
  }

  @Override
  public void beginWindow(long windowId)
  {
    isEmptyWindow = true;
    windowIDOfCompletedPart = windowId;
  }

  /*
   * MapFilenames has mapping from completed file to windowId in which it got completed.
   * Also maintaining a queue of these windowIds which helps in reducing iteration time in committed callback.
   */
  @Override
  protected void rotateHook(String finishedFile)
  {
    isEmptyWindow = false;
    if (mapFilenames.containsKey(windowIDOfCompletedPart)) {
      mapFilenames.get(windowIDOfCompletedPart).add(finishedFile);
    } else {
      ArrayList<String> listFileNames = new ArrayList<String>();
      listFileNames.add(finishedFile);
      mapFilenames.put(windowIDOfCompletedPart, listFileNames);
    }
    queueWindows.add(windowIDOfCompletedPart);

  }

  /*
   * Filenames include operator Id and the specific hive partitions to which the file will be loaded.
   * Partition is determined based on tuple and its implementation is left to user.
   */
  @Override
  protected String getFileName(T tuple)
  {
    isEmptyWindow = false;
    partition = getHivePartition(tuple);
    StringBuilder output = new StringBuilder(outputFilePath);
    int numPartitions = partition.size();
    if (numPartitions > 0) {
      for (int i = 0; i < numPartitions; i++) {
        output.append(File.separator).append(partition.get(i));
      }
      output.append(File.separator).append(operatorId).append("-transaction.out.part");
      String partFile = getPartFileNamePri(output.toString());
      mapPartition.put(partFile, partition);
    }
    return output.toString();
  }

  /*
   * Moving completed files into hive on committed window callback.
   * Criteria for moving them is that the windowId in which they are completed
   * should be less than committed window.
   */
  @Override
  public void committed(long windowId)
  {
    committedWindowId = windowId;
    Iterator<Long> iterWindows = queueWindows.iterator();
    ArrayList<String> list = new ArrayList<String>();
    while (iterWindows.hasNext()) {
      windowId = iterWindows.next();
      if (committedWindowId >= windowId) {
        logger.debug("list is {}", mapFilenames.get(windowId));
        list = mapFilenames.get(windowId);
        FilePartitionMapping partMap = new FilePartitionMapping();
        if (list != null) {
          for (int i = 0; i < list.size(); i++) {
            partMap.setFilename(list.get(i));
            partMap.setPartition(mapPartition.get(list.get(i)));
            outputPort.emit(partMap);
          }
        }
        mapFilenames.remove(windowId);
        iterWindows.remove();
      }
      if (committedWindowId < windowId) {
        break;
      }
    }
  }

  @Override
  public void checkpointed(long windowId)
  {
  }

  protected void rotateCall(String lastFile)
  {
    try {
      this.rotate(lastFile);
    } catch (IOException ex) {
      logger.debug(ex.getMessage());
      DTThrowable.rethrow(ex);
    } catch (ExecutionException ex) {
      logger.debug(ex.getMessage());
      DTThrowable.rethrow(ex);
    }
  }

  public String getHDFSRollingLastFile()
  {
    Iterator<String> iterFileNames = this.openPart.keySet().iterator();
    String lastFile = null;
    if (iterFileNames.hasNext()) {
      lastFile = iterFileNames.next();
      partNumber = this.openPart.get(lastFile);
    }
    return getPartFileName(lastFile, partNumber.intValue());
  }

  /**
   * This method gets a List of Hive Partitions in which the tuple needs to be
   * written to. Example: If hive partitions are date='2014-12-12',country='USA'
   * then this method returns {"2014-12-12","USA"} The implementation is left to
   * the user.
   *
   * @param tuple
   *          A received tuple to be written to a hive partition.
   * @return ArrayList containing hive partition values.
   */
  public abstract ArrayList<String> getHivePartition(T tuple);

  @Override
  public void endWindow()
  {
    if (isEmptyWindow) {
      countEmptyWindow++;
    }
    if (countEmptyWindow >= maxWindowsWithNoData) {
      String lastFile = getHDFSRollingLastFile();
      rotateCall(lastFile);
      countEmptyWindow = 0;
    }
    super.endWindow();

  }

  public long getMaxWindowsWithNoData()
  {
    return maxWindowsWithNoData;
  }

  public void setMaxWindowsWithNoData(long maxWindowsWithNoData)
  {
    this.maxWindowsWithNoData = maxWindowsWithNoData;
  }

  /*
   * A POJO which is emitted by output port of AbstractFSRollingOutputOperator implementation in DAG.
   * The POJO contains the filename which will not be changed by FSRollingOutputOperator once its emitted.
   * The POJO also contains the hive partitions to which the respective files will be moved.
   */
  public static class FilePartitionMapping
  {
    private String filename;
    private ArrayList<String> partition = new ArrayList<String>();

    public ArrayList<String> getPartition()
    {
      return partition;
    }

    public void setPartition(ArrayList<String> partition)
    {
      this.partition = partition;
    }

    public String getFilename()
    {
      return filename;
    }

    public void setFilename(String filename)
    {
      this.filename = filename;
    }

  }

  private static final Logger logger = LoggerFactory.getLogger(AbstractFSRollingOutputOperator.class);

}


text:
package batch_test

import (
	"fmt"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/batch"
)

var _ time.Duration
var _ strings.Reader
var _ aws.Config

func parseTime(layout, value string) *time.Time {
	t, err := time.Parse(layout, value)
	if err != nil {
		panic(err)
	}
	return &t
}

// To cancel a job
// This example cancels a job with the specified job ID.
func ExampleBatch_CancelJob_shared00() {
	svc := batch.New(session.New())
	input := &batch.CancelJobInput{
		JobId:  aws.String("1d828f65-7a4d-42e8-996d-3b900ed59dc4"),
		Reason: aws.String("Cancelling job."),
	}

	result, err := svc.CancelJob(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// To create a managed EC2 compute environment
// This example creates a managed compute environment with specific C4 instance types
// that are launched on demand. The compute environment is called C4OnDemand.
func ExampleBatch_CreateComputeEnvironment_shared00() {
	svc := batch.New(session.New())
	input := &batch.CreateComputeEnvironmentInput{
		ComputeEnvironmentName: aws.String("C4OnDemand"),
		ComputeResources: &batch.ComputeResource{
			DesiredvCpus: aws.Int64(48),
			Ec2KeyPair:   aws.String("id_rsa"),
			InstanceRole: aws.String("ecsInstanceRole"),
			InstanceTypes: []*string{
				aws.String("c4.large"),
				aws.String("c4.xlarge"),
				aws.String("c4.2xlarge"),
				aws.String("c4.4xlarge"),
				aws.String("c4.8xlarge"),
			},
			MaxvCpus: aws.Int64(128),
			MinvCpus: aws.Int64(0),
			SecurityGroupIds: []*string{
				aws.String("sg-cf5093b2"),
			},
			Subnets: []*string{
				aws.String("subnet-220c0e0a"),
				aws.String("subnet-1a95556d"),
				aws.String("subnet-978f6dce"),
			},
			Tags: map[string]*string{
				"Name": aws.String("Batch Instance - C4OnDemand"),
			},
			Type: aws.String("EC2"),
		},
		ServiceRole: aws.String("arn:aws:iam::012345678910:role/AWSBatchServiceRole"),
		State:       aws.String("ENABLED"),
		Type:        aws.String("MANAGED"),
	}

	result, err := svc.CreateComputeEnvironment(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// To create a managed EC2 Spot compute environment
// This example creates a managed compute environment with the M4 instance type that
// is launched when the Spot bid price is at or below 20% of the On-Demand price for
// the instance type. The compute environment is called M4Spot.
func ExampleBatch_CreateComputeEnvironment_shared01() {
	svc := batch.New(session.New())
	input := &batch.CreateComputeEnvironmentInput{
		ComputeEnvironmentName: aws.String("M4Spot"),
		ComputeResources: &batch.ComputeResource{
			BidPercentage: aws.Int64(20),
			DesiredvCpus:  aws.Int64(4),
			Ec2KeyPair:    aws.String("id_rsa"),
			InstanceRole:  aws.String("ecsInstanceRole"),
			InstanceTypes: []*string{
				aws.String("m4"),
			},
			MaxvCpus: aws.Int64(128),
			MinvCpus: aws.Int64(0),
			SecurityGroupIds: []*string{
				aws.String("sg-cf5093b2"),
			},
			SpotIamFleetRole: aws.String("arn:aws:iam::012345678910:role/aws-ec2-spot-fleet-role"),
			Subnets: []*string{
				aws.String("subnet-220c0e0a"),
				aws.String("subnet-1a95556d"),
				aws.String("subnet-978f6dce"),
			},
			Tags: map[string]*string{
				"Name": aws.String("Batch Instance - M4Spot"),
			},
			Type: aws.String("SPOT"),
		},
		ServiceRole: aws.String("arn:aws:iam::012345678910:role/AWSBatchServiceRole"),
		State:       aws.String("ENABLED"),
		Type:        aws.String("MANAGED"),
	}

	result, err := svc.CreateComputeEnvironment(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// To create a job queue with a single compute environment
// This example creates a job queue called LowPriority that uses the M4Spot compute
// environment.
func ExampleBatch_CreateJobQueue_shared00() {
	svc := batch.New(session.New())
	input := &batch.CreateJobQueueInput{
		ComputeEnvironmentOrder: []*batch.ComputeEnvironmentOrder{
			{
				ComputeEnvironment: aws.String("M4Spot"),
				Order:              aws.Int64(1),
			},
		},
		JobQueueName: aws.String("LowPriority"),
		Priority:     aws.Int64(1),
		State:        aws.String("ENABLED"),
	}

	result, err := svc.CreateJobQueue(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// To create a job queue with multiple compute environments
// This example creates a job queue called HighPriority that uses the C4OnDemand compute
// environment with an order of 1 and the M4Spot compute environment with an order of
// 2.
func ExampleBatch_CreateJobQueue_shared01() {
	svc := batch.New(session.New())
	input := &batch.CreateJobQueueInput{
		ComputeEnvironmentOrder: []*batch.ComputeEnvironmentOrder{
			{
				ComputeEnvironment: aws.String("C4OnDemand"),
				Order:              aws.Int64(1),
			},
			{
				ComputeEnvironment: aws.String("M4Spot"),
				Order:              aws.Int64(2),
			},
		},
		JobQueueName: aws.String("HighPriority"),
		Priority:     aws.Int64(10),
		State:        aws.String("ENABLED"),
	}

	result, err := svc.CreateJobQueue(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// To delete a compute environment
// This example deletes the P2OnDemand compute environment.
func ExampleBatch_DeleteComputeEnvironment_shared00() {
	svc := batch.New(session.New())
	input := &batch.DeleteComputeEnvironmentInput{
		ComputeEnvironment: aws.String("P2OnDemand"),
	}

	result, err := svc.DeleteComputeEnvironment(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// To delete a job queue
// This example deletes the GPGPU job queue.
func ExampleBatch_DeleteJobQueue_shared00() {
	svc := batch.New(session.New())
	input := &batch.DeleteJobQueueInput{
		JobQueue: aws.String("GPGPU"),
	}

	result, err := svc.DeleteJobQueue(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// To deregister a job definition
// This example deregisters a job definition called sleep10.
func ExampleBatch_DeregisterJobDefinition_shared00() {
	svc := batch.New(session.New())
	input := &batch.DeregisterJobDefinitionInput{
		JobDefinition: aws.String("sleep10"),
	}

	result, err := svc.DeregisterJobDefinition(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// To describe a compute environment
// This example describes the P2OnDemand compute environment.
func ExampleBatch_DescribeComputeEnvironments_shared00() {
	svc := batch.New(session.New())
	input := &batch.DescribeComputeEnvironmentsInput{
		ComputeEnvironments: []*string{
			aws.String("P2OnDemand"),
		},
	}

	result, err := svc.DescribeComputeEnvironments(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// To describe active job definitions
// This example describes all of your active job definitions.
func ExampleBatch_DescribeJobDefinitions_shared00() {
	svc := batch.New(session.New())
	input := &batch.DescribeJobDefinitionsInput{
		Status: aws.String("ACTIVE"),
	}

	result, err := svc.DescribeJobDefinitions(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// To describe a job queue
// This example describes the HighPriority job queue.
func ExampleBatch_DescribeJobQueues_shared00() {
	svc := batch.New(session.New())
	input := &batch.DescribeJobQueuesInput{
		JobQueues: []*string{
			aws.String("HighPriority"),
		},
	}

	result, err := svc.DescribeJobQueues(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// To describe a specific job
// This example describes a job with the specified job ID.
func ExampleBatch_DescribeJobs_shared00() {
	svc := batch.New(session.New())
	input := &batch.DescribeJobsInput{
		Jobs: []*string{
			aws.String("24fa2d7a-64c4-49d2-8b47-f8da4fbde8e9"),
		},
	}

	result, err := svc.DescribeJobs(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// To list running jobs
// This example lists the running jobs in the HighPriority job queue.
func ExampleBatch_ListJobs_shared00() {
	svc := batch.New(session.New())
	input := &batch.ListJobsInput{
		JobQueue: aws.String("HighPriority"),
	}

	result, err := svc.ListJobs(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// To list submitted jobs
// This example lists jobs in the HighPriority job queue that are in the SUBMITTED job
// status.
func ExampleBatch_ListJobs_shared01() {
	svc := batch.New(session.New())
	input := &batch.ListJobsInput{
		JobQueue:  aws.String("HighPriority"),
		JobStatus: aws.String("SUBMITTED"),
	}

	result, err := svc.ListJobs(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// ListTagsForResource Example
// This demonstrates calling the ListTagsForResource action.
func ExampleBatch_ListTagsForResource_shared00() {
	svc := batch.New(session.New())
	input := &batch.ListTagsForResourceInput{
		ResourceArn: aws.String("arn:aws:batch:us-east-1:123456789012:job-definition/sleep30:1"),
	}

	result, err := svc.ListTagsForResource(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// To register a job definition
// This example registers a job definition for a simple container job.
func ExampleBatch_RegisterJobDefinition_shared00() {
	svc := batch.New(session.New())
	input := &batch.RegisterJobDefinitionInput{
		ContainerProperties: &batch.ContainerProperties{
			Command: []*string{
				aws.String("sleep"),
				aws.String("10"),
			},
			Image: aws.String("busybox"),
			ResourceRequirements: []*batch.ResourceRequirement{
				{
					Type:  aws.String("MEMORY"),
					Value: aws.String("128"),
				},
				{
					Type:  aws.String("VCPU"),
					Value: aws.String("1"),
				},
			},
		},
		JobDefinitionName: aws.String("sleep10"),
		Type:              aws.String("container"),
	}

	result, err := svc.RegisterJobDefinition(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// RegisterJobDefinition with tags
// This demonstrates calling the RegisterJobDefinition action, including tags.
func ExampleBatch_RegisterJobDefinition_shared01() {
	svc := batch.New(session.New())
	input := &batch.RegisterJobDefinitionInput{
		ContainerProperties: &batch.ContainerProperties{
			Command: []*string{
				aws.String("sleep"),
				aws.String("30"),
			},
			Image: aws.String("busybox"),
			ResourceRequirements: []*batch.ResourceRequirement{
				{
					Type:  aws.String("MEMORY"),
					Value: aws.String("128"),
				},
				{
					Type:  aws.String("VCPU"),
					Value: aws.String("1"),
				},
			},
		},
		JobDefinitionName: aws.String("sleep30"),
		Tags: map[string]*string{
			"Department": aws.String("Engineering"),
			"User":       aws.String("JaneDoe"),
		},
		Type: aws.String("container"),
	}

	result, err := svc.RegisterJobDefinition(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// To submit a job to a queue
// This example submits a simple container job called example to the HighPriority job
// queue.
func ExampleBatch_SubmitJob_shared00() {
	svc := batch.New(session.New())
	input := &batch.SubmitJobInput{
		JobDefinition: aws.String("sleep60"),
		JobName:       aws.String("example"),
		JobQueue:      aws.String("HighPriority"),
	}

	result, err := svc.SubmitJob(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// TagResource Example
// This demonstrates calling the TagResource action.
func ExampleBatch_TagResource_shared00() {
	svc := batch.New(session.New())
	input := &batch.TagResourceInput{
		ResourceArn: aws.String("arn:aws:batch:us-east-1:123456789012:job-definition/sleep30:1"),
		Tags: map[string]*string{
			"Stage": aws.String("Alpha"),
		},
	}

	result, err := svc.TagResource(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// To terminate a job
// This example terminates a job with the specified job ID.
func ExampleBatch_TerminateJob_shared00() {
	svc := batch.New(session.New())
	input := &batch.TerminateJobInput{
		JobId:  aws.String("61e743ed-35e4-48da-b2de-5c8333821c84"),
		Reason: aws.String("Terminating job."),
	}

	result, err := svc.TerminateJob(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// UntagResource Example
// This demonstrates calling the UntagResource action.
func ExampleBatch_UntagResource_shared00() {
	svc := batch.New(session.New())
	input := &batch.UntagResourceInput{
		ResourceArn: aws.String("arn:aws:batch:us-east-1:123456789012:job-definition/sleep30:1"),
		TagKeys: []*string{
			aws.String("Stage"),
		},
	}

	result, err := svc.UntagResource(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// To update a compute environment
// This example disables the P2OnDemand compute environment so it can be deleted.
func ExampleBatch_UpdateComputeEnvironment_shared00() {
	svc := batch.New(session.New())
	input := &batch.UpdateComputeEnvironmentInput{
		ComputeEnvironment: aws.String("P2OnDemand"),
		State:              aws.String("DISABLED"),
	}

	result, err := svc.UpdateComputeEnvironment(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}

// To update a job queue
// This example disables a job queue so that it can be deleted.
func ExampleBatch_UpdateJobQueue_shared00() {
	svc := batch.New(session.New())
	input := &batch.UpdateJobQueueInput{
		JobQueue: aws.String("GPGPU"),
		State:    aws.String("DISABLED"),
	}

	result, err := svc.UpdateJobQueue(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case batch.ErrCodeClientException:
				fmt.Println(batch.ErrCodeClientException, aerr.Error())
			case batch.ErrCodeServerException:
				fmt.Println(batch.ErrCodeServerException, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	fmt.Println(result)
}