text:
import iPXSettings
from iPXTools import *

iPXSettings.progName = 'iPodderX'
for arg in sys.argv:
	if re.search('-progName', arg, re.IGNORECASE):
		progNameSplit = arg.split('==')
		iPXSettings.progName = progNameSplit[len(progNameSplit)-1]
iPXSettings.initSettings()

def usage():
	print '\r\nUsage: none really... It just swaps two files'
	#print '\r\nUsage:\r\n%s -d <textToDecrypt>\r\n%s -e <textToEncrypt>\r\n' % (sys.argv[0],sys.argv[0])

try:
	if sys.argv[1] == '-d':
		print decrypt(sys.argv[2].strip())
	elif sys.argv[1] == '-e':
		print encrypt(sys.argv[2].strip())
	else:
		usage()
except Exception, msg:
	print msg
	usage()

redpajama_set_name: RedPajamaGithub


text:
  Perriers-la-Campagne est
       un village
       situé dans le département de l'Eure en Haute-Normandie. Elle totalisait 334 habitants en 2008.

La ville propose quelques  équipements, elle dispose, entre autres, de une boucle de randonnée.

Si vous envisagez de emmenager à Perriers-la-Campagne, vous pourrez facilement trouver une maison à acheter.

Le nombre d'habitations, à Perriers-la-Campagne, était réparti en 2011 en zero appartements et 153 maisons soit
 un marché plutôt équilibré.

À proximité de Perriers-la-Campagne sont situées les villes de
Fontaine-la-Soret à 4 km, 387 habitants,
Rouge-Perriers située à 4 km, 243 habitants,
Nassandres à 3 km, 1 387 habitants,
Thibouville située à 1 km, 258 habitants,
Launay située à 4 km, 215 habitants,
La Haye-de-Calleville située à 4 km, 269 habitants,
 entre autres. De plus, Perriers-la-Campagne est située à seulement 29 km de Louviers.


text:
var timer = null;
var offset = 5000;
var index = 0;

function slideImage(i){
    var id = 'image_'+ target[i];
    $('#'+ id)
        .animate({opacity: 1}, 800, function(){
            $(this).find('.word').animate({height: 'show'}, 'slow');
        }).show()
        .siblings(':visible')
        .find('.word').animate({height: 'hide'},'fast',function(){
            $(this).parent().animate({opacity: 0}, 800).hide();
        });
}
//bind thumb a
function hookThumb(){
    $('#thumbs li a')
        .bind('click', function(){
            if (timer) {
                clearTimeout(timer);
            }
            var id = this.id;
            index = getIndex(id.substr(6));
            rechange(index);
            slideImage(index);
            timer = window.setTimeout(auto, offset);
            this.blur();
            return false;
        });
}
//bind next/prev img
function hookBtn(){
    $('#thumbs li img').filter('#play_prev,#play_next')
        .bind('click', function(){
            if (timer){
                clearTimeout(timer);
            }
            var id = this.id;
            if (id == 'play_prev') {
                index--;
                if (index < 0) index = 6;
            }else{
                index++;
                if (index > 6) index = 0;
            }
            rechange(index);
            slideImage(index);
            timer = window.setTimeout(auto, offset);
        });
}

function bighookBtn(){
    $('#bigpicarea p span').filter('#big_play_prev,#big_play_next')
        .bind('click', function(){
            if (timer){
                clearTimeout(timer);
            }
            var id = this.id;
            if (id == 'big_play_prev') {
                index--;
                if (index < 0) index = 6;
            }else{
                index++;
                if (index > 6) index = 0;
            }
            rechange(index);
            slideImage(index);
            timer = window.setTimeout(auto, offset);
        });
}

//get index
function getIndex(v){
    for(var i=0; i < target.length; i++){
        if (target[i] == v) return i;
    }
}
function rechange(loop){
    var id = 'thumb_'+ target[loop];
    $('#thumbs li a.current').removeClass('current');
    $('#'+ id).addClass('current');
}
function auto(){
    index++;
    if (index > 6){
        index = 0;
    }
    rechange(index);
    slideImage(index);
    timer = window.setTimeout(auto, offset);
}
$(function(){
    //change opacity
    $('div.word').css({opacity: 0.85});
    auto();
    hookThumb();
    hookBtn();
	bighookBtn()

});


text:
"""Daily report command that send email"""

import os
import pytz
import logging
import dateutil.parser
from datetime import timedelta, datetime
from smtplib import SMTPAuthenticationError
from django.utils import timezone
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from timevortex.models import get_sender_email, get_sender_password, get_target_email, get_next_send_daily_report
from timevortex.models import get_last_time_daily_report, create_last_time_daily_report
from timevortex.utils.commands import AbstractCommand
from timevortex.utils.filestorage import FILE_STORAGE_SPACE
from timevortex.utils.globals import ERROR_MISSING_SENDER_EMAIL, KEY_EMAIL_HOST_USER, ERROR_SMTP_AUTH, ERROR_TIMEVORTEX
from timevortex.utils.globals import ERROR_MISSING_SENDER_PASSWORD, KEY_EMAIL_HOST_PASSWORD, ERROR_MISSING_TARGET_EMAIL
from timevortex.utils.globals import ERROR_MISSING_NEXT_SEND, LABEL_LAST_TIME_DAILY_REPORT, KEY_LAST_TIME_DAILY_REPORT

# Data storage
LOGGER = logging.getLogger("timevortex")

# Email sender
KEY_DEFAULT_FROM_EMAIL = "DEFAULT_FROM_EMAIL"
DEFAULT_DEFAULT_FROM_EMAIL = "Timevortex <%s@gmail.com>"

# Emaill template
FILE_EMAIL_SUBJECT = "emails/daily_report/subject.txt"
FILE_EMAIL_BODY_TXT = "emails/daily_report/full.txt"
FILE_EMAIL_BODY_HTML = "emails/daily_report/full.html"

# KEY
KEY_REPORT_NAME = "name"
KEY_REPORT_ERROR_NUMBERS = "errorNumbers"
KEY_REPORT_SERIES_NUMBERS = "seriesNumbers"

def collect_free_space():
    """This method collect free space on disk.

    :returns: str -- Str containing free space.

    """
    temp_file = "/tmp/freespace.log"
    os.system('df -h / > %s' % temp_file)
    file_desc = open(temp_file, 'r')
    free = file_desc.readlines()
    file_desc.close()
    free = ''.join(free)
    return free[:-1].replace("\n", "<br/>")

def get_sites_information(day_date):
    """Get site information
    """
    sites = []
    sites_list = FILE_STORAGE_SPACE.get_sites_list()
    for site_id in sites_list:
        site_info = {
            KEY_REPORT_NAME: site_id,
            KEY_REPORT_ERROR_NUMBERS: FILE_STORAGE_SPACE.get_number_of_error(site_id, day_date),
            KEY_REPORT_SERIES_NUMBERS: FILE_STORAGE_SPACE.get_number_of_series(site_id, day_date)
        }
        sites.append(site_info)

    return sites

class Command(AbstractCommand):
    """Command class

        Test cases:
            * No sender_email in DB => log error ERROR_MISSING_SENDER_EMAIL
            * No sender_password in DB => log error ERROR_MISSING_SENDER_PASSWORD
            * Bad SMTP authentication => log error ERROR_SMTP_AUTH
    """

    help = "Daily report command that send email"
    name = "daily report command"
    logger = LOGGER
    sleep_time = 300
    sender_email = None
    sender_password = None

    def send_daily_report_email(self, emails, report):
        """Send daily report email
        """
        subject = render_to_string(FILE_EMAIL_SUBJECT, report)
        body = render_to_string(FILE_EMAIL_BODY_TXT, report)
        body_html = render_to_string(FILE_EMAIL_BODY_HTML, report)
        header_email = DEFAULT_DEFAULT_FROM_EMAIL % self.sender_email.value

        msg = EmailMultiAlternatives(subject, body, header_email, emails)
        msg.attach_alternative(body_html, "text/html")
        msg.content_subtype = "plain"
        try:
            msg.send()
        except SMTPAuthenticationError:
            error_msg = ERROR_TIMEVORTEX[ERROR_SMTP_AUTH] % (self.sender_email.value, self.sender_password)
            self.logger.error(error_msg)

    def run(self, *args, **options):
        """ Run
        """
        now = timezone.now()
        self.sender_email = get_sender_email()
        self.sender_password = get_sender_password()
        target_email = get_target_email()
        next_send_daily_report = get_next_send_daily_report()
        last_time_daily_report = get_last_time_daily_report()
        last_time_daily_report_datetime = dateutil.parser.parse(last_time_daily_report.value).replace(
            tzinfo=pytz.UTC)

        if self.sender_email is None:
            self.logger.error(ERROR_TIMEVORTEX[ERROR_MISSING_SENDER_EMAIL])
            return
        elif self.sender_password is None:
            self.logger.error(ERROR_TIMEVORTEX[ERROR_MISSING_SENDER_PASSWORD])
            return
        elif target_email is None:
            self.logger.error(ERROR_TIMEVORTEX[ERROR_MISSING_TARGET_EMAIL])
            return
        elif next_send_daily_report is None:
            self.logger.error(ERROR_TIMEVORTEX[ERROR_MISSING_NEXT_SEND])
            return
        elif last_time_daily_report_datetime is None:
            last_time_daily_report_datetime = (datetime.now() - timedelta(days=1)).replace(hour=4, minute=0,
                                                                                second=0, microsecond=0)
            create_last_time_daily_report(LABEL_LAST_TIME_DAILY_REPORT, KEY_LAST_TIME_DAILY_REPORT,
                                          last_time_daily_report_datetime)

        setattr(settings, KEY_EMAIL_HOST_USER, self.sender_email.value)
        setattr(settings, KEY_EMAIL_HOST_PASSWORD, self.sender_password.value)

        if now >= last_time_daily_report_datetime + timedelta(seconds=int(next_send_daily_report.value)):

            # get last_time_daily_report from DB
            day_date = (timezone.now() - timedelta(days=1))
            report = {
                "yesterday_date": day_date.strftime("%d-%m-%Y"),
                "free_space": collect_free_space(),
                "sites": get_sites_information(day_date.strftime("%Y-%m-%d"))
            }

            emails = [target_email.value]

            self.send_daily_report_email(emails, report)

            last_time_daily_report.value = now
            last_time_daily_report.save()


text:
export class Container {
  selector: string;

  top: number;
  right: number;
  bottom: number;
  left: number;

  width: number;
  height: number;

  constructor(selector: string, top?: number, right?: number, bottom?: number, left?: number, width?: number, height?: number) {
    this.selector = selector;

    this.top = top || 0;
    this.right = right || 0;
    this.bottom = bottom || 0;
    this.left = left || 0;

    this.width = width || 0;
    this.height = height || 0;
  }
}


text:
using System;

namespace Project17
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Revta Period. Lav. Regia Accad. Sci. , Padova 5: 69 (1857)

#### Original name
Bayrhofferia Trevis.

### Remarks
null


text:
namespace Demo.Pipeline.CommandUI
{
    public class Patient
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Kinect;

namespace Rotate3D {
    /// <summary>
    /// Contains static extension methods for use with the Kinect SDK.
    /// </summary>
    public static class KinectExtensions {
        /// <summary>
        /// Finds whether the skeleton has its left arm at a 45 degree angle and its right arm at its side (similar to Xbox guide position).
        /// </summary>
        /// <param name="skeleton">(extension) the skeleton to analyze</param>
        /// <returns>whether the skeleton is in the guide position</returns>
        public static bool IsInGuidePosition(this Skeleton skeleton) {
            SkeletonPoint
                shoulderLeft  = skeleton.Joints[JointType.ShoulderLeft].Position,
                shoulderRight = skeleton.Joints[JointType.ShoulderRight].Position,
                handLeft      = skeleton.Joints[JointType.HandLeft].Position,
                handRight     = skeleton.Joints[JointType.HandRight].Position;

            // Similar distances between left shoulder and left hand on axes (45 degrees) and
            //  left shoulder above left hand and
            //  right shoulder above right hand
            return
                Math.Abs((shoulderLeft.X - handLeft.X) - (shoulderLeft.Y - handLeft.Y)) < 0.2 &&
                Math.Abs(shoulderLeft.Z  - handLeft.Z)  < 0.25 &&
                Math.Abs(shoulderRight.X - handRight.X) < 0.1 && Math.Abs(shoulderRight.Z - handRight.Z) < 0.25;
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JSDoc: Source: index.js</title>

    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">

Source: index.js

'use strict';

module.exports = function (periodic) {
	// express,app,logger,config/settings,db
	var adminRouter = periodic.express.Router(),
		periodicRouter = periodic.express.Router(),
		authController = require('../periodicjs.ext.login/controller/auth')(periodic),
		userroleController = require('./controller/userrole')(periodic),
		uacController = require('./controller/uac')(periodic);

	adminRouter.all('*', authController.ensureAuthenticated, uacController.loadUserRoles, uacController.check_user_access);

	//user roles
	adminRouter.get('/userroles', uacController.loadUserAccesControls, userroleController.index);
	adminRouter.get('/userrole/new', userroleController.userrole_new);
	adminRouter.get('/userrole/:id', uacController.loadUserrole, userroleController.show);
	adminRouter.get('/userrole/edit/:id', uacController.loadUserrole, userroleController.show);
	adminRouter.post('/userrole/new', userroleController.create);
	adminRouter.post('/userrole/edit', userroleController.update);
	adminRouter.post('/userrole/:id/delete', uacController.loadUserrole, userroleController.remove);
	periodicRouter.get('/userroles/search.:ext', uacController.loadUserroles, uacController.userroleSearchResults);
	periodicRouter.get('/userroles/search', uacController.loadUserroles, uacController.userroleSearchResults);

	//user priviliges
	periodicRouter.get('/userprivileges/search.:ext', uacController.loadUserprivileges, uacController.userprivilegeSearchResults);
	periodicRouter.get('/userprivileges/search', uacController.loadUserprivileges, uacController.userprivilegeSearchResults);

	//add routes
	periodic.app.use('/p-admin', adminRouter);
	periodic.app.use(periodicRouter);
};

Index

Modules

uacController

userroleController

user_access_control

    Documentation generated by JSDoc 3.2.2 on Sun Oct 12 2014 19:22:27 GMT-0400 (EDT)


text:
package com.wut.datasources.jdbc.derby;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wut.datasources.TableRowSource;
import com.wut.datasources.jdbc.ResultSetListHelper;
import com.wut.datasources.jdbc.SqlStatementHelper;
import com.wut.format.Decoder;
import com.wut.format.FormatFactory;
import com.wut.format.Formatter;
import com.wut.format.json.JsonDecoder;
import com.wut.model.Data;
import com.wut.model.map.MappedData;
import com.wut.support.ErrorHandler;
import com.wut.support.logging.WutLogger;

public class Derby implements TableRowSource {
	private static final String DERBY_DB_USERNAME = "derbyuser";
	private static final String DERBY_DB_PASSWORD = "derbyuser";
	public static final String database = "webutilitykit";
	public static final int DERBY_PORT = 1527;

	private static final String dbURL = "jdbc:derby://localhost:" + DERBY_PORT + "/" + database + ";create=true;user=" + DERBY_DB_USERNAME + ";password=" + DERBY_DB_PASSWORD;
	private static final String driver = "org.apache.derby.jdbc.ClientDriver";
	//private static final String connectionString = "jdbc:derby:myDB;create=true;user=me;password=mine";
	//private static final String connectionString = "jdbc:derby:myDB;create=true";
	private static WutLogger log = new WutLogger(Derby.class);
	private static Connection connection;
	//private static boolean initialized = false;
	//private static String dbName="wut";
	//private static String connectionURL = "jdbc:derby:" + dbName + ";create=true";

	public Derby() {
		// SETUP DATA DIRECTORY FOR DERBY
//		String userHomeDir = System.getProperty("user.home", ".");
//		String systemDir = userHomeDir + File.separator + "data";
//		System.setProperty("derby.system.home", systemDir);
//		File fileSystemDir = new File(systemDir);
//		fileSystemDir.mkdir();

//		try {
//			DriverManager.getConnection("jdbc:derby:ContactsManagerDirectory");
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}

		// start derby

		/*
		//String driver = "org.apache.derby.jdbc.EmbeddedDriver";
		try {
		    Class.forName(driver);
		} catch(java.lang.ClassNotFoundException e) {
			log.error("error starting derby");
			ErrorHandler.fatalError(e, "error starting derby");
		}

		// BOOT THE DB
		String connectionURL = "jdbc:derby:" + database + ";create=true";
		try {
		    this.connection = DriverManager.getConnection(connectionString);
		} catch (Throwable e) {
			log.error("error establishing derby connection");
			ErrorHandler.fatalError("error establishing derby connection");
		}
		*/
	}

//	private void start() {
//		//NetworkServerControl serverControl = new NetworkServerControl(InetAddress.getByName("myhost"),1621);
////		serverControl.shutdown();
//	}

	private void checkConnection() {
		if (connection == null) {
			createConnection();
		}
	}

	private synchronized void createConnection()
    {
        try
        {
        	//if (!initialized) {
//        		// DONT THINK NEW INSTANCE IS APPROPRIATE
               // Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
                //Get a connection
                //connection = DriverManager.getConnection(connectionString);

        		Class.forName(driver).newInstance();
        		connection = DriverManager.getConnection(dbURL);

        		try {
	                createTable("webutilitykit", false);
	                createTable("tokens", false);
        		} catch (Exception e) {
        			// fuck that
        		}

                //initialized = true;
        //	}
        }
        catch (SQLException e)
        {
    		if (e.getNextException().getErrorCode() ==  45000) {
    			// derby already running which is ok for us
    			e.printStackTrace();
    		} else {
            	e.printStackTrace();
            }
        } catch (Exception e) {
        	e.printStackTrace();
        }
    }

	private boolean createTable(String name, boolean dropIfExists) throws SQLException {
		checkConnection();

		// CHECK if table exists
		DatabaseMetaData dbm = connection.getMetaData();
		// check if "employee" table is there
		ResultSet tables = dbm.getTables(null, null, name, null);
		boolean tableExists = false;
		if (tables.next()) { // TODO handle case insensitivity of table name (check twice lower and upper case)
			tableExists = true;
		}

		if (tableExists && dropIfExists) {
			// Drop Table
			log.info("Dropping " + name + " table...");
	        Statement dropStmt = connection.createStatement();
	        String dropSql = "DROP TABLE " + name;
	        try {
	        	dropStmt.executeUpdate(dropSql); // TODO use executeDDL
	        } catch (Exception e) {
	        	// eat it
	        	ErrorHandler.fatalError(e, "failed to drop " + name);
	        }
		}

		if (!tableExists || dropIfExists) {
			System.out.println("Creating " + name + " table...");
	        Statement createStmt = connection.createStatement();

	        String createTableSql = "CREATE TABLE " + name + " " +
	                     "(id VARCHAR(255) not NULL, " +
	                     " customer VARCHAR(255), " +
	                     " tablename VARCHAR(255), " +
	                     " updated INTEGER, " +
	                     " created INTEGER, " +
	                     " updator VARCHAR(255), " +
	                     " creator VARCHAR(255), " +
	                     " data LONG VARCHAR, " +
	                     " PRIMARY KEY ( id ))";

	        createStmt.executeUpdate(createTableSql);
	        System.out.println("Created table " + name + "...");
		}

        return true;
	}

//		Statement stmt = dbConnection.createStatement();
//		stmt.execute(strCreateContactsTable);
//
//
//		String createString = "CREATE TABLE WISH_LIST  "
//		  +  "(WISH_ID INT NOT NULL GENERATED ALWAYS AS IDENTITY "
//		  +  " WISH_ITEM VARCHAR(32) NOT NULL) " ;
//
//		// START DERBY ENGINE
//		String driver = "org.apache.derby.jdbc.EmbeddedDriver";
//		...
//		try {
//		    Class.forName(driver);
//		} catch(java.lang.ClassNotFoundException e) {
//		... }
//
//		// BOOT THE DB
//		String connectionURL = "jdbc:derby:" + dbName + ";create=true";
//		...
//		try {
//		    conn = DriverManager.getConnection(connectionURL);
//		... <most of the program code is contained here> } catch (Throwable e) {
//		... }
//
//		// CREATE STATEMENT
//
//		s = conn.createStatement();
//		if (! WwdUtils.wwdChk4Table(conn))
//		{
//		   System.out.println (" . . . . creating table WISH_LIST");
//		   s.execute(createString);
//		}
//
//		psInsert = conn.prepareStatement
//				   ("insert into WISH_LIST(WISH_ITEM) values (?)");
//
//
//		psInsert.setString(1,answer);
//		psInsert.executeUpdate();
//
//		myWishes = s.executeQuery("select ENTRY_DATE, WISH_ITEM
//	               from WISH_LIST order by ENTRY_DATE");" +
//	               		"" +
//	               		";" +
//	               		"";
//
//	               while (myWishes.next())
//	               {
//
//	               System.out.println("On " + myWishes.getTimestamp(1) +
//	                  " I wished for " + myWishes.getString(2));
//	               }
//	}

	public void shutdown() {
		if (driver.equals("org.apache.derby.jdbc.EmbeddedDriver")) { // TODO this check is not needed
			boolean gotSQLExc = false;
			try {
				DriverManager.getConnection("jdbc:derby:;shutdown=true");
			} catch (SQLException se) {
				if (se.getSQLState().equals("XJ015")) {
					gotSQLExc = true;
				}
			}
			if (!gotSQLExc) {
				log.error("Database did not shut down normally");
			} else {
				log.info("Database shut down normally");
			}
		}
	}

	@Override
	public List<Map<String, String>> get(String customer, String application, String tableId) {
		List<Map<String, String>> listOfResults = new ArrayList<Map<String,String>>();

		try {
			String statementStr = SqlStatementHelper.select(tableId);
			ResultSet results = executeQuery(statementStr);
			while (results.next()) {
				//results.getString("_updated");
				String table = results.getString("tablename");

				String data = results.getString("data");
				MappedData mappedData = expandDataIntoMap(data);
				Map<String, String> map = mappedData.getMapAsPojo();

				map.put("_table", String.valueOf(table));

				int updated = results.getInt("updated");
				map.put("_updated", String.valueOf(updated));

				int created = results.getInt("created");
				map.put("_created", String.valueOf(created));

				String customer2 = results.getString("customer");
				map.put("_customer", String.valueOf(customer2));

				String creator = results.getString("creator");
				map.put("_creator", String.valueOf(creator));

				listOfResults.add(map);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return listOfResults;
	}

	@Override
	public List<Map<String, String>> filter(String customer, String application, String tableId,
			Map<String, String> filter) {

		try {
			String statementStr = SqlStatementHelper.select(tableId, filter);
			ResultSet results = executeQuery(statementStr);
			while (results.next()) {
				int updated = results.getInt("_updated");
				int created = results.getInt("_created");
				String owner = results.getString("_owner");
				String data = results.getString("_data");

			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return null;
	}

	@Override
	public Map<String, String> get(String customer, String application, String tableId, String rowId) {
		Map<String, String> conditions = new HashMap<String, String>();
		conditions.put("id", rowId);

		String readSql = SqlStatementHelper.select(tableId, conditions);

		ResultSet resultSet = executeQuery(readSql);

		try {
			List<Map<String,String>> results = ResultSetListHelper.getList(resultSet);
			if (results != null && results.size() < 1) { // < 1 == 0
				return null;
			} else if (results != null) {
				Map<String,String> result = results.get(0);
				String dataResultString = result.get("DATA");
				Map<String,String> dataMap = parseFromString(dataResultString);
				//String resultMapStr = dataMap.get("result");
				//Map<String,String> resultMap = parseFromString(resultMapStr);
				return dataMap;
			}
		} catch (SQLException e) {
			// eat it
		}

		return null;
	}

	@Override
	public boolean remove(String customer, String application, String tableId, String rowId) {

		String deleteSql = SqlStatementHelper.remove(tableId, rowId);
		boolean resultSuccessful = executeDML(deleteSql);

		return resultSuccessful;
	}

	@Override
	public boolean update(String customer, String application, String tableId, String rowId, Map<String, String> data) {
		data.put("id", rowId); // TODO hacky and weird but needed so SqlHelper generates correct sql
		Map<String, String> statementData = convertMapToString(data);
		//statementData.put("id", rowId);
		String updateSql = SqlStatementHelper.update(tableId, statementData);
		boolean resultSuccessful = executeDML(updateSql);

		return resultSuccessful;
	}

	@Override
	public boolean crupdate(String customer, String application, String tableId, String rowId, Map<String, String> data) {
		boolean updated = update(customer, application, tableId, rowId, data);
		if (!updated) {
			//String insertSql = SqlStatementHelper.insert(tableId, rowId, data);
			data.put("id", rowId);
			String id = insert(customer, application, tableId, data);
			return (id != null);
		}

		return updated;
	}

	@Override
	public String insert(String customer, String application, String tableId, Map<String, String> data) {
		Map<String, String> statementData = new HashMap<String, String>();

		convertMapElement("id", data, "id", statementData);
		convertMapElement("_table", data, "tablename", statementData);
		convertMapElement("_updated", data, "updated", statementData);
		convertMapElement("_created", data, "created", statementData);
		convertMapElement("_updator", data, "updator", statementData);
		convertMapElement("_customer", data, "customer", statementData);
		convertMapElement("_updated", data, "updated", statementData);

		String dataAsString = condenseToString(data);
		statementData.put("data", dataAsString);

		String insertSql = SqlStatementHelper.insert(tableId, statementData);
		boolean resultSuccessful = executeDML(insertSql);

		if (resultSuccessful) {
			return data.get("id");
		} else {
			return null;
		}
	}

	// HELPER FUNCTIONS

	private static void convertMapElement(String originalKey, Map<String, String> originalData, String destinationKey, Map<String, String> destinationData) {
		if (originalData.containsKey(originalKey)) {
			String originalValue = originalData.get(originalKey);
			destinationData.put(destinationKey, originalValue);
		}
	}

	private Map<String, String> convertMapToString(String rowId, Map<String, String> data) {
		Map<String, String> statementData = convertMapToString(data);
		statementData.put("id", rowId);
		return statementData;
	}

	private Map<String, String> convertMapToString(Map<String, String> data) {
		Map<String, String> statementData = new HashMap<String, String>();

		convertMapElement("id", data, "id", statementData);
		convertMapElement("_table", data, "tablename", statementData);
		convertMapElement("_updated", data, "updated", statementData);
		convertMapElement("_created", data, "created", statementData);
		convertMapElement("_updator", data, "updator", statementData);
		convertMapElement("_customer", data, "customer", statementData);
		convertMapElement("_updated", data, "updated", statementData);

		String dataAsString = condenseToString(data);
		statementData.put("data", dataAsString);

		return statementData;
	}

	public MappedData expandDataIntoMap(String data) {
		try {
			JsonDecoder decoder = new JsonDecoder();
			MappedData map = (MappedData) decoder.decode(data);
			return map;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new MappedData();
	}

	// TODO name stringify() ?
	public String condenseToString(Map<String,String> data) {
		MappedData mappedData = MappedData.convert(data);

		Formatter encoder = FormatFactory.getDefaultFormatter();
		String encodedMap = encoder.format(mappedData);

		return encodedMap;
	}

	public Map<String,String> parseFromString(String data) {
		try {
			Decoder decoder = FormatFactory.getDefaultDecoder();

			String fuckMyLife = null;
		    if (data.startsWith("{\"result\":")) {
		    	String noStartResult = data.substring(10, data.length()-1);
		    	String noEndResult = noStartResult.substring(0, noStartResult.length());
		    	fuckMyLife = noEndResult;
		    } else {
		    	fuckMyLife = data;
		    }
			Data dataObj = decoder.decode(fuckMyLife);
			MappedData mapData = (MappedData) dataObj;
			Map<String,String> pojoData = mapData.getMapAsPojo();
			return pojoData;
		} catch (IOException e) {
			ErrorHandler.systemError(e, "error parsing data in derby");
			return null;
		}
	}

	// JDBC HELPER FUNCTIONS

	/*
	 * SELECT - retrieve data from the a database
INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the records remain
MERGE - UPSERT operation (insert or update)
CALL - call a PL/SQL or Java subprogram
EXPLAIN PLAN - explain access path to data
LOCK TABLE - control concurrency
	 */
	public boolean executeDML(String statement) {
		checkConnection();
		System.out.println(statement);
		log.debug("Executing SQL: " + statement);
		try {
			Statement stmt = connection.createStatement();
			boolean resultIsResultSet = stmt.execute(statement);
			if (!resultIsResultSet) {
				int updatedCount = stmt.getUpdateCount();
				return updatedCount > 0;
				//return true;
			}
			return false;
		} catch (SQLException e) {
			ErrorHandler.userError(e.getMessage() + " in statement " + statement);
		}
		return false;
	}

	/*
	 * CREATE - to create objects in the database
ALTER - alters the structure of the database
DROP - delete objects from the database
TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
COMMENT - add comments to the data dictionary
RENAME - rename an object
	 */
	public boolean executeDDL(String statement) {
		checkConnection();

		log.debug("Executing SQL: " + statement);
		try {
			Statement stmt = this.connection.createStatement();
			boolean resultIsResultSet = stmt.execute(statement);
			return true;
		} catch (SQLException e) {
			ErrorHandler.userError(e.getMessage() + " in statement " + statement);
		}
		return false;
	}

	public ResultSet executeQuery(String query) {
		checkConnection();

		System.out.println(query);

		log.debug("Executing SQL: " + query);
		try {
			Statement stmt = this.connection.createStatement();
			ResultSet rs = stmt.executeQuery(query);
			return rs;
		} catch (SQLException e) {
			ErrorHandler.userError("error executing sql query " + query, e);
		}
		return null;
	}

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.bigquery.model;

/**
 * Hyperparameter search spaces. These should be a subset of training_options.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the BigQuery API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class HparamSearchSpaces extends com.google.api.client.json.GenericJson {

  /**
   * Activation functions of neural network models.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private StringHparamSearchSpace activationFn;

  /**
   * Mini batch sample size.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private IntHparamSearchSpace batchSize;

  /**
   * Booster type for boosted tree models.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private StringHparamSearchSpace boosterType;

  /**
   * Subsample ratio of columns for each level for boosted tree models.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private DoubleHparamSearchSpace colsampleBylevel;

  /**
   * Subsample ratio of columns for each node(split) for boosted tree models.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private DoubleHparamSearchSpace colsampleBynode;

  /**
   * Subsample ratio of columns when constructing each tree for boosted tree models.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private DoubleHparamSearchSpace colsampleBytree;

  /**
   * Dart normalization type for boosted tree models.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private StringHparamSearchSpace dartNormalizeType;

  /**
   * Dropout probability for dnn model training and boosted tree models using dart booster.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private DoubleHparamSearchSpace dropout;

  /**
   * Hidden units for neural network models.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private IntArrayHparamSearchSpace hiddenUnits;

  /**
   * L1 regularization coefficient.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private DoubleHparamSearchSpace l1Reg;

  /**
   * L2 regularization coefficient.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private DoubleHparamSearchSpace l2Reg;

  /**
   * Learning rate of training jobs.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private DoubleHparamSearchSpace learnRate;

  /**
   * Maximum depth of a tree for boosted tree models.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private IntHparamSearchSpace maxTreeDepth;

  /**
   * Minimum split loss for boosted tree models.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private DoubleHparamSearchSpace minSplitLoss;

  /**
   * Minimum sum of instance weight needed in a child for boosted tree models.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private IntHparamSearchSpace minTreeChildWeight;

  /**
   * Number of clusters for k-means.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private IntHparamSearchSpace numClusters;

  /**
   * Number of latent factors to train on.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private IntHparamSearchSpace numFactors;

  /**
   * Number of parallel trees for boosted tree models.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private IntHparamSearchSpace numParallelTree;

  /**
   * Optimizer of TF models.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private StringHparamSearchSpace optimizer;

  /**
   * Subsample the training data to grow tree to prevent overfitting for boosted tree models.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private DoubleHparamSearchSpace subsample;

  /**
   * Tree construction algorithm for boosted tree models.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private StringHparamSearchSpace treeMethod;

  /**
   * Hyperparameter for matrix factoration when implicit feedback type is specified.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private DoubleHparamSearchSpace walsAlpha;

  /**
   * Activation functions of neural network models.
   * @return value or {@code null} for none
   */
  public StringHparamSearchSpace getActivationFn() {
    return activationFn;
  }

  /**
   * Activation functions of neural network models.
   * @param activationFn activationFn or {@code null} for none
   */
  public HparamSearchSpaces setActivationFn(StringHparamSearchSpace activationFn) {
    this.activationFn = activationFn;
    return this;
  }

  /**
   * Mini batch sample size.
   * @return value or {@code null} for none
   */
  public IntHparamSearchSpace getBatchSize() {
    return batchSize;
  }

  /**
   * Mini batch sample size.
   * @param batchSize batchSize or {@code null} for none
   */
  public HparamSearchSpaces setBatchSize(IntHparamSearchSpace batchSize) {
    this.batchSize = batchSize;
    return this;
  }

  /**
   * Booster type for boosted tree models.
   * @return value or {@code null} for none
   */
  public StringHparamSearchSpace getBoosterType() {
    return boosterType;
  }

  /**
   * Booster type for boosted tree models.
   * @param boosterType boosterType or {@code null} for none
   */
  public HparamSearchSpaces setBoosterType(StringHparamSearchSpace boosterType) {
    this.boosterType = boosterType;
    return this;
  }

  /**
   * Subsample ratio of columns for each level for boosted tree models.
   * @return value or {@code null} for none
   */
  public DoubleHparamSearchSpace getColsampleBylevel() {
    return colsampleBylevel;
  }

  /**
   * Subsample ratio of columns for each level for boosted tree models.
   * @param colsampleBylevel colsampleBylevel or {@code null} for none
   */
  public HparamSearchSpaces setColsampleBylevel(DoubleHparamSearchSpace colsampleBylevel) {
    this.colsampleBylevel = colsampleBylevel;
    return this;
  }

  /**
   * Subsample ratio of columns for each node(split) for boosted tree models.
   * @return value or {@code null} for none
   */
  public DoubleHparamSearchSpace getColsampleBynode() {
    return colsampleBynode;
  }

  /**
   * Subsample ratio of columns for each node(split) for boosted tree models.
   * @param colsampleBynode colsampleBynode or {@code null} for none
   */
  public HparamSearchSpaces setColsampleBynode(DoubleHparamSearchSpace colsampleBynode) {
    this.colsampleBynode = colsampleBynode;
    return this;
  }

  /**
   * Subsample ratio of columns when constructing each tree for boosted tree models.
   * @return value or {@code null} for none
   */
  public DoubleHparamSearchSpace getColsampleBytree() {
    return colsampleBytree;
  }

  /**
   * Subsample ratio of columns when constructing each tree for boosted tree models.
   * @param colsampleBytree colsampleBytree or {@code null} for none
   */
  public HparamSearchSpaces setColsampleBytree(DoubleHparamSearchSpace colsampleBytree) {
    this.colsampleBytree = colsampleBytree;
    return this;
  }

  /**
   * Dart normalization type for boosted tree models.
   * @return value or {@code null} for none
   */
  public StringHparamSearchSpace getDartNormalizeType() {
    return dartNormalizeType;
  }

  /**
   * Dart normalization type for boosted tree models.
   * @param dartNormalizeType dartNormalizeType or {@code null} for none
   */
  public HparamSearchSpaces setDartNormalizeType(StringHparamSearchSpace dartNormalizeType) {
    this.dartNormalizeType = dartNormalizeType;
    return this;
  }

  /**
   * Dropout probability for dnn model training and boosted tree models using dart booster.
   * @return value or {@code null} for none
   */
  public DoubleHparamSearchSpace getDropout() {
    return dropout;
  }

  /**
   * Dropout probability for dnn model training and boosted tree models using dart booster.
   * @param dropout dropout or {@code null} for none
   */
  public HparamSearchSpaces setDropout(DoubleHparamSearchSpace dropout) {
    this.dropout = dropout;
    return this;
  }

  /**
   * Hidden units for neural network models.
   * @return value or {@code null} for none
   */
  public IntArrayHparamSearchSpace getHiddenUnits() {
    return hiddenUnits;
  }

  /**
   * Hidden units for neural network models.
   * @param hiddenUnits hiddenUnits or {@code null} for none
   */
  public HparamSearchSpaces setHiddenUnits(IntArrayHparamSearchSpace hiddenUnits) {
    this.hiddenUnits = hiddenUnits;
    return this;
  }

  /**
   * L1 regularization coefficient.
   * @return value or {@code null} for none
   */
  public DoubleHparamSearchSpace getL1Reg() {
    return l1Reg;
  }

  /**
   * L1 regularization coefficient.
   * @param l1Reg l1Reg or {@code null} for none
   */
  public HparamSearchSpaces setL1Reg(DoubleHparamSearchSpace l1Reg) {
    this.l1Reg = l1Reg;
    return this;
  }

  /**
   * L2 regularization coefficient.
   * @return value or {@code null} for none
   */
  public DoubleHparamSearchSpace getL2Reg() {
    return l2Reg;
  }

  /**
   * L2 regularization coefficient.
   * @param l2Reg l2Reg or {@code null} for none
   */
  public HparamSearchSpaces setL2Reg(DoubleHparamSearchSpace l2Reg) {
    this.l2Reg = l2Reg;
    return this;
  }

  /**
   * Learning rate of training jobs.
   * @return value or {@code null} for none
   */
  public DoubleHparamSearchSpace getLearnRate() {
    return learnRate;
  }

  /**
   * Learning rate of training jobs.
   * @param learnRate learnRate or {@code null} for none
   */
  public HparamSearchSpaces setLearnRate(DoubleHparamSearchSpace learnRate) {
    this.learnRate = learnRate;
    return this;
  }

  /**
   * Maximum depth of a tree for boosted tree models.
   * @return value or {@code null} for none
   */
  public IntHparamSearchSpace getMaxTreeDepth() {
    return maxTreeDepth;
  }

  /**
   * Maximum depth of a tree for boosted tree models.
   * @param maxTreeDepth maxTreeDepth or {@code null} for none
   */
  public HparamSearchSpaces setMaxTreeDepth(IntHparamSearchSpace maxTreeDepth) {
    this.maxTreeDepth = maxTreeDepth;
    return this;
  }

  /**
   * Minimum split loss for boosted tree models.
   * @return value or {@code null} for none
   */
  public DoubleHparamSearchSpace getMinSplitLoss() {
    return minSplitLoss;
  }

  /**
   * Minimum split loss for boosted tree models.
   * @param minSplitLoss minSplitLoss or {@code null} for none
   */
  public HparamSearchSpaces setMinSplitLoss(DoubleHparamSearchSpace minSplitLoss) {
    this.minSplitLoss = minSplitLoss;
    return this;
  }

  /**
   * Minimum sum of instance weight needed in a child for boosted tree models.
   * @return value or {@code null} for none
   */
  public IntHparamSearchSpace getMinTreeChildWeight() {
    return minTreeChildWeight;
  }

  /**
   * Minimum sum of instance weight needed in a child for boosted tree models.
   * @param minTreeChildWeight minTreeChildWeight or {@code null} for none
   */
  public HparamSearchSpaces setMinTreeChildWeight(IntHparamSearchSpace minTreeChildWeight) {
    this.minTreeChildWeight = minTreeChildWeight;
    return this;
  }

  /**
   * Number of clusters for k-means.
   * @return value or {@code null} for none
   */
  public IntHparamSearchSpace getNumClusters() {
    return numClusters;
  }

  /**
   * Number of clusters for k-means.
   * @param numClusters numClusters or {@code null} for none
   */
  public HparamSearchSpaces setNumClusters(IntHparamSearchSpace numClusters) {
    this.numClusters = numClusters;
    return this;
  }

  /**
   * Number of latent factors to train on.
   * @return value or {@code null} for none
   */
  public IntHparamSearchSpace getNumFactors() {
    return numFactors;
  }

  /**
   * Number of latent factors to train on.
   * @param numFactors numFactors or {@code null} for none
   */
  public HparamSearchSpaces setNumFactors(IntHparamSearchSpace numFactors) {
    this.numFactors = numFactors;
    return this;
  }

  /**
   * Number of parallel trees for boosted tree models.
   * @return value or {@code null} for none
   */
  public IntHparamSearchSpace getNumParallelTree() {
    return numParallelTree;
  }

  /**
   * Number of parallel trees for boosted tree models.
   * @param numParallelTree numParallelTree or {@code null} for none
   */
  public HparamSearchSpaces setNumParallelTree(IntHparamSearchSpace numParallelTree) {
    this.numParallelTree = numParallelTree;
    return this;
  }

  /**
   * Optimizer of TF models.
   * @return value or {@code null} for none
   */
  public StringHparamSearchSpace getOptimizer() {
    return optimizer;
  }

  /**
   * Optimizer of TF models.
   * @param optimizer optimizer or {@code null} for none
   */
  public HparamSearchSpaces setOptimizer(StringHparamSearchSpace optimizer) {
    this.optimizer = optimizer;
    return this;
  }

  /**
   * Subsample the training data to grow tree to prevent overfitting for boosted tree models.
   * @return value or {@code null} for none
   */
  public DoubleHparamSearchSpace getSubsample() {
    return subsample;
  }

  /**
   * Subsample the training data to grow tree to prevent overfitting for boosted tree models.
   * @param subsample subsample or {@code null} for none
   */
  public HparamSearchSpaces setSubsample(DoubleHparamSearchSpace subsample) {
    this.subsample = subsample;
    return this;
  }

  /**
   * Tree construction algorithm for boosted tree models.
   * @return value or {@code null} for none
   */
  public StringHparamSearchSpace getTreeMethod() {
    return treeMethod;
  }

  /**
   * Tree construction algorithm for boosted tree models.
   * @param treeMethod treeMethod or {@code null} for none
   */
  public HparamSearchSpaces setTreeMethod(StringHparamSearchSpace treeMethod) {
    this.treeMethod = treeMethod;
    return this;
  }

  /**
   * Hyperparameter for matrix factoration when implicit feedback type is specified.
   * @return value or {@code null} for none
   */
  public DoubleHparamSearchSpace getWalsAlpha() {
    return walsAlpha;
  }

  /**
   * Hyperparameter for matrix factoration when implicit feedback type is specified.
   * @param walsAlpha walsAlpha or {@code null} for none
   */
  public HparamSearchSpaces setWalsAlpha(DoubleHparamSearchSpace walsAlpha) {
    this.walsAlpha = walsAlpha;
    return this;
  }

  @Override
  public HparamSearchSpaces set(String fieldName, Object value) {
    return (HparamSearchSpaces) super.set(fieldName, value);
  }

  @Override
  public HparamSearchSpaces clone() {
    return (HparamSearchSpaces) super.clone();
  }

}


text:
import numpy
import rospy
import sys

from PIL import Image as PILImage
from cv_bridge import CvBridge
from sensor_msgs.msg import Image

rospy.init_node("animated_gif")
gif = rospy.get_param("~gif", "")
rospy.loginfo("loading " + gif)
bridge = CvBridge()
# if gif == "":

# only loads the first frame
# im_array = ndimage.imread(gif)
pil_im = PILImage.open(gif)
im_array = []
try:
    while 1:
        im_array.append(numpy.asarray(pil_im.convert('RGBA')))
        pil_im.seek(pil_im.tell() + 1)
except EOFError:
    pass  # end of sequence
print(len(im_array))
print(im_array[0].shape)
pub = rospy.Publisher("image", Image, queue_size=3)

ind = 0
while True:
    for i in range(len(im_array)):
        if rospy.is_shutdown():
            sys.exit(0)
        # print(i, type(im_array[i]))
        pub.publish(bridge.cv2_to_imgmsg(im_array[i], "rgba8"))
        rospy.sleep(0.05)


text:
namespace Blocks
{
	class Air : public ::Block
	{
	public:
		Air(void);
		~Air(void);
		inline bool IsOpaque();
		float GetFaceTextureId(FaceType face);
	};

	bool Air::IsOpaque() { return false; }
}


text:
GOOGLE_CLIENT_ID = ""
GOOGLE_CLIENT_SECRET = ""
# the local path for the redirect URL you set in the APIs Console
GOOGLE_REDIRECT_URI = "/oauth2callback"
# Restrict logins to users from this GApps domain
GOOGLE_DOMAIN_CHECK = "example.com"

# Domain to set cookies against
TKT_DOMAIN = ".internal.example.com"
TKT_COOKIE = "auth_pubtkt"  # default
TKT_EXPIRY = 86400  # 1 day
# See the mod_auth_pubtkt docs to generate a keypair
TKT_PRIVATE_KEY = "/path/to/mod_auth_pubtkt/keys/privkey.pem"
TKT_PUBLIC_KEY = "/path/to/mod_auth_pubtkt/keys/pubkey.pem"
# Restrict cookies to only go via HTTPS
TKT_SSL_ONLY = True
# Set Client IPs in cookie values - see the mod_auth_pubtkt docs for details
TKT_CLIENT_IP = True

# A LONG and RANDOM string
SECRET_KEY = "change me"
# Print lots of noise (including sensitive stuff) to stderr/logs
DEBUG = True

# Name to put at the top of the pages
APP_NAME = "Example Co"
# Application link/launch list
APP_LIST = (
    ("My App 1", "https://myapp1.internal.example.com/"),
    ("My App 2", "https://myapp1.internal.example.com/"),
)


text:
#include <common.h>
#include <debug_uart.h>
#include <errno.h>
#include <linux/err.h>
#include <linux/types.h>
#include <efi.h>
#include <efi_api.h>

DECLARE_GLOBAL_DATA_PTR;

static struct efi_priv *global_priv;

struct efi_system_table *efi_get_sys_table(void)
{
	return global_priv->sys_table;
}

unsigned long efi_get_ram_base(void)
{
	return global_priv->ram_base;
}

static efi_status_t setup_memory(struct efi_priv *priv)
{
	struct efi_boot_services *boot = priv->boot;
	efi_physical_addr_t addr;
	efi_status_t ret;
	int pages;

	/*
	 * Use global_data_ptr instead of gd since it is an assignment. There
	 * are very few assignments to global_data in U-Boot and this makes
	 * it easier to find them.
	 */
	global_data_ptr = efi_malloc(priv, sizeof(struct global_data), &ret);
	if (!global_data_ptr)
		return ret;
	memset(gd, '\0', sizeof(*gd));

	gd->malloc_base = (ulong)efi_malloc(priv, CONFIG_VAL(SYS_MALLOC_F_LEN),
					    &ret);
	if (!gd->malloc_base)
		return ret;
	pages = CONFIG_EFI_RAM_SIZE >> 12;

	/*
	 * Don't allocate any memory above 4GB. U-Boot is a 32-bit application
	 * so we want it to load below 4GB.
	 */
	addr = 1ULL << 32;
	ret = boot->allocate_pages(EFI_ALLOCATE_MAX_ADDRESS,
				   priv->image_data_type, pages, &addr);
	if (ret) {
		printf("(using pool %lx) ", ret);
		priv->ram_base = (ulong)efi_malloc(priv, CONFIG_EFI_RAM_SIZE,
						   &ret);
		if (!priv->ram_base)
			return ret;
		priv->use_pool_for_malloc = true;
	} else {
		priv->ram_base = addr;
	}
	gd->ram_size = pages << 12;

	return 0;
}

static void free_memory(struct efi_priv *priv)
{
	struct efi_boot_services *boot = priv->boot;

	if (priv->use_pool_for_malloc)
		efi_free(priv, (void *)priv->ram_base);
	else
		boot->free_pages(priv->ram_base, gd->ram_size >> 12);

	efi_free(priv, (void *)gd->malloc_base);
	efi_free(priv, gd);
	global_data_ptr = NULL;
}

/**
 * efi_main() - Start an EFI image
 *
 * This function is called by our EFI start-up code. It handles running
 * U-Boot. If it returns, EFI will continue. Another way to get back to EFI
 * is via reset_cpu().
 */
efi_status_t efi_main(efi_handle_t image, struct efi_system_table *sys_table)
{
	struct efi_priv local_priv, *priv = &local_priv;
	efi_status_t ret;

	/* Set up access to EFI data structures */
	efi_init(priv, "App", image, sys_table);

	global_priv = priv;

	/*
	 * Set up the EFI debug UART so that printf() works. This is
	 * implemented in the EFI serial driver, serial_efi.c. The application
	 * can use printf() freely.
	 */
	debug_uart_init();

	ret = setup_memory(priv);
	if (ret) {
		printf("Failed to set up memory: ret=%lx\n", ret);
		return ret;
	}

	printf("starting\n");

	board_init_f(GD_FLG_SKIP_RELOC);
	board_init_r(NULL, 0);
	free_memory(priv);

	return EFI_SUCCESS;
}

void reset_cpu(ulong addr)
{
	struct efi_priv *priv = global_priv;

	free_memory(priv);
	printf("U-Boot EFI exiting\n");
	priv->boot->exit(priv->parent_image, EFI_SUCCESS, 0, NULL);
}


text:
<?php

namespace app\modules\manajerkeuangan\controllers;

use app\models\db\Siaran;
use app\models\form\TransaksiPeriodeForm;
use app\models\form\TransaksiSiaranForm;
use app\modules\manajerkeuangan\models\form\TransaksiSearchForm;
use yii\web\Controller;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use Yii;
use yii\data\ActiveDataProvider;
use yii\web\NotFoundHttpException;
use yii\web\Session;

use app\models\db\Transaksi;
use app\models\db\Akun;
use app\models\db\TransaksiLain;
use app\modules\manajerkeuangan\models\BukuBesar;
use app\models\form\ConfirmationForm;
use app\models\factory\TransaksiFactory;
use app\models\factory\TransaksiLainFactory;
use app\models\factory\SiaranFactory;
use app\models\factory\RekamanFactory;
use app\helpers\TimeHelper;
use app\models\search\TransaksiSearch;

class TransaksiController extends BaseController {

	public function behaviors(){
		return ArrayHelper::merge([
			//allow access to direktur
			'access' => [
				'class' => AccessControl::className(),
				'rules' => [
					[
						'allow' => true,
						'roles' => ['@'],
						'matchCallback' => function($rule,$action){
							if (isset(Yii::$app->user->identity)){
								return Yii::$app->user->identity->isDirektur();
							}
							else
								return false;
						}
					],
				]
			]
		],parent::behaviors());
	}

	public $defaultAction = 'index';

    public function actionIndex()
    {
    	$model = new TransaksiSearch;
    	$dataProvider = $model->search(Yii::$app->request->queryParams);

        return $this->render('index',[
        	'model' => $model,
        	'akuns' => $akuns,
        	'dataProvider' => $dataProvider,
        ]);
    }

	public function actionNewadd() {
		$session = new Session();
		$session->open();

		$session->set('transaksi', []);

		return $this->redirect(['add']);
	}

	public function actionAdd() {
		$session = new Session();
		$session->open();

		$model = new TransaksiLain();
		$akuns = Akun::getLeafs();

		if((Yii::$app->request->isPost) && ($model->load(Yii::$app->request->post()))) {
			if($model->validate()) {
				Yii::$app->session->setFlash('success', 'Transaksi ditambahkan.');
				$transaction = $session->get('transaksi');
				$transaction[] = $model;
				$session->set('transaksi', $transaction);
				$model = new TransaksiLain();
			} else {
				Yii::$app->session->setFlash('error', 'Transaksi gagal disimpan.');
			}
		}

		$transaction = $session->get('transaksi');

		return $this->render('add', [
			'model' => $model,
			'akun' => $akuns,
			'transaction' => $transaction,
		]);
	}

	public function actionDoadd() {
		$session = new Session();
		$session->open();

		$transactions = $session->get('transaksi');
		$sum = 0;
		foreach($transactions as $transaction) {
			if($transaction->jenis_transaksi == "debit") {
				$sum += $transaction->nominal;
			} else {
				$sum -= $transaction->nominal;
			}
		}

		if($sum != 0) {
			Yii::$app->session->setFlash('error', 'Jumlah debit dan kredit belum sama.');
			return $this->redirect(['add']);
		} else {
			foreach($transactions as $transaction) {
				$transaction->save();
			}
			Yii::$app->session->setFlash('success', 'Transaksi berhasil disimpan.');
			return $this->redirect(['newadd']);
		}
	}

	public function actionPrint($id) {
		$model = $this->findModel($id);

		return $this->render('print', [
			'model' => $model,
		]);
	}

	public function actionEditAkun($id){
		$model = Akun::findOne($id);
		if ($model === null){
			throw new \yii\web\HttpException(404, 'Akun tidak ditemukan.');
		}
		if ($model->load(Yii::$app->request->post()) ) {
			if ($model->save()){
				Yii::$app->session->setFlash('success','Akun berhasil diubah');
				$this->redirect('akun');
			}
			else
				Yii::$app->session->setFlash('error','Akun gagal diubah');
		}
		return $this->render('edit-akun',[
			'model' => $model]);
	}

	public function actionAkun() {
		$model = new Akun();

		if((Yii::$app->request->isPost) && ($model->load(Yii::$app->request->post()))) {
			$model->harga = 0;
			if($model->save()) {
				Yii::$app->session->setFlash('success', 'Akun berhasil disimpan.');
			} else {
				Yii::$app->session->setFlash('error', 'Akun gagal disimpan.');
			}
			$model = new Akun();
		}

		$akun = Akun::queryLeaf();

		return $this->render('akun', [
			'akun' => $akun,
			'model' => $model,
		]);
	}

	public function actionListunconfirmed() {
		$dataProvider = new ActiveDataProvider([
			'query' => Transaksi::find()->
				where(['not', ['and', ['confirmed' => 1], ['<','tanggal',TimeHelper::getTodayDate()]]]),
				//		->orWhere('confirmed=0')
				//		->orWhere('date_confirmed="' . TimeHelper::getTodayDate() . '"'),
			'pagination' => [
				'pageSize' => 10,
			],
		]);

		return $this->render('listunconfirmed', [
			'dataProvider' => $dataProvider,
		]);
	}

	public function actionListedit() {
		$searchModel = new TransaksiSearch(['scenario'=>'filtertanggal']);
    	$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    	/*
		$dataProvider = new ActiveDataProvider([
			'query' => Transaksi::find()
				->where('confirmed=0'),
			'pagination' => [
				'pageSize' => 10,
			],
		]);*/

		return $this->render('listedit', [
			'dataProvider' => $dataProvider,
			'model' => $searchModel,
		]);
	}

	public function actionListtransaction($date = "") {
		$listTransaksi = TransaksiLain::find();
		$form = new TransaksiSearchForm();
		$akuns = Akun::find()->all();

		if ($form->load(\Yii::$app->request->get()) && $form->validate()) {
		}

		if($form->akun_id != "") {
			$listTransaksi->andWhere('akun_id=' . $form->akun_id);
		}

		if($form->tanggal_awal != "") {
			$listTransaksi->andWhere('tanggal>="' . $form->tanggal_awal . '"');
			$listTransaksi->andWhere('tanggal<="' . $form->tanggal_akhir . '"');
		}

		$listTransaksi = $listTransaksi->orderBy(['tanggal' => SORT_ASC])->with('akun');

		$dataProvider = new ActiveDataProvider([
			'query' => $listTransaksi,
			'pagination' => [
				'pageSize' => 15,
			],
		]);

		return $this->render('listtransaction', [
			'date' => $date,
			'dataProvider' => $dataProvider,
			'model' => $form,
			'akuns' => $akuns,
		]);
	}

	public function actionNewconfirm($id) {
		$session = new Session();
		$session->open();

		$session->set('transaksi', []);

		return $this->redirect(['confirm', 'id'=>$id], 302);
	}

	public function actionConfirm($id) {
		$session = new Session();
		$session->open();

		$listTransaksi = $session->get('transaksi');

		$transaksi = Transaksi::findOne($id);
		if($transaksi->jenis_periode == "periode") {
			$siarans = $transaksi->getSiarans()->limit($transaksi->siaran_per_hari)->all();
		} else {
			$siarans = $transaksi->getSiarans()->all();
		}
		$confirmationForm = new ConfirmationForm();
		$akun = Akun::find()->all();

		if((Yii::$app->request->isPost) && ($confirmationForm->load(Yii::$app->request->post()))) {
			if($confirmationForm->validate()) {
				$listTransaksi[] = $confirmationForm;
				$session->set('transaksi', $listTransaksi);
				$confirmationForm = new ConfirmationForm();
			} else {
				Yii::$app->session->setFlash('error', 'Input tidak valid.');
			}
		}

		return $this->render('confirm', [
			'transaksi' => $transaksi,
			'siarans' => $siarans,
			'akun' => $akun,
			'confirmationForm' => $confirmationForm,
			'listTransaksi' => $listTransaksi,
		]);
	}

	public function actionDoconfirm($id) {
		$session = new Session();
		$session->open();

		$listTransaksi = $session->get('transaksi');
		$transaksi = Transaksi::findOne($id);

		$debit = 0;
		$kredit = 0;

		foreach ($listTransaksi as $data) {
			if($data->jenis_transaksi == "debit") {
				$debit += $data->nominal;
			} else {
				$kredit += $data->nominal;
			}
		}

		if(($debit == $kredit) && ($debit == $transaksi->nominal)) {
			foreach ($listTransaksi as $data) {
				$transaksiLain = TransaksiLainFactory::createTransaksiLainFromConfirmation($transaksi, $data);
				$transaksiLain->save();
			}

			$transaksi->confirmed = 1;
			$transaksi->date_confirmed = TimeHelper::getTodayDate();
			$transaksi->save();
			Yii::$app->session->setFlash('success', 'transaksi berhasil dikonfirmasi');
			return $this->redirect('listunconfirmed', 302);
		} else {
			Yii::$app->session->setFlash('error', 'Jumlah debit, kredit, dan nominal transaksi belum sama.');
			return $this->redirect(['confirm', 'id'=>$id], 302);
		}
	}

	public function actionEdit($id) {
		$session = new Session();
		$session->open();

		$transaksi = Transaksi::findOne($id);

		if($transaksi->jenis_periode == "siaran") {
			$transaksiSiaranForm = new TransaksiSiaranForm();
			$transaksiSiaranForm->fillFromTransaksi($transaksi);
			$session->set('transaksi', $transaksiSiaranForm);

			if($transaksi->haveSiaran()) {
				$listSiaran = $transaksi->siarans;
			} else {
				$listSiaran = $transaksi->rekaman;
			}

			$siarans = array();
			foreach($listSiaran as $siaran) {
				$record = array();
				$record['tanggal'] = $siaran->tanggal;
				$record['jam'] = substr($siaran->waktu, 0, 5);

				$siarans[] = $record;
			}

			$session->set('siarans',  $siarans);
			return $this->redirect(['editsiaran', 'id'=>$id], 302);
		} else {
			$transaksiPeriodeForm = new TransaksiPeriodeForm();
			$transaksiPeriodeForm->fillFromTransaksi($transaksi);
			$session->set('transaksi', $transaksiPeriodeForm);

			if($transaksi->haveSiaran()) {
				$listSiaran = Siaran::find()
								->where('transaksi_id='.$transaksi->id)
								->limit($transaksi->siaran_per_hari)
								->all();
			} else {
				$listSiaran = Rekaman::find()
								->where('transaksi_id='.$transaksi->id)
								->limit($transaksi->siaran_per_hari)
								->all();
			}

			$siarans = array();
			foreach($listSiaran as $siaran) {
				$record = array();
				$record['jam'] = substr($siaran->waktu, 0, 5);

				$siarans[] = $record;
			}

			$session->set('siarans',  $siarans);
			return $this->redirect(['editperiode', 'id'=>$id], 302);
		}
	}

	public function actionEditsiaran($id = 0, $request = "transaksi") {
		$session = new Session();
		$session->open();

		$transaksiForm = $session->get('transaksi');
		$siarans = $session->get('siarans');

		if($request == 'siaran') {
			Yii::$app->response->format = 'json';
			return $siarans;
		}

		$model = $transaksiForm;

		if(Yii::$app->request->isPost) {
			$model->load(Yii::$app->request->post());

			if($model->validate()) {
				$transaksi = Transaksi::findOne($id);
				$transaksi->fillFromSiaranForm($model);

				$siarans = Yii::$app->request->post('Siaran');

				if($transaksi->update(false)) {
					foreach ($siarans as $siaran) {
						if ($transaksi->haveSiaran()) {
							$listSiaran = $transaksi->siarans;
							foreach($listSiaran as $record) {
								$record->delete();
							}

							$siaran = SiaranFactory::createSiaranFromInput($siaran['tanggal'], $siaran['jam'] . ":00", $transaksi->id);
							$siaran->save();
						}
						if ($transaksi->haveRekaman()) {
							$listRekaman = $transaksi->rekaman;
							foreach($listRekaman as $record) {
								$record->delete();
							}

							$rekaman = RekamanFactory::createRekamanFromInput($siaran['tanggal'], $siaran['jam'] . ":00", $transaksi->id);
							$rekaman->save();
						}
					}
					Yii::$app->session->setFlash('success', 'Transaksi berhasil diedit.');
					return $this->redirect(['edit', 'id' => $id]);
				} else {
					Yii::$app->session->setFlash('error', 'Transaksi gagal diedit.');
				}
			} else {
				Yii::$app->session->setFlash('error', 'Data tidak valid, masukan data lagi.');
			}
		}

		return $this->render('edittransaksisiaran', [
			'model' => $model,
		]);
	}

	public function actionEditperiode($id = 0, $request = "transaksi") {
		$session = new Session();
		$session->open();

		$transaksiForm = $session->get('transaksi');
		$siarans = $session->get('siarans');

		if($request == 'siaran') {
			Yii::$app->response->format = 'json';
			return $siarans;
		}

		$model = $transaksiForm;

		if(Yii::$app->request->isPost) {
			$model->load(Yii::$app->request->post());

			if($model->validate()) {
				$transaksi = Transaksi::findOne($id);
				$transaksi->fillFromPeriodeForm($model);

				$siarans = Yii::$app->request->post('Siaran');

				if($transaksi->update(false)) {
					if ($transaksi->haveSiaran()) {
						$listSiaran = $transaksi->siarans;
						foreach ($listSiaran as $record) {
							$record->delete();
						}
					}
					if ($transaksi->haveRekaman()) {
						$listRekaman = $transaksi->rekaman;
						foreach ($listRekaman as $record) {
							$record->delete();
						}
					}

					$tanggal = $transaksi->periode_awal;
					while (TimeHelper::compareFirstDate($tanggal, $transaksi->periode_akhir)) {
						foreach ($siarans as $siaran) {
							if ($transaksi->haveSiaran()) {
								$siaran = SiaranFactory::createSiaranFromInput($tanggal, $siaran['jam'] . ":00", $transaksi->id);
								$siaran->save();
							}
							if ($transaksi->haveRekaman()) {
								$rekaman = RekamanFactory::createRekamanFromInput($tanggal, $siaran['jam'] . ":00", $transaksi->id);
								$rekaman->save();
							}
						}
						for ($i = 0; $i < $transaksi->frekuensi; $i++) {
							$tanggal = TimeHelper::getTomorrowDate($tanggal);
						}
					}
					Yii::$app->session->setFlash('success', 'Transaksi berhasil diedit.');
					return $this->redirect(['edit', 'id' => $id]);
				} else {
					Yii::$app->session->setFlash('error', 'Transaksi gagal diedit.');
				}
			} else {
				var_dump($model->errors);
				exit;
				Yii::$app->session->setFlash('error', 'Data tidak valid, masukan data lagi.');
			}
		}

		return $this->render('edittransaksiperiode', [
			'model' => $model,
		]);
	}

	public function actionUpdate($id) {
		$model = $this->findModel($id);
		$akun = Akun::find()->all();

		if((Yii::$app->request->isPost) && ($model->load(Yii::$app->request->post()))) {
			if($model->save()) {
				Yii::$app->session->setFlash('success', 'Transaksi berhasil diubah.');
			} else {
				Yii::$app->session->setFlash('error', 'Transaksi gagal diubah.');
			}
		}

		return $this->render('update', [
			'model' => $model,
			'akun' => $akun,
		]);
	}

	public function actionPrinttabungan($startDate, $endDate,$akunId) {
		$query = TabunganHariTua::find();
		$debit = TabunganHariTua::getTotalDebit();
		$kredit = TabunganHariTua::getTotalKredit();

		if($debit >= $kredit) {
			$debit -= $kredit;
			$kredit = 0;
		} else {
			$debit = 0;
			$kredit -= $debit;
		}

		if($startDate != "") {
			$query = $query->andWhere('tanggal>="' . $startDate . '"');
		}
		if($endDate != "") {
			$query = $query->andWhere('tanggal<="' . $endDate . '"');
		}
		$data = $query->orderBy(['tanggal' => SORT_ASC])->all();

		$output = fopen('php://output', 'w');

		fputcsv($output, ['Tanggal', 'Jenis Kegiatan', 'Debit', 'Kredit']);

		foreach ($data as $record) {
			$recordDebit = 0;
			$recordKredit = 0;
			if($record->jenis_transaksi == "debit") {
				$recordDebit = $record->nominal;
			} else {
				$recordKredit = $record->nominal;
			}

			fputcsv($output, [$record->tanggal, $record->jenis_kegiatan, $recordDebit, $recordKredit]);
		}

		fputcsv($output, []);
		fputcsv($output, ['', '', 'Saldo Debit', $debit]);
		fputcsv($output, ['', '', 'Saldo Kredit', $kredit]);

		header('Content-type: application/xlsx');
		header('Content-Disposition: attachment; filename=tes.csv');
	}

	protected function findModel($id) {
        if (($model = TransaksiLain::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}


text:
The Timeline Reader is a stand-alone server daemon and doesn't need to be
co-located with any other service.

    module.exports = header: 'YARN TR HBase Service RM Install', handler: ({options}) ->
      tmp_dir = "/tmp/hbase_tarball_#{Date.now()}"

## Register

      @registry.register 'hdp_select', '@rybajs/metal/lib/hdp_select'
      @registry.register ['file', 'jaas'], '@rybajs/metal/lib/file_jaas'
      @registry.register ['yarn','service', 'create'], '@rybajs/metal/lib/actions/yarn/service_create'
      @registry.register ['hdfs','put'], '@rybajs/metal/lib/actions/hdfs/put'
      @registry.register ['hdfs','chown'], '@rybajs/metal/lib/actions/hdfs/chown'
      @registry.register ['hdfs','mkdir'], '@rybajs/metal/lib/actions/hdfs/mkdir'
      @registry.register 'ranger_policy', '@rybajs/metal/ranger/actions/ranger_policy'

## Identities

By default, the "hadoop-yarn-timelineserver" package create the following entries:

```bash
cat /etc/passwd | grep yarn
yarn:x:2403:2403:Hadoop YARN User:/var/lib/hadoop-yarn:/bin/bash
cat /etc/group | grep hadoop
hadoop:x:499:hdfs
```

      @system.group header: 'Hadoop Group', options.hadoop_group
      @system.group header: 'Group', options.group
      @system.user header: 'User', options.user

## Wait

      @call once: true, 'masson/core/krb5_client/wait', options.wait_krb5_client
      @call once: true, '@rybajs/metal/hadoop/hdfs_nn/wait', options.wait_hdfs_nn, conf_dir: '/etc/hadoop/conf'

## Configuration

Update the "hbase-site.xml" and "hbase-env.sh" configuration file.

      @file.types.hfile
        header: 'HBase Site'
        target: "#{options.conf_dir}/hbase-site.xml"
        properties: options.hbase_site
        backup: true
        user: options.ats_user.name
        group: options.hadoop_group.name
      @file.types.hfile
        header: 'HBase Policy'
        target: "#{options.conf_dir}/hbase-policy.xml"
        properties: options.hbase_policy
        backup: true
        user: options.ats_user.name
        group: options.hadoop_group.name
      @file
        header: 'HBase Log4j'
        target: "#{options.conf_dir}/log4j.properties"
        source: "#{__dirname}/../resources/hbase-log4j.properties"
        local: true

# HDFS Layout

      @call
        header: 'HDFS Layout'
        if: options.post_service
      , ->
        @hdfs.mkdir
          header: 'Mkdir HBase root dir'
          nn_url: options.nn_url
          target: "#{options.hbase_site['hbase.rootdir']}"
          owner: 'yarn-ats'
          group: options.hadoop_group.name
          krb5_user: options.hdfs_krb5_user
          mode: '755'
        @hdfs.put
          header: 'Upload HBase Policy'
          source: "#{options.conf_dir}/hbase-policy.xml"
          target: "/atsv2/hbase-policy.xml"
          nn_url: options.nn_url
          owner: 'yarn-ats'
          group: options.hadoop_group.name
          krb5_user: options.hdfs_krb5_user
        @hdfs.put
          header: 'Upload HBase Site'
          source: "#{options.conf_dir}/hbase-site.xml"
          target: "/atsv2/hbase-site.xml"
          nn_url: options.nn_url
          owner: 'yarn-ats'
          group: options.hadoop_group.name
          krb5_user: options.hdfs_krb5_user
        @hdfs.put
          header: 'Upload HBase Log4j'
          source: "#{options.conf_dir}/log4j.properties"
          target: "/atsv2/log4j.properties"
          nn_url: options.nn_url
          owner: 'yarn-ats'
          group: options.hadoop_group.name
          krb5_user: options.hdfs_krb5_user
        @hdfs.put
          header: 'Upload Core Site'
          source: "/etc/hadoop/conf/core-site.xml"
          target: "/atsv2/core-site.xml"
          nn_url: options.nn_url
          owner: 'yarn-ats'
          group: options.hadoop_group.name
          krb5_user: options.hdfs_krb5_user

## YARN ATS kerberos Client Keytab

      @krb5.addprinc options.krb5.admin,
        header: 'Yarn HBase ATS Client Principal'
        principal: options.yarn_ats_user.principal
        password: options.yarn_ats_user.password
        unless: options.hbase_local

      @krb5.ktutil.add options.krb5.admin,
        unless: options.hbase_local
        header: 'Yarn HBase ATS Client Keytab'
        principal: options.yarn_ats_user.principal
        password: options.yarn_ats_user.password
        keytab: options.yarn_ats_user.keytab
        kadmin_server: options.krb5.admin.admin_server
        mode: 0o0640
        uid: options.ats_user.name
        gid: options.hadoop_group.name

## Prepare HBase TarBall

      @call
        header: 'HBase TarBall'
        if: options.post_service
        unless_exec: mkcmd.hdfs options.hdfs_krb5_user, "hdfs hdfs -test -f /atsv2/hbase.tar.gz"
      , ->
        @system.mkdir
          target: tmp_dir
        @system.execute
          cmd: """
              version=`hdp-select versions | tail -1`
              #hbase
              cp -rf /usr/hdp/$version/hbase #{tmp_dir}/
              echo yes | mv #{tmp_dir}/hbase/bin/hbase.distro #{tmp_dir}/hbase/bin/hbase
              rm -rf #{tmp_dir}/hbase/conf
              rm -rf #{tmp_dir}/hbase/logs
              rm -rf #{tmp_dir}/hbase/pids
              rm -rf #{tmp_dir}/hbase/lib/zookeeper*.jar
              cp -rf /usr/hdp/$version/zookeeper/zookeeper-*.jar #{tmp_dir}/hbase/lib
              #mapreduce
              cp -rf /usr/hdp/$version/hadoop/mapreduce.tar.gz #{tmp_dir}/
              cd #{tmp_dir}
              tar -xzf mapreduce.tar.gz
              rm -rf mapreduce.tar.gz
              tar -czf hbase.tar.gz hbase hadoop && echo "`date` HBase package created in path $yarn_hbase_user_tmp"
              chmod 644 hbase.tar.gz && echo "`date` hbase.tar.gz has set with ugo=644"
              rm -rf hbase
              rm -rf hadoop
            """
        @hdfs.put
          header: 'Upload HBase TarBall'
          source: "#{tmp_dir}/hbase.tar.gz"
          target: "/atsv2/hbase.tar.gz"
          nn_url: options.nn_url
          krb5_user: options.hdfs_krb5_user

## Dependencies

    mkcmd = require '../../lib/mkcmd'


text:
class LogMessageHandler < GorgService::Consumer::MessageHandler::Base
  def initialize(msg)
    GorgService.logger.debug "Message received in LogMessageHandler"
    self.class.messages<<msg
  end

  def self.messages
    @@messages||=[]
  end

  def self.has_received_error?(type)
    messages.any?{|m| m.errors.any?{|x| x.type==type}} || messages.any?{|m| m.type=='log'&&m.error_type=type}
  end

  def self.has_received_hardfail?
    self.has_received_error?("hardfail")
  end

  def self.has_received_softfail?
    self.has_received_error?("softfail")
  end

  def self.has_received_a_message_with_routing_key?(routing_key)
    messages.any?{|m| m.routing_key==routing_key}
  end

  def self.reset
    @@messages=nil
  end
end


text:
eval my_gray='$FG[237]'
eval my_orange='$FG[214]'

# Convert seconds to human-readable time
# e.g. 165392 => 1d 21h 56m 32s
# https://github.com/sindresorhus/pretty-time-zsh
prompt_human_time_to_var() {
  local human=" " total_seconds=$1 var=$2
  local days=$(( total_seconds / 60 /60 / 24 ))
  local hours=$(( total_seconds / 60 / 60 % 24 ))
  local minutes=$(( total_seconds / 60 % 60 ))
  local seconds=$(( total_seconds % 60 ))
  (( days > 0 )) && human+="${days}d "
  (( hours > 0 )) && human+="${hours}h "
  (( minutes > 0 )) && human+="${minutes}m "
  human+="${seconds}s"

  # store human-readable time in variable as specified by caller
  typeset -g "${var}"="${human}"
}

# stores (into prompt_cmd_exec_time) the exec time of the last command if set threshold exceeded
# (currently 5 secs, change in CMD_MAX_EXEC_TIME:=)
prompt_check_cmd_exec_time() {
  integer elapsed
  (( elapsed = EPOCHSECONDS - ${prompt_cmd_timestamp:-$EPOCHSECONDS} ))
  prompt_cmd_exec_time=
  (( elapsed > ${CMD_MAX_EXEC_TIME:=5} )) && {
    prompt_human_time_to_var $elapsed "prompt_cmd_exec_time"
  }
}

prompt_clear_screen() {
  # enable output to terminal
  zle -I
  # clear screen and move cursor to (0,0)
  print -n '\e[2J\e[0;0H'
  # print preprompt
  prompt_preprompt_render precmd
}

prompt_git_check() {
  # check if in a git repo
  command git rev-parse --is-inside-work-tree &>/dev/null || return
  if [[ $? -eq 1 ]]; then
    exit 0
  else
    echo "%F{39}%f"
  fi
}

prompt_git_dirty() {
  # check if in a git repo
  command git rev-parse --in-inside-work-tree &>/dev/null || return
  # check if repo is dirty
  command git diff --quiet --ignore-submodules HEAD &>/dev/null;
  if [[ $? -eq 1 ]]; then
    echo "F${my_orange}±%f"
  else
    echo "%F{green}✔%f"
  fi
}

prompt_check_git_arrows() {
  # reset git arrows
  prompt_git_arrows=

  # check if there is an upstream configured for this branch
  command git rev-parse --abbrev-ref @'{u}' &>/dev/null || return

  local arrow_status
  # check git left and right arrow_status
  arrow_status="$(command git rev-list --left-right --count HEAD...@'{u}' 2>/dev/null)"
  # exit if the command fails
  (( !$? )) || return

  # left and right are tab-separated, split on tab and store as array
  arrow_status=(${(ps:\t:)arrow_status})
  local arrows left=${arrow_status[1]} right=${arrow_status[2]}

#  (( ${right:-0} > 0 )) && arrows+="${GIT_DOWN_ARROW:-⇣}"
#  (( ${left:-0} > 0 )) && arrows+="${GIT_UP_ARROW:-⇡}"
  (( ${right:-0} > 0 )) && arrows+="%F${my_orange}${GIT_DOWN_ARROW:-⬇}%f"
  (( ${left:-0} > 0 )) && arrows+="%F{red}${GIT_UP_ARROW:-⬆}%f"

  [[ -n $arrows ]] && prompt_git_arrows=" ${arrows}"
}

prompt_background_job() {
  local bgjob
  bgjob=$(jobs 2>/dev/null | tail -n 1)
  if [[ $bgjob == "" ]]; then
    echo ""
  else
    echo "%{$FG[208]%}✱%f"
  fi
}

prompt_set_title() {
  # emacs doesn't support setting the title
  (( ${EMACS} )) && return

  # tell the terminal we're setting the title
  print -n '\e]0;'
  # show hostname if connected via SSH
  [[ -n $SSH_CONNECTION ]] && print -Pn '(%m) '
  case $1 in
    expand-prompt)
      print -Pn $2;;
    ignore-escape)
      print -rn $2;;
  esac
  # end set title
  print -n '\a'
}

prompt_preexec() {
  # attempt to detect and prevent prompt_async_git_fetch from interfering with
  # user-initiated git or hub fetch
  [[ $2 =~ (git|hub)\ .*(pull|fetch) ]] && async_flush_jobs 'prompt'

  prompt_cmd_timestamp=$EPOCHSECONDS

  # shows the current dir and executed commands in the title while a process is active
  prompt_set_title 'ignore-escape' "$PWD:t: $2"
}

# string length ignoring ansi escapes
prompt_string_length_to_var() {
  local str=$1 var=$2 length
  # perform expansion on str and check length
  length=$(( ${#${(S%%)str//(\%([KF1]|)\{*\}|\%[Bbkf])}} ))

	# store string length in variable as specified by caller
	typeset -g "${var}"="${length}"
}

prompt_preprompt_render() {
	# store the current prompt_subst setting so that it can be restored later
	local prompt_subst_status=$options[prompt_subst]

	# make sure prompt_subst is unset to prevent parameter expansion in preprompt
	#setopt local_options no_prompt_subst
	setopt local_options no_prompt_subst

	#check that no command is currently running, the preprompt will otherwise be
	# rendered in the wrong place
	[[ -n ${prompt_cmd_timestamp+x} && "$1" != "precmd" ]] && return

	# set color for git branch/dirty status, change color if dirty check is delayed
	local git_color=246
	[[ -n ${prompt_git_last_dirty_check_timestamp+x} ]] && git_color=red

	# construct preprompt beginning with path
  local preprompt=""
  preprompt+="%F{blue}${prompt_git_check}%f"
  preprompt+="%F{blue}%~%f"
  # git info
  preprompt+="%F{$git_color}${vcs_info_msg_0_}${prompt_git_dirty}%f"
  # git pull/push arrows
  preprompt+="${prompt_git_arrows}"
  # username and machine (if applicable)
  preprompt+=$prompt_username
  # execution time
  preprompt+="%F${my_orange}${prompt_cmd_exec_time}%f"

  # make sure prompt_last_preprompt is a global array
  typeset -g -a prompt_last_preprompt

  # if executing through precmd, don't perform fancy terminal editing
  if [[ "$1" == "precmd" ]]; then
    print -P "\n${preprompt}"
  else
    # only redraw if the expanded preprompt has changed
    [[ "${prompt_last_preprompt[2]}" != "${(S%%)preprompt}" ]] || return

    # calculate length of preprompt and store locally in preprompt_length
    integer preprompt_length lines
    prompt_string_length_to_var "${preprompt}" "preprompt_length"

    # calculate number of preprompt lines for redraw purposes
    (( lines = ( preprompt_length - 1 ) / COLUMNS +1 ))

    # calculate previous preprompt lines to figure out how the new preprompt should behave
    integer last_preprompt_length last_lines
    prompt_string_length_to_var "${prompt_last_preprompt[1]}" "last_preprompt_length"
    (( last_lines = ( last_preprompt_length - 1 ) / COLUMNS +1 ))

    # clr_prev_preprompt erases visual artifacts from previous preprompt
    local clr_prev_preprompt
    if (( last_lines > lines )); then
      # move cursor up by last_lines, clear the line, and move it down by 1 line
      clr_prev_preprompt="\e[${last_lines}A\e[2K\e[1B"
      while (( last_lines - lines > 1 )); do
        # clear the line and move cursor down by one
        clr_prev_preprompt+='\e[2K\e[1B'
        (( last_lines-- ))
      done

      # move cursor into correct position for preprompt update
      clr_prev_preprompt+="\e[${lines}B"

    # create more space for preprompt if new preprompt has more lines than last
    elif (( last_lines < lines )); then
      # move cursor using newlines because ansi cursor movement can't push the cursor beyong the last line
      printf $'\n'%.0s {1..$(( lines - last_lines ))}
    fi

    # disable clearing of line if last char of preprompt is last column of terminal
    local clr='\e[K'
    (( COLUMNS * lines == preprompt_length )) && clr=

    # modify previous preprompt
    print -Pn "${clr_prev_preprompt}\e[${lines}A\e[${COLUMNS}D${preprompt}${clr}\n"

    if [[ $prompt_subst_status = 'on' ]]; then
      # reenable prompt_subst for expansion on PS1
      setopt prompt_subst
    fi

    # redraw prompt (also resets cursor position)
    zle && zle .reset-prompt
  fi

  # store both unexpanded and expanded preprompt for comparison
  prompt_last_preprompt=("$preprompt" "${(S%%)preprompt}")
}

prompt_precmd() {
  # check exec time and store in a var
  prompt_check_cmd_exec_time

  # by making sure that prompt_cmd_timestamp is defined here, the async funcs are prevented
  # from interfering with initial prompt rendering
  prompt_cmd_timestamp=

  # check for git arrows
  prompt_check_git_arrows

  # show the full path in the title
  prompt_set_title 'expand-prompt' '%~'

  # get vcs info
  vcs_info

  # perform async git dirty check and fetch
  prompt_async_tasks

  # print the preprompt
  prompt_preprompt_render "precmd"

  # remove the prompt_cmd_timestamp, indicating that precmd has completed
  unset prompt_cmd_timestamp
}

# fastest possible way to check if repo is dirty
prompt_asynch_git_dirty() {
  local untracked_dirty=$1; shift

  # use cd -q to avoid side effects of changing directory, e.g. chpwd hooks
  builtin cd -q "$*"

  if [[ "$untracked_dirty" == "0" ]]; then
    command git diff --no-ext-diff --quiet --exit-code
  else
    test -z "$(command git status --porcelain --ignore-submodules --unormal)"
  fi

  (( $? )) && echo "*"
}

prompt_async_git_fetch() {
  # use cd -q to avoid side effects of changing directory, e.g. chpwd hooks
  builtin cd -q "$*"

  # set GIT_TERMINAL_PROMPT=0 to disable auth prompting for git fetch (git 2.3+)
  GIT_TERMINAL_PROMPT=0 command git -c gc.auto=0 fetch
}

prompt_async_tasks() {
  # initialize async worker
  ((!${prompt_async_init:-0})) && {
    async_start_worker "prompt" -u -n
    async_register_callback "prompt" prompt_async_callback
    prompt_async_init=1
  }

  # store working_tree without the "x" prefix
  local working_tree="${vcs_info_msg_1_#x}"

  # check if the working tree changed (prompt_current_working_tree prefixed by "x")
  if [[ ${prompt_current_working_tree#x} != $working_tree ]]; then
    # stop any running async jobs
    async_flush_jobs "prompt"

    #reset git preprompt variables, switching working tree
    unset prompt_git_dirty
    unset prompt_git_last_dirty_check_timestamp

    # set the new working tree and prefix with "x" to prevent the creation of a named
    # path by AUTO_NAME_DIRS
    prompt_current_working_tree="x${working_tree}"
  fi

  # only perform tasks inside git working tree
  [[ -n $working_tree ]] || return

  # do not perform git fetch if it is disabled or working_tree == HOME
  if (( ${GIT_PULL:-1} )) && [[ $working_tree != $HOME ]]; then
    # tell worker to git fetch
    async_job "prompt" prompt_async_git_fetch "${working_tree}"
  fi

  # if dirty checking is sufficiently fast, tell worker to check it again or wait for timeout
  integer time_since_last_dirty_check=$(( EPOCHSECONDS - ${prompt_git_last_dirty_check_timestamp:-0} ))
  if (( time_since_last_dirty_check > ${GIT_DELAY_DIRTY_CHECK:-1800} )); then
    unset prompt_git_last_dirty_check_timestamp
    # check if there is anything to pull
    async_job "prompt" prompt_async_git_dirty "${GIT_UNTRACKED_DIRTY:-1}" "${working_tree}"
  fi
}

prompt_async_callback() {
  local job=$1
  local output=$3
  local exec_time=$4

  case "${job}" in
    prompt_async_git_dirty)
      prompt_git_dirty=$output
      prompt_preprompt_render

      # when prompt_git_last_dirty_check_timestamp is set, the git info is displayed in
      # a different color. To distinguish between "fresh" and "cached" result, the preprompt
      # is rendered before setting this variable. Thus, only upon next rendering of the
      # preprompt will the result appear in a different color
      (( $exec_time > 2 )) && prompt_git_last_dirty_check_timestamp=$EPOCHSECONDS
      ;;
    prompt_async_git_fetch)
      prompt_check_git_arrows
      prompt_preprompt_render
      ;;
  esac
}

prompt_setup() {
  # prevent % from appearing if output doesn't end with newline
  export PROMPT_EOL_MARK=''

  prompt_opts=(subst percent)

  zmodload zsh/datetime
  zmodload zsh/zle
  zmodload zsh/parameter

  autoload -Uz add-zsh-hook
  autoload -Uz vcs_info
  autoload -Uz async && async

  add-zsh-hook precmd prompt_precmd
  add-zsh-hook preexec prompt_preexec

  zstyle ':vcs_info:*' enable git
  zstyle ':vcs_info:*' use-simple true
  # only export two msg variables from vcs_info
  zstyle ':vcs_info:*' max-exports 2
  zstyle ':vcs_info:git*' formats ' %b' 'x%R'
  zstyle ':vcs_info:git*' actionformats ' %b|%a' 'x%R'

  # if user hasn't registered a custom zle widget for clear-screen, override
  # the builtin one so the preprompt is displayed correctly when ^L is given
  if [[ $widgets[clear-screen] == 'builtin' ]]; then
    zle -N clear-screen prompt_clear_screen
  fi

  # show username@host if logged in via SSH
  [[ "$SSH_CONNECTION" != '' ]] && prompt_username=' %F{242}%n@%m%f'

  # show username@host if root, with username in white
  [[ $UID -eq 0 ]] && prompt_username=' %F{white}%n%f%F{242}@%m%f'

  # prompt turns red if the previous command didn't exit 0
  PROMPT="%(?.%F{magenta}.%F{red})${PROMPT_SYMBOL:-❯}%f "
}

prompt_setup "$@"

## PURE END

## LEGACY START

# Make git info available to prompt
#autoload colors && colors

# color vars
#eval my_gray='$FG[237]'
#eval my_orange='$FG[214]'

# Functions to build git-aware prompt(s)
#git_check() {
#  command git rev-parse --is-inside-work-tree &>/dev/null || return
#  if [[ $? -eq 1 ]]; then
#    exit 0
#  else
#    echo "%F{39}%f"
#  fi
#}
#
#git_dirty() {
#  # check to see if we're in a git repo
#  command git rev-parse --is-inside-work-tree &>/dev/null || return
#  # check to see if it's dirty
#  command git diff --quiet --ignore-submodules HEAD &>/dev/null;
#  if [[ $? -eq 1 ]]; then
##    echo "%F{red}✗%f"
#    echo "%F${my_orange}±%f"
#  else
#    echo "%F{green}✔%f"
#  fi
#}
#
## Get the status of the current branch and its remote
## If there are changes upstream, display a ⇣
## If there are changes that have been committed but not yet pushed, display a ⇡
#git_arrows() {
#  # do nothing if there is no upstream configured
#  command git rev-parse --abbrev-ref @'{u}' &>/dev/null || return
#
#  local arrows=""
#  local status
#  arrow_status="$(command git rev-list --left-right --count HEAD...@'{u}' 2>/dev/null)"
#
#  # do nothing if the command failed
#  (( !$? )) || return
#
#  # split on tabs
#  arrow_status=(${(ps:\t:)arrow_status})
#  local left=${arrow_status[1]} right=${arrow_status[2]}
#
#  (( ${right:-0} > 0 )) && arrows+="%F{red}⬇%f"
##  (( ${left:-0} > 0 )) && arrows+="%F{046}⇡%f"
#  (( ${left:-0} > 0 )) && arrows+="%F${my_orange}⬆%f"
##  (( ${left:-0} > 0 )) && arrows+="%F{208}⇡%f"
#
#  echo $arrows
#}
#
## If there is a job in the background, display a ✱
#suspended_jobs() {
#  local sj
#  sj=$(jobs 2>/dev/null | tail -n 1)
#  if [[ $sj == "" ]]; then
#    echo ""
#  else
#    echo "%{$FG[208]%}✱%f"
#  fi
#}
#
#if [ $UID -eq 0 ]; then NCOLOR="red"; else NCOLOR="green"; fi
#local return_code="%(?..%{$fg[red]%}%? ↵%{$reset_color%})"
#
#if [ "${whoami}" = "root" ]
#then CARETCOLOR="red"
#else CARETCOLOR="blue"
#fi
#
#

## precmd() {
##  vcs_info
###  print -P '\n`git_check`%F{39}%~ `git_dirty`%F{246}$vcs_info_msg_0_%f `git_arrows` `suspended_jobs`'
##  print -P '\n`git_check``git_arrows` %F{39}%~  %F{246}$vcs_info_msg_0_%f `git_dirty`'
##}
##
##export PROMPT='`suspended_jobs`%(?.%F{10}.%F{10})❯%f '
###export RPROMPT='`git_dirty`%F{246}$vcs_info_msg_0_%f `git_arrows` `suspended_jobs`'
##export RPROMPT=''


text:
module ValidatesIpAddress
  VERSION = '0.0.4'
end


text:
package http_retry_test

import (
	"io"
	"io/ioutil"
	"net/http"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/improbable-eng/go-httpwares"
	"github.com/improbable-eng/go-httpwares/retry"
	"github.com/improbable-eng/go-httpwares/testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/stretchr/testify/suite"
	"golang.org/x/net/context"
)

var (
	noSleep         = 0 * time.Second
	retryTimeout    = 50 * time.Millisecond
	failureCode     = http.StatusServiceUnavailable
	expectedContent = "SomeReallyLongString"
)

type failingHandler struct {
	*testing.T
	reqCounter uint
	reqModulo  uint
	reqSleep   time.Duration
	mu         sync.Mutex
}

func (f *failingHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
	if f.maybeFailRequest() {
		resp.WriteHeader(failureCode)
		return
	}
	content, err := ioutil.ReadAll(req.Body)
	assert.NoError(f.T, err, "should have a body")
	assert.EqualValues(f.T, expectedContent, string(content), "the body should be sent")
	httpwares_testing.PingBackHandler(httpwares_testing.DefaultPingBackStatusCode).ServeHTTP(resp, req)
}

func (f *failingHandler) resetFailingConfiguration(modulo uint, sleepTime time.Duration) {
	f.mu.Lock()
	defer f.mu.Unlock()
	f.reqCounter = 0
	f.reqModulo = modulo
	f.reqSleep = sleepTime
}

func (f *failingHandler) requestCount() uint {
	f.mu.Lock()
	defer f.mu.Unlock()
	return f.reqCounter
}

func (f *failingHandler) maybeFailRequest() bool {
	f.mu.Lock()
	defer f.mu.Unlock()
	f.reqCounter += 1
	if (f.reqModulo > 0) && (f.reqCounter%f.reqModulo == 0) {
		return false
	}
	time.Sleep(f.reqSleep)
	return true
}

func TestRetryTripperwareSuite(t *testing.T) {
	f := &failingHandler{T: t}
	s := &RetryTripperwareSuite{
		f: f,
		WaresTestSuite: &httpwares_testing.WaresTestSuite{
			Handler: f,
			ClientTripperware: []httpwares.Tripperware{
				http_retry.Tripperware(
					http_retry.WithMax(5),
					http_retry.WithBackoff(http_retry.BackoffLinear(retryTimeout)),
				),
			},
		},
	}
	suite.Run(t, s)
}

type RetryTripperwareSuite struct {
	*httpwares_testing.WaresTestSuite
	f *failingHandler
}

func (s *RetryTripperwareSuite) SetupTest() {
}

func (s *RetryTripperwareSuite) createRequest(method string, ctx context.Context) *http.Request {
	var content io.Reader
	if expectedContent != "" {
		content = strings.NewReader(expectedContent)
	}
	req, _ := http.NewRequest(method, "https://something.local/someurl", content)
	req = req.WithContext(ctx)
	return req
}

func (s *RetryTripperwareSuite) TestRetryPassesOnEnabled() {
	s.f.resetFailingConfiguration(3, noSleep)
	req := s.createRequest("GET", s.SimpleCtx())
	resp, err := s.NewClient().Do(req)
	require.NoError(s.T(), err, "call shouldn't fail")
	require.Equal(s.T(), httpwares_testing.DefaultPingBackStatusCode, resp.StatusCode, "response should succeed")
	require.EqualValues(s.T(), 3, s.f.requestCount(), "3 requests should be retried to meet the modulo")
}

func (s *RetryTripperwareSuite) TestRetryFailsOnMoreThanRetryCount() {
	s.f.resetFailingConfiguration(10, noSleep)
	req := s.createRequest("GET", s.SimpleCtx())
	resp, err := s.NewClient().Do(req)
	require.NoError(s.T(), err, "call shouldn't fail")
	assert.Equal(s.T(), failureCode, resp.StatusCode, "failure code should be propagated")
	require.EqualValues(s.T(), 5, s.f.requestCount(), "backend should see all the retry calls")
}

func (s *RetryTripperwareSuite) TestRetryFailsOnNonRetriable() {
	s.f.resetFailingConfiguration(2, noSleep)
	req := s.createRequest("POST", s.SimpleCtx()) // post is not retriable
	resp, err := s.NewClient().Do(req)
	require.NoError(s.T(), err, "call shouldn't fail")
	assert.Equal(s.T(), failureCode, resp.StatusCode, "failure code should be propagated")
	require.EqualValues(s.T(), 1, s.f.requestCount(), "backend should see only one request")
}

func (s *RetryTripperwareSuite) TestRetryWorksWithAnEnable() {
	s.f.resetFailingConfiguration(3, noSleep)
	req := s.createRequest("PUT", s.SimpleCtx()) // put is not retriable
	resp, err := s.NewClient().Do(http_retry.Enable(req))
	require.NoError(s.T(), err, "call shouldn't fail")
	require.Equal(s.T(), httpwares_testing.DefaultPingBackStatusCode, resp.StatusCode, "response should succeed")
	require.EqualValues(s.T(), 3, s.f.requestCount(), "backend should see all the retry calls")
}

func (s *RetryTripperwareSuite) TestTimesoutTheContextAnyway() {
	s.f.resetFailingConfiguration(4, noSleep)
	ctx, _ := context.WithTimeout(s.SimpleCtx(), 2*retryTimeout) // should be enough for 2 calls
	req := s.createRequest("GET", ctx)                           // GET is retriable
	_, err := s.NewClient().Do(req)
	require.Error(s.T(), err, "call should fail with a context deadline exceeded")
	require.EqualValues(s.T(), 2, s.f.requestCount(), "backend should see two calls")
}

func (s *RetryTripperwareSuite) TestCustomRetriableDecider() {
	s.f.resetFailingConfiguration(10, noSleep)
	clientTripperware := s.ClientTripperware
	s.ClientTripperware = []httpwares.Tripperware{
		http_retry.Tripperware(
			http_retry.WithMax(5),
			http_retry.WithDecider(func(req *http.Request) bool {
				return req.Method == "PUT"
			}),
			http_retry.WithBackoff(http_retry.BackoffLinear(retryTimeout)),
		),
	}
	req := s.createRequest("PUT", s.SimpleCtx())
	resp, err := s.NewClient().Do(req)
	require.NoError(s.T(), err, "call shouldn't fail")
	assert.Equal(s.T(), failureCode, resp.StatusCode, "failure code should be propagated")
	require.EqualValues(s.T(), 5, s.f.requestCount(), "backend should see all the retry calls")
	s.ClientTripperware = clientTripperware
}

func (s *RetryTripperwareSuite) TestCustomResponseDiscarder() {
	s.f.resetFailingConfiguration(10, noSleep)
	clientTripperware := s.ClientTripperware
	s.ClientTripperware = []httpwares.Tripperware{
		http_retry.Tripperware(
			http_retry.WithMax(5),
			http_retry.WithResponseDiscarder(func(resp *http.Response) bool {
				return resp.StatusCode == failureCode
			}),
			http_retry.WithBackoff(http_retry.BackoffLinear(retryTimeout)),
		),
	}
	req := s.createRequest("GET", s.SimpleCtx())
	resp, err := s.NewClient().Do(req)
	require.NoError(s.T(), err, "call shouldn't fail")
	assert.Equal(s.T(), failureCode, resp.StatusCode, "failure code should be propagated")
	require.EqualValues(s.T(), 5, s.f.requestCount(), "backend should see all the retry calls")
	s.ClientTripperware = clientTripperware
}

func (s *RetryTripperwareSuite) TestRequestBodyBuffering() {
	s.f.resetFailingConfiguration(3, noSleep)
	req := s.createRequest("GET", s.SimpleCtx())
	removeGetBody(req)
	resp, err := s.NewClient().Do(req)
	require.NoError(s.T(), err, "call shouldn't fail")
	require.Equal(s.T(), httpwares_testing.DefaultPingBackStatusCode, resp.StatusCode, "response should succeed")
	require.EqualValues(s.T(), 3, s.f.requestCount(), "3 requests should be retried to meet the modulo")
}

func (s *RetryTripperwareSuite) TestRequestBodyBufferingWithNoBody() {
	s.f.resetFailingConfiguration(3, noSleep)
	storedContent := expectedContent
	expectedContent = ""
	req := s.createRequest("GET", s.SimpleCtx())
	resp, err := s.NewClient().Do(req)
	require.NoError(s.T(), err, "call shouldn't fail")
	require.Equal(s.T(), httpwares_testing.DefaultPingBackStatusCode, resp.StatusCode, "response should succeed")
	require.EqualValues(s.T(), 3, s.f.requestCount(), "3 requests should be retried to meet the modulo")
	expectedContent = storedContent
}


text:
#ifndef MIRTK_EulerMethodWithDamping_H
#define MIRTK_EulerMethodWithDamping_H

#include "mirtk/EulerMethod.h"

namespace mirtk {

/**
 * Minimizes deformable surface model using Euler's method with momentum
 *
 * This method has for example been used in the following paper on which this
 * implementation is also based on:
 *
 *   Park et al. (2001), A non-self-intersecting adaptive deformable surface for
 *   complex boundary extraction from volumetric images,
 *   Computer & Graphics, 25, 421–440
 *
 * Another variant of an Euler method with momentum used by the FreeSurfer tools
 * is implemented by EulerMethodWithMomentum.
 */
class EulerMethodWithDamping : public EulerMethod
{
  mirtkOptimizerMacro(EulerMethodWithDamping, OM_EulerMethodWithDamping);

  // ---------------------------------------------------------------------------
  // Attributes

  /// Common mass of all nodes
  mirtkPublicAttributeMacro(double, BodyMass);

  /// Damping coefficient
  mirtkPublicAttributeMacro(double, DampingFactor);

  /// Copy attributes of this class from another instance
  void CopyAttributes(const EulerMethodWithDamping &);

  // ---------------------------------------------------------------------------
  // Construction/Destruction
public:

  /// Constructor
  EulerMethodWithDamping(ObjectiveFunction * = NULL);

  /// Copy constructor
  EulerMethodWithDamping(const EulerMethodWithDamping &);

  /// Assignment operator
  EulerMethodWithDamping &operator =(const EulerMethodWithDamping &);

  /// Destructor
  virtual ~EulerMethodWithDamping();

  // ---------------------------------------------------------------------------
  // Parameters
  using LocalOptimizer::Parameter;

  /// Set parameter value from string
  virtual bool Set(const char *, const char *);

  /// Get parameters as key/value as string map
  virtual ParameterList Parameter() const;

  // ---------------------------------------------------------------------------
  // Execution

  /// Initialize optimization
  ///
  /// This member funtion is implicitly called by Run.
  virtual void Initialize();

  /// Update node displacements
  virtual void UpdateDisplacement();

};

} // namespace mirtk

#endif // MIRTK_EulerMethodWithDamping_H