text:
from __future__ import absolute_import
from __future__ import division

import string
from time import time

from PyQt5 import QtGui, QtCore
from builtins import str

from .TextDecorators import *
from .ViewMode import *
from .cemu import *

class BinViewMode(ViewMode):
    def __init__(self, themes, width, height, data, cursor, widget=None):
        super(BinViewMode, self).__init__()

        self.dataModel = data
        self.addHandler(self.dataModel)
        self.themes = themes

        self.width = width
        self.height = height

        self.cursor = cursor
        self.widget = widget

        self.refresh = True

        self.selector = TextSelection.DefaultSelection(themes, self)

        # background brush
        self.backgroundBrush = QtGui.QBrush(self.themes['background'])

        self.font = self.themes['font']

        # font metrics. assume font is monospaced
        self.font.setKerning(False)
        self.font.setFixedPitch(True)
        fm = QtGui.QFontMetrics(self.font)
        self._fontWidth = fm.width('a')
        self._fontHeight = fm.height()

        self.textPen = QtGui.QPen(self.themes['pen'], 0, QtCore.Qt.SolidLine)
        self.resize(width, height)

        self.Paints = {}
        self.newPix = None
        self.Ops = []

    @property
    def fontWidth(self):
        return self._fontWidth

    @property
    def fontHeight(self):
        return self._fontHeight

    def startCaching(self):
        # cache
        self.cache()
        # t = threading.Thread(target=self.cache)
        # t.start()

    def isInCache(self, page):
        if page in self.Paints:
            return True

    def cache(self):

        for i in [1, 2]:
            # pix = self._getNewPixmap(self.width, self.height)
            if not self.isInCache(self.dataModel.getPageOffset(i)):
                pix = QtGui.QImage(self.width, self.height, QtGui.QImage.Format_ARGB32)
                self.scrollPages(1, cachePix=pix, pageOffset=i)
                self.Paints[self.dataModel.getPageOffset(i)] = pix
                # print 'cache'

    def _getNewPixmap(self, width, height):
        return QtGui.QPixmap(width, height)

    def setTransformationEngine(self, engine):
        self.transformationEngine = engine
        self.original_textdecorator = engine

    def computeTextArea(self):
        self.COLUMNS = self.width // self.fontWidth
        self.ROWS = self.height // self.fontHeight
        self.notify(self.ROWS, self.COLUMNS)

    def drawAdditionals(self):
        self.newPix = self._getNewPixmap(self.width, self.height + self.SPACER)
        qp = QtGui.QPainter()
        qp.begin(self.newPix)
        qp.drawPixmap(0, 0, self.qpix)

        # self.transformationEngine.decorateText()

        # highlight selected text
        self.selector.highlightText()

        # draw other selections
        self.selector.drawSelections(qp)

        # draw our cursor
        self.drawCursor(qp)
        qp.end()

    def getPageOffset(self):
        return self.dataModel.getOffset()

    def getGeometry(self):
        return self.COLUMNS, self.ROWS

    def getColumnsbyRow(self, row):
        return self.COLUMNS

    def getDataModel(self):
        return self.dataModel

    def startSelection(self):
        self.selector.startSelection()

    def stopSelection(self):
        self.selector.stopSelection()

    def draw(self, refresh=False, row=0, howMany=0):
        if self.dataModel.getOffset() in self.Paints:
            self.refresh = False
            self.qpix = QtGui.QPixmap(self.Paints[self.dataModel.getOffset()])
            # print 'hit'
            self.drawAdditionals()
            return

        if self.refresh or refresh:
            qp = QtGui.QPainter()
            qp.begin(self.qpix)
            # start = time()
            if not howMany:
                howMany = self.ROWS

            self.drawTextMode(qp, row=row, howMany=howMany)
            # end = time() - start
            # print 'Time ' + str(end)
            self.refresh = False
            qp.end()

        #        self.Paints[self.dataModel.getOffset()] = QtGui.QPixmap(self.qpix)
        self.drawAdditionals()

    def draw2(self, qp, refresh=False):
        if self.refresh or refresh:
            start = time()
            self.drawTextMode(qp, howMany=self.ROWS)
            end = time() - start
            # print 'Time ' + str(end)
            qp = QtGui.QPainter()
            qp.begin(self.qpix)

        self.drawAdditionals()

    def drawCursor(self, qp):
        cursorX, cursorY = self.cursor.getPosition()
        qp.setBrush(self.themes['background_cursor'])

        if self.isInEditMode():
            qp.setBrush(QtGui.QColor(255, 102, 179))

        qp.setOpacity(0.8)
        qp.drawRect(cursorX * self.fontWidth, cursorY * self.fontHeight, self.fontWidth, self.fontHeight + 2)
        qp.setOpacity(1)

    def scroll_h(self, dx):
        self.qpix.scroll(dx * self.fontWidth, 0, self.qpix.rect())

        qp = QtGui.QPainter()

        qp.begin(self.qpix)
        qp.setFont(self.font)
        qp.setPen(self.textPen)

        factor = abs(dx)
        if dx < 0:
            qp.fillRect((self.COLUMNS - 1 * factor) * self.fontWidth, 0, factor * self.fontWidth,
                        self.ROWS * self.fontHeight + self.SPACER, self.backgroundBrush)
        if dx > 0:
            qp.fillRect(0, 0, factor * self.fontWidth, self.ROWS * self.fontHeight + self.SPACER, self.backgroundBrush)

        cemu = ConsoleEmulator(qp, self.ROWS, self.COLUMNS)

        page = self.transformationEngine.decorate()
        # scriem pe fiecare coloana in parte
        for column in range(factor):
            # fiecare caracter de pe coloana
            for i in range(self.ROWS):

                if dx < 0:
                    # cu (column) selectam coloana
                    idx = (i + 1) * self.COLUMNS - (column + 1)
                if dx > 0:
                    idx = i * self.COLUMNS + column

                # c = self.dataModel.getDisplayablePage()[idx]
                c = self.transformationEngine.getChar(idx)
                qp.setPen(self.transformationEngine.choosePen(idx))

                if self.transformationEngine.chooseBrush(idx) is not None:
                    qp.setBackgroundMode(1)
                    qp.setBackground(self.transformationEngine.chooseBrush(idx))

                #                self.decorate(qp, (idx, c), self.dataModel.getDisplayablePage())
                if dx < 0:
                    cemu.writeAt(self.COLUMNS - (column + 1), i, self.cp437(c))

                if dx > 0:
                    cemu.writeAt(column, i, self.cp437(c))

                qp.setBackgroundMode(0)
        qp.end()

    def scroll_v(self, dy, cachePix=None, pageOffset=None):
        start = time()

        if not cachePix:
            self.qpix.scroll(0, dy * self.fontHeight, self.qpix.rect())

        qp = QtGui.QPainter()

        if cachePix:
            qp.begin(cachePix)
        else:
            qp.begin(self.qpix)

        # self.font.setStyleHint(QtGui.QFont.AnyStyle, QtGui.QFont.PreferAntialias)
        qp.setFont(self.font)
        qp.setPen(self.textPen)

        # TODO: while the characters are not all the same hight, when scrolling up on y axis, trails remains. We should also erase a Rect with SPACER in hight
        #       same problem when scrolling up.
        factor = abs(dy)
        if dy < 0:
            qp.fillRect(0, (self.ROWS - factor) * self.fontHeight, self.fontWidth * self.COLUMNS,
                        factor * self.fontHeight + self.SPACER, self.backgroundBrush)

        if dy > 0:
            qp.fillRect(0, 0, self.fontWidth * self.COLUMNS, factor * self.fontHeight, self.backgroundBrush)

        cemu = ConsoleEmulator(qp, self.ROWS, self.COLUMNS)

        # page = self.dataModel.getDisplayablePage()
        page = self.transformationEngine.decorate(pageOffset=pageOffset)

        lastPen = None
        lastBrush = None

        # cate linii desenam
        k = time()
        for row in range(factor):
            # desenam caracterele
            # cemu.writeAt(0, row, str(page[row*self.COLUMNS:row*self.COLUMNS+self.COLUMNS]))

            for i in range(self.COLUMNS):

                if dy < 0:
                    idx = (self.ROWS - (row + 1)) * self.COLUMNS + i

                if dy > 0:
                    idx = i + (self.COLUMNS * row)

                c = self.transformationEngine.getChar(idx)

                nextPen = self.transformationEngine.choosePen(idx)
                if nextPen != lastPen:
                    qp.setPen(nextPen)
                    lastPen = nextPen

                qp.setBackgroundMode(0)
                nextBrush = self.transformationEngine.chooseBrush(idx)
                if nextBrush is not None:
                    qp.setBackgroundMode(1)

                    if nextBrush != lastBrush:
                        qp.setBackground(nextBrush)
                        lastBrush = nextBrush

                if dy < 0:
                    cemu.writeAt_c(i, self.ROWS - 1 - row, self.cp437(c))

                if dy > 0:
                    cemu.writeAt_c(i, row, self.cp437(c))

        # TODO: text decorator is taking too much! print time() - k
        qp.end()

        end = time() - start

    #        print end
    #        sys.exit()

    def scroll(self, dx, dy, cachePix=None, pageOffset=None):
        if not cachePix:
            if self.dataModel.getOffset() in self.Paints:
                self.draw()
                return

        if dx != 0:
            if self.dataModel.inLimits((self.dataModel.getOffset() - dx)):
                self.dataModel.slide(-dx)
                self.scroll_h(dx)

        if dy != 0:
            if self.dataModel.inLimits((self.dataModel.getOffset() - dy * self.COLUMNS)):
                self.dataModel.slide(-dy * self.COLUMNS)
                # import time
                # k = time.time()
                self.scroll_v(dy, cachePix, pageOffset)
                # print time.time() - k
            else:
                if dy <= 0:
                    pass
                    # self.dataModel.slideToLastPage()
                else:
                    self.dataModel.slideToFirstPage()

                if not cachePix:
                    self.draw(refresh=True)

        if not cachePix:
            self.draw()

    def scrollPages(self, number, cachePix=None, pageOffset=None):
        self.scroll(0, -number * self.ROWS, cachePix=cachePix, pageOffset=pageOffset)

    def getPixmap(self):
        for t in self.Ops:
            if len(t) == 1:
                t[0]()

            else:
                t[0](*t[1:])

        self.Ops = []

        if not self.newPix:
            self.draw()

        return self.newPix

    def resize(self, width, height):
        self.width = width - width % self.fontWidth
        self.height = height - height % self.fontHeight
        self.computeTextArea()
        self.qpix = self._getNewPixmap(self.width, self.height + self.SPACER)
        self.refresh = True

    def drawTextMode(self, qp, row=0, howMany=1):
        # draw background
        qp.fillRect(0, row * self.fontHeight, self.COLUMNS * self.fontWidth, howMany * self.fontHeight + self.SPACER,
                    self.backgroundBrush)

        # set text pen&font
        qp.setFont(self.font)
        qp.setPen(self.textPen)

        cemu = ConsoleEmulator(qp, self.ROWS, self.COLUMNS)

        self.page = self.transformationEngine.decorate()

        cemu.gotoXY(0, row)

        for i, c in enumerate(self.getDisplayablePage()[row * self.COLUMNS:(row + howMany) * self.COLUMNS]):
            x = i + row * self.COLUMNS

            c = self.transformationEngine.getChar(x)

            qp.setPen(self.transformationEngine.choosePen(x))

            if self.transformationEngine.chooseBrush(x) is not None:
                qp.setBackgroundMode(1)
                qp.setBackground(self.transformationEngine.chooseBrush(x))

            cemu.write(self.cp437(c))
            qp.setBackgroundMode(0)

    def getCursorAbsolutePosition(self):
        x, y = self.cursor.getPosition()
        return self.dataModel.getOffset() + y * self.COLUMNS + x

    def moveCursor(self, direction):
        cursorX, cursorY = self.cursor.getPosition()

        if direction == Directions.Left:
            if cursorX == 0:
                if cursorY == 0:
                    self.scroll(1, 0)
                else:
                    self.cursor.moveAbsolute(self.COLUMNS - 1, cursorY - 1)
            else:
                self.cursor.move(-1, 0)

        if direction == Directions.Right:
            if self.getCursorAbsolutePosition() + 1 >= self.dataModel.getDataSize():
                return

            if cursorX == self.COLUMNS - 1:
                if cursorY == self.ROWS - 1:
                    self.scroll(-1, 0)
                else:
                    self.cursor.moveAbsolute(0, cursorY + 1)
            else:
                self.cursor.move(1, 0)

        if direction == Directions.Down:
            if self.getCursorAbsolutePosition() + self.COLUMNS >= self.dataModel.getDataSize():
                y, x = self.dataModel.getXYInPage(self.dataModel.getDataSize() - 1)
                self.cursor.moveAbsolute(x, y)
                return

            if cursorY == self.ROWS - 1:
                self.scroll(0, -1)
            else:
                self.cursor.move(0, 1)

        if direction == Directions.Up:
            if cursorY == 0:
                self.scroll(0, 1)
            else:
                self.cursor.move(0, -1)

        if direction == Directions.End:
            if self.dataModel.getDataSize() < self.getCursorAbsolutePosition() + self.ROWS * self.COLUMNS:
                y, x = self.dataModel.getXYInPage(self.dataModel.getDataSize() - 1)
                self.cursor.moveAbsolute(x, y)

            else:
                self.cursor.moveAbsolute(self.COLUMNS - 1, self.ROWS - 1)

        if direction == Directions.Home:
            self.cursor.moveAbsolute(0, 0)

        if direction == Directions.CtrlHome:
            self.dataModel.slideToFirstPage()
            self.draw(refresh=True)
            self.cursor.moveAbsolute(0, 0)

        if direction == Directions.CtrlEnd:
            self.dataModel.slideToLastPage()
            self.draw(refresh=True)
            self.moveCursor(Directions.End)

    def keyFilter(self):
        return [
            (QtCore.Qt.ControlModifier, QtCore.Qt.Key_Right),
            (QtCore.Qt.ControlModifier, QtCore.Qt.Key_Left),
            (QtCore.Qt.ControlModifier, QtCore.Qt.Key_Up),
            (QtCore.Qt.ControlModifier, QtCore.Qt.Key_Down),
            (QtCore.Qt.ControlModifier, QtCore.Qt.Key_End),
            (QtCore.Qt.ControlModifier, QtCore.Qt.Key_Home),

            (QtCore.Qt.NoModifier, QtCore.Qt.Key_Right),
            (QtCore.Qt.NoModifier, QtCore.Qt.Key_Left),
            (QtCore.Qt.NoModifier, QtCore.Qt.Key_Up),
            (QtCore.Qt.NoModifier, QtCore.Qt.Key_Down),
            (QtCore.Qt.NoModifier, QtCore.Qt.Key_End),
            (QtCore.Qt.NoModifier, QtCore.Qt.Key_Home),
            (QtCore.Qt.NoModifier, QtCore.Qt.Key_PageDown),
            (QtCore.Qt.NoModifier, QtCore.Qt.Key_PageUp)

        ]

    def anon(self, dx, dy):
        self.scroll(dx, dy)

        # scroll modifies datamodel offset, so we must do scroll and cursor
        # operations toghether

        y, x = self.dataModel.getXYInPage(self.dataModel.getDataSize() - 1)
        if self.getCursorAbsolutePosition() >= self.dataModel.getDataSize():
            y, x = self.dataModel.getXYInPage(self.dataModel.getDataSize() - 1)
            self.cursor.moveAbsolute(x, y)

        # we call draw() again because it was called before by scroll()
        # and the cursor is already painted but it's not in correct position
        # kinda hack, don't really like it
        self.draw()

    def handleEditMode(self, modifiers, key, event):
        if key in range(0, 256):
            offs = self.getCursorOffsetInPage()

            self.dataModel.setData_b(self.dataModel.getOffset() + offs, str(event.text()))

            z = self.dataModel.getOffset() + offs
            # TODO: sa nu se repete, tre original_transformengine
            self.transformationEngine = RangePen(self.original_textdecorator, z, z + 0,
                                                 QtGui.QPen(QtGui.QColor(218, 94, 242), 0, QtCore.Qt.SolidLine),
                                                 ignoreHighlights=True)

            self.moveCursor(Directions.Right)

            x, y = self.cursor.getPosition()

            self.draw(refresh=True, row=y, howMany=1)

    def handleKeyEvent(self, modifiers, key, event=None):
        if event.type() == QtCore.QEvent.KeyRelease:
            if key == QtCore.Qt.Key_Shift:
                self.stopSelection()
                return True

        if event.type() == QtCore.QEvent.KeyPress:
            if modifiers & QtCore.Qt.ShiftModifier:
                keys = [QtCore.Qt.Key_Right, QtCore.Qt.Key_Left, QtCore.Qt.Key_Down, QtCore.Qt.Key_Up,
                        QtCore.Qt.Key_End, QtCore.Qt.Key_Home]
                if key in keys:
                    self.startSelection()

            if modifiers & QtCore.Qt.ControlModifier:
                if key == QtCore.Qt.Key_Right:
                    self.addop((self.anon, -1, 0))

                if key == QtCore.Qt.Key_Left:
                    self.addop((self.scroll, 1, 0))

                if key == QtCore.Qt.Key_Down:
                    self.addop((self.anon, 0, -1))

                if key == QtCore.Qt.Key_Up:
                    self.addop((self.scroll, 0, 1))

                if key == QtCore.Qt.Key_End:
                    self.moveCursor(Directions.CtrlEnd)
                    self.addop((self.draw,))

                if key == QtCore.Qt.Key_Home:
                    self.moveCursor(Directions.CtrlHome)
                    self.addop((self.draw,))

                return True

            else:  # elif modifiers == QtCore.Qt.NoModifier or modifiers == QtCore.Qt.ShiftModifier::

                if key == QtCore.Qt.Key_Escape:
                    self.selector.resetSelections()
                    self.addop((self.draw,))

                if key == QtCore.Qt.Key_Left:
                    self.moveCursor(Directions.Left)
                    self.addop((self.draw,))

                if key == QtCore.Qt.Key_Right:
                    self.moveCursor(Directions.Right)
                    self.addop((self.draw,))

                if key == QtCore.Qt.Key_Down:
                    self.moveCursor(Directions.Down)
                    self.addop((self.draw,))

                if key == QtCore.Qt.Key_End:
                    self.moveCursor(Directions.End)
                    self.addop((self.draw,))

                if key == QtCore.Qt.Key_Home:
                    self.moveCursor(Directions.Home)
                    self.addop((self.draw,))

                if key == QtCore.Qt.Key_Up:
                    self.moveCursor(Directions.Up)
                    self.addop((self.draw,))

                if key == QtCore.Qt.Key_PageDown:
                    self.addop((self.scrollPages, 1))

                if key == QtCore.Qt.Key_PageUp:
                    self.addop((self.scrollPages, -1))

                if self.isInEditMode():
                    self.handleEditMode(modifiers, key, event)

                return True

        return False

    def isEditable(self):
        return True

    def setEditMode(self, mode):
        super(BinViewMode, self).setEditMode(mode)

        letters = string.ascii_letters + string.digits + ' .;\':;=\"?-!()/\\_'

        # disable/enable shortcuts
        if not mode:
            self.transformationEngine = self.original_textdecorator
            self.transformationEngine.reset()
            self.draw(refresh=True)

    """
    def handleKeyPressEvent(self, modifier, key):
        if modifier == QtCore.Qt.ShiftModifier:
            #self.startSelection()
            return True

    def handleKeyReleaseEvent(self, modifier, key):
        if modifier == QtCore.Qt.ShiftModifier:
            self.stopSelection()
            return True
    """

    def addop(self, t):
        self.Ops.append(t)

    def getHeaderInfo(self):
        return 'Binary'


text:
package com.jk.db.dataaccess.core;

import java.sql.PreparedStatement;
import java.sql.SQLException;

// TODO: Auto-generated Javadoc
/**
 * The Interface Updater.
 *
 * @author Jalal Kiswani
 */
public interface JKUpdater {

	/**
	 * Gets the update sql.
	 *
	 * @return the update sql
	 */
	public String getStatement();

	/**
	 * Sets the paramters.
	 *
	 * @param ps the new paramters
	 * @throws SQLException the SQL exception
	 */
	public void setParamters(PreparedStatement ps) throws SQLException;

	public default Boolean isMultiTenant() {
		return null;
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php
require_once './vendor/autoload.php';
use Twilio\TwiML\VoiceResponse;

$response = new VoiceResponse();
$dial = $response->dial('', ['record' => 'record-from-answer', 'recordingTrack' => 'inbound', 'recordingStatusCallback' => 'https://www.myexample.com/recording-handler']);
$dial->number('+15551239876');

echo $response;


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true" name="AM-SetAccessTokenResponse-ClientCred">
    <Set>
        <Payload contentType="application/json">{
  "access_token": "{oauthv2accesstoken.OA-IssueAccessTokenClientCreds.access_token}",
  "expires_in": {oauthv2accesstoken.OA-IssueAccessTokenClientCreds.expires_in},
  "scope": "{oauthv2accesstoken.OA-IssueAccessTokenClientCreds.scope}"
}</Payload>
    </Set>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <AssignTo createNew="false" transport="http" type="response"/>
</AssignMessage>


text:
// @APIVersion v2.1
// @APITitle CIAO Controller API
// @APIDescription Ciao controller is responsible for policy choices around tenant workloads. It provides compute API endpoints for access from ciao-cli and ciao-webui over HTTPS.
// @Contact https://github.com/01org/ciao/wiki/Package-maintainers
// @License Apache License, Version 2.0
// @LicenseUrl http://www.apache.org/licenses/LICENSE-2.0
// @BasePath http://<ciao-controller-server>:8774/v2.1/

package main

import (
	"context"
	"flag"
	"fmt"
	"net/http"
	"os"
	"sync"

	"github.com/01org/ciao/ciao-controller/api"
	"github.com/01org/ciao/ciao-controller/internal/datastore"
	"github.com/01org/ciao/ciao-controller/internal/quotas"
	storage "github.com/01org/ciao/ciao-storage"
	"github.com/01org/ciao/clogger/gloginterface"
	"github.com/01org/ciao/database"
	"github.com/01org/ciao/openstack/block"
	"github.com/01org/ciao/openstack/compute"
	osIdentity "github.com/01org/ciao/openstack/identity"
	osimage "github.com/01org/ciao/openstack/image"
	"github.com/01org/ciao/osprepare"
	"github.com/01org/ciao/ssntp"
	"github.com/golang/glog"
	"github.com/gorilla/mux"
	"github.com/pkg/errors"
)

type tenantConfirmMemo struct {
	ch  chan struct{}
	err error
}

type controller struct {
	storage.BlockDriver
	client              controllerClient
	ds                  *datastore.Datastore
	id                  *identity
	apiURL              string
	tenantReadiness     map[string]*tenantConfirmMemo
	tenantReadinessLock sync.Mutex
	qs                  *quotas.Quotas
}

var cert = flag.String("cert", "", "Client certificate")
var caCert = flag.String("cacert", "", "CA certificate")
var serverURL = flag.String("url", "", "Server URL")
var identityURL = "identity:35357"
var serviceUser = "csr"
var servicePassword = ""
var volumeAPIPort = block.APIPort
var computeAPIPort = compute.APIPort
var imageAPIPort = osimage.APIPort
var controllerAPIPort = api.Port
var httpsCAcert = "/etc/pki/ciao/ciao-controller-cacert.pem"
var httpsKey = "/etc/pki/ciao/ciao-controller-key.pem"
var tablesInitPath = flag.String("tables_init_path", "/var/lib/ciao/data/controller/tables", "path to csv files")
var workloadsPath = flag.String("workloads_path", "/var/lib/ciao/data/controller/workloads", "path to yaml files")
var noNetwork = flag.Bool("nonetwork", false, "Debug with no networking")
var persistentDatastoreLocation = flag.String("database_path", "/var/lib/ciao/data/controller/ciao-controller.db", "path to persistent database")
var imageDatastoreLocation = flag.String("image_database_path", "/var/lib/ciao/data/image/ciao-image.db", "path to image persistent database")
var transientDatastoreLocation = flag.String("stats_path", "/tmp/ciao-controller-stats.db", "path to stats database")
var logDir = "/var/lib/ciao/logs/controller"

var imagesPath = flag.String("images_path", "/var/lib/ciao/images", "path to ciao images")

var cephID = flag.String("ceph_id", "", "ceph client id")

var cnciVCPUs = 4
var cnciMem = 2048
var cnciDisk = 2048
var adminSSHKey = ""

// default password set to "ciao"
var adminPassword = "$6$rounds=4096$w9I3hR4g/hu$AnYjaC2DfznbPSG3vxsgtgAS4mJwWBkcR74Y/KHNB5OsfAlA4gpU5j6CHWMOkkt9j.9d7OYJXJ4icXHzKXTAO."

func init() {
	flag.Parse()

	logDirFlag := flag.Lookup("log_dir")
	if logDirFlag == nil {
		glog.Errorf("log_dir does not exist")
		return
	}

	if logDirFlag.Value.String() == "" {
		logDirFlag.Value.Set(logDir)
	}

	if err := os.MkdirAll(logDirFlag.Value.String(), 0755); err != nil {
		glog.Errorf("Unable to create log directory (%s) %v", logDir, err)
		return
	}
}

func main() {
	var wg sync.WaitGroup
	var err error

	ctl := new(controller)
	ctl.tenantReadiness = make(map[string]*tenantConfirmMemo)
	ctl.ds = new(datastore.Datastore)
	ctl.qs = new(quotas.Quotas)

	dsConfig := datastore.Config{
		PersistentURI:     "file:" + *persistentDatastoreLocation,
		TransientURI:      "file:" + *transientDatastoreLocation,
		InitWorkloadsPath: *workloadsPath,
	}

	err = ctl.ds.Init(dsConfig)
	if err != nil {
		glog.Fatalf("unable to Init datastore: %s", err)
		return
	}

	ctl.qs.Init()
	populateQuotasFromDatastore(ctl.qs, ctl.ds)

	config := &ssntp.Config{
		URI:    *serverURL,
		CAcert: *caCert,
		Cert:   *cert,
		Log:    ssntp.Log,
	}

	ctl.client, err = newSSNTPClient(ctl, config)
	if err != nil {
		// spawn some retry routine?
		glog.Fatalf("unable to connect to SSNTP server")
		return
	}

	ssntpClient := ctl.client.ssntpClient()
	clusterConfig, err := ssntpClient.ClusterConfiguration()
	if err != nil {
		glog.Fatalf("Unable to retrieve Cluster Configuration: %v", err)
		return
	}

	volumeAPIPort = clusterConfig.Configure.Controller.VolumePort
	computeAPIPort = clusterConfig.Configure.Controller.ComputePort
	controllerAPIPort = clusterConfig.Configure.Controller.CiaoPort
	httpsCAcert = clusterConfig.Configure.Controller.HTTPSCACert
	httpsKey = clusterConfig.Configure.Controller.HTTPSKey
	identityURL = clusterConfig.Configure.IdentityService.URL
	serviceUser = clusterConfig.Configure.Controller.IdentityUser
	servicePassword = clusterConfig.Configure.Controller.IdentityPassword
	if *cephID == "" {
		*cephID = clusterConfig.Configure.Storage.CephID
	}

	if clusterConfig.Configure.Controller.CNCIVcpus != 0 {
		cnciVCPUs = clusterConfig.Configure.Controller.CNCIVcpus
	}

	if clusterConfig.Configure.Controller.CNCIMem != 0 {
		cnciMem = clusterConfig.Configure.Controller.CNCIMem
	}

	if clusterConfig.Configure.Controller.CNCIDisk != 0 {
		cnciDisk = clusterConfig.Configure.Controller.CNCIDisk
	}

	adminSSHKey = clusterConfig.Configure.Controller.AdminSSHKey

	if clusterConfig.Configure.Controller.AdminPassword != "" {
		adminPassword = clusterConfig.Configure.Controller.AdminPassword
	}

	ctl.ds.GenerateCNCIWorkload(cnciVCPUs, cnciMem, cnciDisk, adminSSHKey, adminPassword)

	database.Logger = gloginterface.CiaoGlogLogger{}

	logger := gloginterface.CiaoGlogLogger{}
	osprepare.Bootstrap(context.TODO(), logger)
	osprepare.InstallDeps(context.TODO(), controllerDeps, logger)

	idConfig := identityConfig{
		endpoint:        identityURL,
		serviceUserName: serviceUser,
		servicePassword: servicePassword,
	}

	ctl.BlockDriver = func() storage.BlockDriver {
		driver := storage.CephDriver{
			ID: *cephID,
		}
		return driver
	}()

	ctl.id, err = newIdentityClient(idConfig)
	if err != nil {
		glog.Fatal("Unable to authenticate to Keystone: ", err)
		return
	}

	wg.Add(1)
	go ctl.startComputeService()

	wg.Add(1)
	go ctl.startVolumeService()

	wg.Add(1)
	go ctl.startImageService()

	host := clusterConfig.Configure.Controller.ControllerFQDN
	if host == "" {
		host, _ = os.Hostname()
	}
	ctl.apiURL = fmt.Sprintf("https://%s:%d", host, controllerAPIPort)

	wg.Add(1)
	go ctl.startCiaoService()

	wg.Wait()
	ctl.qs.Shutdown()
	ctl.ds.Exit()
	ctl.client.Disconnect()
}

func (c *controller) startCiaoService() error {
	config := api.Config{URL: c.apiURL, CiaoService: c}

	r := api.Routes(config)
	if r == nil {
		return errors.New("Unable to start Ciao API Service")
	}

	// wrap each route in keystone validation.
	validServices := []osIdentity.ValidService{
		{ServiceType: "compute", ServiceName: "ciao"},
		{ServiceType: "compute", ServiceName: "nova"},
	}

	validAdmins := []osIdentity.ValidAdmin{
		{Project: "service", Role: "admin"},
		{Project: "admin", Role: "admin"},
	}

	err := r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
		h := osIdentity.Handler{
			Client:        c.id.scV3,
			Next:          route.GetHandler(),
			ValidServices: validServices,
			ValidAdmins:   validAdmins,
		}

		route.Handler(h)

		return nil
	})

	if err != nil {
		return err
	}

	service := fmt.Sprintf(":%d", controllerAPIPort)

	glog.Infof("Starting ciao API on port %d\n", controllerAPIPort)

	err = http.ListenAndServeTLS(service, httpsCAcert, httpsKey, r)
	if err != nil {
		glog.Fatal(err)
	}

	return nil
}


text:
<?php
namespace backend\assets;

use yii\base\Exception;
use yii\web\AssetBundle;

/**
 * AdminLte AssetBundle
 * @since 0.1
 */
class MaterialAsset extends AssetBundle
{
    public $sourcePath = '@vendor/mervick/material-design-icons';
    public $css = [
        'css/material-icons.css',
    ];
    public $js = [

    ];
    public $depends = [
    ];

}


text:
package org.apache.shardingsphere.sql.parser.sql.dialect.statement.postgresql.ddl;

import lombok.ToString;
import org.apache.shardingsphere.sql.parser.sql.common.statement.ddl.AlterFunctionStatement;
import org.apache.shardingsphere.sql.parser.sql.dialect.statement.postgresql.PostgreSQLStatement;

/**
 * PostgreSQL alter function statement.
 */
@ToString
public final class PostgreSQLAlterFunctionStatement extends AlterFunctionStatement implements PostgreSQLStatement {
}


text:
@class GITRefStore, GITRef;

@interface GITRefStoreTests : GHTestCase {
    GITRefStore *store;
}
@property(readwrite,retain) GITRefStore *store;

@end


text:
package resources.java;

import com.test.api_v2_mutable.MutableProto2Mutable.M1;
import com.test.api_v2_mutable.MutableProto2Mutable.M1.TestOneofCase;
import com.test.api_v2_mutable.MutableProto2Mutable.Shapes;
import com.test.api_v2_mutable.MutableProto2Mutable.weirdEnum_name;
import com.test.api_v2_mutable.MutableProto2Mutable.weirdMessage_name;
import java.util.List;
import java.util.Map;

/**
 * Test references to generated java code (w/ java_mutable_api = true).
 *
 * <p>Cross between {@link Proto1User} and {@link Proto2User}.
 */
@SuppressWarnings("unused") // Loaded by IntelliJ test.
public class Proto2MutableUser {

  //---- Single primitive (like proto1)
  public static int getSinglePrimitive(M1 caretAfterThis) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.single_primitive
    return caretAfterThis.getSinglePrimitive();
  }

  public static M1 setSinglePrimitive(M1 caretAfterThis, int value) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.single_primitive
    return caretAfterThis.setSinglePrimitive(value);
  }

  //---- Repeated primitive (more like proto2)
  public static int getRepeatedPrimitiveCount(M1 caretAfterThis) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.repeated_primitive
    return caretAfterThis.getRepeatedPrimitiveCount();
  }

  public static List<Integer> getRepeatedPrimitiveList(M1 caretAfterThis) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.repeated_primitive
    return caretAfterThis.getRepeatedPrimitiveList();
  }

  // Almost like proto1, but named differently.
  public static List<Integer> getMutableRepeatedPrimitiveList(M1 caretAfterThis) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.repeated_primitive
    return caretAfterThis.getMutableRepeatedPrimitiveList();
  }

  public static M1 addAllRepeatedInt32Field(M1 caretAfterThis, Iterable<? extends Integer> values) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.repeated_primitive
    return caretAfterThis.addAllRepeatedPrimitive(values);
  }

  //---- Single string ("AsBytes" is like proto1 instead of proto2).

  public static M1 setSingleStringAsBytes(M1 caretAfterThis, byte[] value) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.single_string
    return caretAfterThis.setSingleStringAsBytes(value);
  }

  //---- Repeated string

  // Almost like proto1, but named differently.
  public static List<byte[]> getRepeatedStringListAsBytes(M1 caretAfterThis) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.repeated_string
    return caretAfterThis.getRepeatedStringListAsBytes();
  }

  //---- Single message
  public static M1.NestedM1 getMutableSingleMessage(M1 caretAfterThis) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.single_message
    return caretAfterThis.getMutableSingleMessage();
  }
  // no "OrBuilder" variant.
  // no merge

  //---- Repeated message
  public static List<M1.NestedM1> getMutableRepeatedMessageList(M1 caretAfterThis) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.repeated_message
    return caretAfterThis.getMutableRepeatedMessageList();
  }

  public static M1 addAllRepeatedMessage(M1 caretAfterThis, List<? extends M1.NestedM1> values) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.repeated_message
    return caretAfterThis.addAllRepeatedMessage(values);
  }

  //---- Single enum
  public static Shapes getSingleEnum(M1 caretAfterThis) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.single_enum
    return caretAfterThis.getSingleEnum();
  }

  public static M1 setSingleEnum(M1 caretAfterThis) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.single_enum
    return caretAfterThis.setSingleEnum(
        // EXPECT-NEXT: Proto2Mutable.proto / Shapes
        /* caretAfterThis */ Shapes.
            // EXPECT-NEXT: Proto2Mutable.proto / CIRCLE
            /* caretAfterThis */ CIRCLE);
  }

  // EXPECT-NEXT: Proto2Mutable.proto / weirdEnum_name
  public static /* caretAfterThis */ weirdEnum_name checkWeirdEnum() {
    // EXPECT-NEXT: Proto2Mutable.proto / weirdValue_name
    return weirdEnum_name./* caretAfterThis */ weirdValue_name;
  }

  //---- Map
  public static Map<Integer, Integer> getTestMap(M1 caretAfterThis) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.test_map
    return caretAfterThis.getTestMap();
  }

  public static Map<Integer, Integer> getMutableTestMap(M1 caretAfterThis) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.test_map
    return caretAfterThis.getMutableTestMap();
  }

  public static M1 putAllTestMap(M1 caretAfterThis, Map<Integer, Integer> values) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.test_map
    return caretAfterThis.putAllTestMap(values);
  }

  //---- Oneof

  public static TestOneofCase getOneofFieldCase(M1 caretAfterThis) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.test_oneof
    return caretAfterThis.getTestOneofCase();
  }

  public static M1 clearOneofField(M1 caretAfterThis) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.test_oneof
    return caretAfterThis.clearTestOneof();
  }

  public static TestOneofCase enumMethods(int value) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.test_oneof
    return TestOneofCase./* caretAfterThis */ forNumber(value);
  }

  public static TestOneofCase oneofEnumValue(int x) {
    if (x > 0) {
      // EXPECT-NEXT: Proto2Mutable.proto / M1.test_oneof
      return /* caretAfterThis */ TestOneofCase.
          // EXPECT-NEXT: Proto2Mutable.proto / M1.string_choice
          /* caretAfterThis */ STRING_CHOICE;
    } else {
      // EXPECT-NEXT: Proto2Mutable.proto / M1.test_oneof
      return TestOneofCase./* caretAfterThis */ TESTONEOF_NOT_SET;
    }
  }

  public static boolean hasIntChoice(M1 caretAfterThis) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.int_choice
    return caretAfterThis.hasIntChoice();
  }

  public static String getStringChoice(M1 caretAfterThis) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.string_choice
    return caretAfterThis.getStringChoice();
  }

  //---- Group
  // EXPECT-NEXT: Proto2Mutable.proto / M1.SingleGroupField
  public static M1./* caretAfterThis */ SingleGroupField getSingleGroupField(M1 caretAfterThis) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.singlegroupfield
    return caretAfterThis.getSingleGroupField();
  }

  //---- Second message type
  public static int getSinglePrimitiveM2(weirdMessage_name caretAfterThis) {
    // EXPECT-NEXT: Proto2Mutable.proto / weirdMessage_name.single_primitive
    return caretAfterThis.getSinglePrimitive();
  }

  public static boolean hasRepeatedPrimitiveCountM2(weirdMessage_name caretAfterThis) {
    // EXPECT-NEXT: Proto2Mutable.proto / weirdMessage_name.Repeated_primitiveCount
    return caretAfterThis.hasRepeatedPrimitiveCount();
  }

  public static int getRepeatedPrimitiveCountM2(weirdMessage_name caretAfterThis) {
    // EXPECT-NEXT: Proto2Mutable.proto / weirdMessage_name.Repeated_primitiveCount
    return caretAfterThis.getRepeatedPrimitiveCount();
  }

  //---- Nested message single primitive
  public static M1.NestedM1 setSinglePrimitive(M1.NestedM1 caretAfterThis, int value) {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.NestedM1.single_primitive
    return caretAfterThis.setSinglePrimitive(value);
  }

  //---- Grab the field constant

  public int getSinglePrimitiveFieldNumber() {
    // EXPECT-NEXT: Proto2Mutable.proto / M1.single_primitive
    return M1./* caretAfterThis */ SINGLE_PRIMITIVE_FIELD_NUMBER;
  }
}


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class DropPacksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::dropIfExists('packs');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::create('packs', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('egg_id');
            $table->char('uuid', 36)->unique();
            $table->string('name');
            $table->string('version');
            $table->text('description')->nullable();
            $table->tinyInteger('selectable')->default(1);
            $table->tinyInteger('visible')->default(1);
            $table->tinyInteger('locked')->default(0);
            $table->timestamps();
        });

        Schema::table('packs', function (Blueprint $table) {
            $table->foreign('egg_id')->references('id')->on('eggs')->cascadeOnDelete();
        });
    }
}


text:
from django.db import models

class PublishMixin(models.Model):
    """
    provides a nullable `published` field and an auto-tracked `modified` field

    >>> from datetime import datetime, timedelta
    >>> from bulbs2.content.mixins import TitleMixin, DescriptionMixin
    >>> from bulbs2.publishing.managers import PublishedManager, ScheduledManager, DraftManager
    >>> from bulbs2.publishing.mixins import PublishMixin
    >>> from django.db import models
    >>>
    >>> class Article(TitleMixin, DescriptionMixin, PublishMixin):
    ...     fun_to_read = models.BooleanField(default=True)
    ...     published_objects = PublishedManager()
    ...     scheduled_objects = ScheduledManager()
    ...     draft_objects = DraftManager()
    ...
    >>> article = Article.objects.create(
    ...     name="How to Write Good Django Docs",
    ...     subhead="A Masterclass",
    ...     description="Written by a total egomaniac"
    ...     fun_to_read=False)
    >>> assert article not in Article.published_objects.all()
    >>> assert article in Article.draft_objects.all()
    >>> article.published = datetime.now() + timedelta(days=1)
    >>> article.save()
    >>> assert article in Article.scheduled_objects.all()
    """

    class Meta(object):
        abstract = True

    published = models.DateTimeField(null=True, default=None, blank=True)
    modified = models.DateTimeField(auto_now=True)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Microsoft.Deployment.WindowsInstaller;
using WixSharp.CommonTasks;
using IO = System.IO;

using System.IO;

using System.Diagnostics;

namespace WixSharp
{
    /// <summary>
    /// Extends <see cref="T:WixSharp.Project"/> with runtime event-driven behavior ans managed UI (see <see cref="T:WixSharp.ManagedUI"/> and
    /// <see cref="T:WixSharp.UI.Forms.ManagedForm"/>).
    /// <para>
    /// The managed project has three very important events that are raised during deployment at run: Load/BeforeInstall/AfterInstall.
    /// </para>
    /// <remark>
    /// ManagedProject still maintains backward compatibility for the all older features. That is why it is important to distinguish the use cases
    /// associated with the project class members dedicated to the same problem domain but resolving the problems in different ways:
    /// <para><c>UI support</c></para>
    /// <para>   project.UI - to be used to define native MSI/WiX UI.</para>
    /// <para>   project.CustomUI - to be used for minor to customization of native MSI/WiX UI and injection of CLR dialogs. </para>
    /// <para>   project.ManagedUI - to be used to define managed Embedded UI. It allows full customization of the UI</para>
    /// <para> </para>
    /// <para><c>Events</c></para>
    /// <para>   project.WixSourceGenerated</para>
    /// <para>   project.WixSourceFormated</para>
    /// <para>   project.WixSourceSaved - to be used at compile time to customize WiX source code (XML) generation.</para>
    /// <para> </para>
    /// <para>   project.Load</para>
    /// <para>   project.BeforeInstall</para>
    /// <para>   project.AfterInstall - to be used at runtime (msi execution) to customize deployment behaver.</para>
    /// </remark>
    /// </summary>
    /// <example>The following is an example of a simple setup handling the three setup events at runtime.
    /// <code>
    /// var project = new ManagedProject("ManagedSetup",
    ///                   new Dir(@"%ProgramFiles%\My Company\My Product",
    ///                       new File(@"..\Files\bin\MyApp.exe")));
    ///
    /// project.GUID = new Guid("6f330b47-2577-43ad-9095-1861ba25889b");
    ///
    /// project.ManagedUI = ManagedUI.Empty;
    ///
    /// project.Load += project_Load;
    /// project.BeforeInstall += project_BeforeInstall;
    /// project.AfterInstall += project_AfterInstall;
    ///
    /// project.BuildMsi();
    /// </code>
    /// </example>
    public partial class ManagedProject : Project
    {
        //some materials to consider: http://cpiekarski.com/2012/05/18/wix-custom-action-sequencing/

        /// <summary>
        /// Initializes a new instance of the <see cref="ManagedProject"/> class.
        /// </summary>
        public ManagedProject()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ManagedProject"/> class.
        /// </summary>
        /// <param name="name">The name of the project. Typically it is the name of the product to be installed.</param>
        /// <param name="items">The project installable items (e.g. directories, files, registry keys, Custom Actions).</param>
        public ManagedProject(string name, params WixObject[] items)
            : base(name, items)
        {
        }

        /// <summary>
        /// Gets or sets a value indicating whether the full or reduced custom drawing algorithm should be used for rendering the Features dialog
        /// tree view control. The reduced algorithm involves no manual positioning of the visual elements so it handles better custom screen resolutions.
        /// However it also leads to the slightly less intuitive tree view item appearance.
        /// <para>Reduced custom drawing will render disabled tree view items with the text grayed out.</para>
        /// <para>Full custom drawing will render disabled tree view items with the checkbox grayed out.</para>
        /// </summary>
        /// <value>
        /// <c>true</c> (default) if custom drawing should be reduced otherwise, <c>false</c>.
        /// </value>
        public bool MinimalCustomDrawing
        {
            get
            {
                return Properties.Where(x => x.Name == "WixSharpUI_TreeNode_TexOnlyDrawing").FirstOrDefault() != null;
            }

            set
            {
                if (value)
                {
                    var prop = Properties.Where(x => x.Name == "WixSharpUI_TreeNode_TexOnlyDrawing").FirstOrDefault();
                    if (prop != null)
                        prop.Value = "true";
                    else
                        this.AddProperty(new Property("WixSharpUI_TreeNode_TexOnlyDrawing", "true"));
                }
                else
                {
                    Properties = Properties.Where(x => x.Name != "WixSharpUI_TreeNode_TexOnlyDrawing").ToArray();
                }
            }
        }

        /// <summary>
        /// Event handler of the ManagedSetup for the MSI runtime events.
        /// </summary>
        /// <param name="e">The <see cref="SetupEventArgs"/> instance containing the event data.</param>
        public delegate void SetupEventHandler(SetupEventArgs e);

        /// <summary>
        /// Indicates if the installations should be aborted if managed event handler throws an unhanded exception.
        /// <para>
        /// Aborting is the default behavior if this field is not set.
        /// </para>
        /// </summary>
        public bool? AbortSetupOnUnhandledExceptions;

        /// <summary>
        /// Occurs on EmbeddedUI initialized but before the first dialog is displayed. It is only invoked if ManagedUI is set.
        /// </summary>
        public event SetupEventHandler UIInitialized;

        /// <summary>
        /// Occurs on EmbeddedUI loaded and ShellView (main window) is displayed but before first dialog is positioned within ShellView.
        /// It is only invoked if ManagedUI is set.
        /// <para>Note that this event is fired on the loading the UI main window thus it's not a good stage for any decision regarding
        /// aborting/continuing the whole setup process. That is UILoaded event will ignore any value set to SetupEventArgs.Result by the user.
        /// </para>
        /// </summary>
        public event SetupEventHandler UILoaded;

        /// <summary>
        /// Occurs before AppSearch standard action.
        /// </summary>
        public event SetupEventHandler Load;

        /// <summary>
        /// Occurs before InstallFiles standard action.
        /// </summary>
        public event SetupEventHandler BeforeInstall;

        /// <summary>
        /// Occurs after InstallFiles standard action. The event is fired from the elevated execution context.
        /// </summary>
        public event SetupEventHandler AfterInstall;

        /// <summary>
        /// An instance of ManagedUI defining MSI UI dialogs sequence. User should set it if he/she wants native MSI dialogs to be
        /// replaced by managed ones.
        /// </summary>
        public IManagedUI ManagedUI;

        bool preprocessed = false;

        string thisAsm = typeof(ManagedProject).Assembly.Location;

        bool IsHandlerSet<T>(Expression<Func<T>> expression)
        {
            var name = Reflect.NameOf(expression);
            var handler = expression.Compile()() as Delegate;
            return (handler != null);
        }

        void Bind<T>(Expression<Func<T>> expression, When when = When.Before, Step step = null, bool elevated = false)
        {
            var name = Reflect.NameOf(expression);
            var handler = expression.Compile()() as Delegate;

            const string wixSharpProperties = "WIXSHARP_RUNTIME_DATA";

            if (handler != null)
            {
                if (this.AbortSetupOnUnhandledExceptions.HasValue)
                {
                    var abortOnErrorName = "WIXSHARP_ABORT_ON_ERROR";

                    if (!Properties.Any(p => p.Name == abortOnErrorName))
                        this.Properties = Properties.Add(new Property(abortOnErrorName, this.AbortSetupOnUnhandledExceptions.Value.ToString()));
                }

                //foreach (string handlerAsm in handler.GetInvocationList().Select(x => x.Method.DeclaringType.Assembly.Location))
                foreach (var type in handler.GetInvocationList().Select(x => x.Method.DeclaringType))
                {
                    string location = type.Assembly.Location;

                    //Resolving scriptAsmLocation is not properly tested yet
                    bool resolveInMemAsms = true;

                    if (resolveInMemAsms)
                    {
                        if (location.IsEmpty())
                            location = type.Assembly.GetLocation();
                    }

                    if (location.IsEmpty())
                        throw new ApplicationException($"The location of the assembly for ManagedProject event handler ({type}) cannot be obtained.\n" +
                                                        "The assembly must be a file based one but it looks like it was loaded from memory.\n" +
                                                        "If you are using CS-Script to build MSI ensure it has 'InMemoryAssembly' set to false.");

                    if (!this.DefaultRefAssemblies.Contains(location))
                        this.DefaultRefAssemblies.Add(location);
                }

                this.Properties = this.Properties.Add(new Property("WixSharp_{0}_Handlers".FormatWith(name), GetHandlersInfo(handler as MulticastDelegate)));

                string dllEntry = "WixSharp_{0}_Action".FormatWith(name);
                if (step != null)
                {
                    if (elevated)
                        this.Actions = this.Actions.Add(new ElevatedManagedAction(dllEntry)
                        {
                            Id = new Id(dllEntry),
                            ActionAssembly = thisAsm,
                            Return = Return.check,
                            When = when,
                            Step = step,
                            Condition = Condition.Create("1"),
                            UsesProperties = "WixSharp_{0}_Handlers,{1},{2}".FormatWith(name, wixSharpProperties, DefaultDeferredProperties),
                        });
                    else
                        this.Actions = this.Actions.Add(new ManagedAction(dllEntry) { Id = new Id(dllEntry), ActionAssembly = thisAsm, Return = Return.check, When = when, Step = step, Condition = Condition.Create("1") });
                }
            }
        }

        void AddCancelFromUIIHandler()
        {
            string dllEntry = "CancelRequestHandler";
            this.Actions = this.Actions.Add(new ElevatedManagedAction(dllEntry)
            {
                Id = new Id(dllEntry),
                ActionAssembly = thisAsm,
                Return = Return.check,
                When = When.Before,
                Step = Step.InstallFinalize,
                Condition = Condition.NOT_BeingRemoved,
                UsesProperties = "UpgradeCode"
            });
        }

        /// <summary>
        /// The default properties mapped for use with the deferred custom actions. See <see cref="ManagedAction.UsesProperties"/> for the details.
        /// <para>The default value is "INSTALLDIR,UILevel"</para>
        /// </summary>
        public string DefaultDeferredProperties
        {
            set { defaultDeferredProperties = value; }
            get
            {
                return string.Join(",", this.Properties
                                            .Where(x => x.IsDeferred)
                                            .Select(x => x.Name)
                                            .Concat(defaultDeferredProperties.Split(','))
                                            .Where(x => x.IsNotEmpty())
                                            .Select(x => x.Trim())
                                            .ToArray());
            }
        }

        string defaultDeferredProperties = "INSTALLDIR,UILevel,ProductName";

        /// <summary>
        /// Flags that indicates if <c>WixSharp_InitRuntime_Action</c> custom action should be always scheduled. The default value is <c>true</c>.
        /// <para><c>WixSharp_InitRuntime_Action</c> is the action, which ManagedSetup performs at startup (before AppSearch).
        /// In this action the most important MSI properties are pushed into Session.CustomActionData. These properties are typically consumed
        /// from other custom actions (e.g. Project.AfterInstall event) and they are:
        /// <list type="bullet">
        /// <item><description>Installed</description></item>
        /// <item><description>REMOVE</description></item>
        /// <item><description>ProductName</description></item>
        /// <item><description>REINSTALL</description></item>
        /// <item><description>UPGRADINGPRODUCTCODE</description></item>
        /// <item><description>UILevel</description></item>
        /// <item><description>WIXSHARP_MANAGED_UI</description></item>
        /// </list>
        /// </para>
        /// <para>However in same cases (e.g. oversizes msi file) it is desirable to minimize amount of time the msi loaded into memory
        /// (e.g. by custom actions). Thus setting AlwaysScheduleInitRuntime to <c>false</c> will prevent scheduling <c>WixSharp_InitRuntime_Action</c>
        /// unless any of the ManagedProject events (e.g. Project.AfterInstall) has user handler assigned.
        /// </para>
        /// </summary>
        public bool AlwaysScheduleInitRuntime = true;

        override internal void Preprocess()
        {
            //Debug.Assert(false);
            base.Preprocess();

            if (!preprocessed)
            {
                preprocessed = true;

                //It is too late to set prerequisites. Launch conditions are evaluated after UI is popped up.
                //this.SetNetFxPrerequisite(Condition.Net35_Installed, "Please install .NET v3.5 first.");

                if (ManagedUI?.Icon != null)
                {
                    this.AddBinary(new Binary(new Id("ui_shell_icon"), ManagedUI.Icon));
                }

                string dllEntry = "WixSharp_InitRuntime_Action";

                bool needInvokeInitRuntime = (IsHandlerSet(() => UIInitialized)
                                           || IsHandlerSet(() => Load)
                                           || IsHandlerSet(() => UILoaded)
                                           || IsHandlerSet(() => BeforeInstall)
                                           || IsHandlerSet(() => AfterInstall)
                                           || AlwaysScheduleInitRuntime);
                if (needInvokeInitRuntime)
                    this.AddAction(new ManagedAction(dllEntry)
                    {
                        Id = new Id(dllEntry),
                        ActionAssembly = thisAsm,
                        Return = Return.check,
                        When = When.Before,
                        Step = Step.AppSearch,
                        Condition = Condition.Always
                    });

                if (ManagedUI != null)
                {
                    this.AddProperty(new Property("WixSharp_UI_INSTALLDIR", ManagedUI.InstallDirId ?? "INSTALLDIR"));

                    ManagedUI.BeforeBuild(this);

                    InjectDialogs("WixSharp_InstallDialogs", ManagedUI.InstallDialogs);
                    InjectDialogs("WixSharp_ModifyDialogs", ManagedUI.ModifyDialogs);

                    this.EmbeddedUI = new EmbeddedAssembly(new Id("WixSharp_EmbeddedUI_Asm"), ManagedUI.GetType().Assembly.Location);

                    this.DefaultRefAssemblies.Add(ManagedUI.GetType().Assembly.Location);

                    Bind(() => UIInitialized);
                    Bind(() => UILoaded);

                    AddCancelFromUIIHandler();
                }

                Bind(() => Load, When.Before, Step.AppSearch);
                Bind(() => BeforeInstall, When.Before, Step.InstallFiles);
                Bind(() => AfterInstall, When.After, Step.InstallFiles, true);
            }
        }

        void InjectDialogs(string name, ManagedDialogs dialogs)
        {
            if (dialogs.Any())
            {
                var dialogsInfo = new StringBuilder();

                foreach (var item in dialogs)
                {
                    if (!this.DefaultRefAssemblies.Contains(item.Assembly.Location))
                        this.DefaultRefAssemblies.Add(item.Assembly.Location);

                    var info = GetDialogInfo(item);

                    ValidateDialogInfo(info);
                    dialogsInfo.Append(info + "\n");
                }
                this.AddProperty(new Property(name, dialogsInfo.ToString().Trim()));
            }
        }

        /// <summary>
        /// Reads and returns the dialog types from the string definition. This method is to be used by WixSharp assembly.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public static List<Type> ReadDialogs(string data)
        {
            return data.Split('\n')
                       .Select(x => x.Trim())
                       .Where(x => x.IsNotEmpty())
                       .Select(x => ManagedProject.GetDialog(x))
                       .ToList();
        }

        static void ValidateDialogInfo(string info)
        {
            try
            {
                GetDialog(info, true);
            }
            catch (Exception)
            {
                //may need to do extra logging; not important for now
                throw;
            }
        }

        static string GetDialogInfo(Type dialog)
        {
            var info = "{0}|{1}".FormatWith(
                                dialog.Assembly.FullName,
                                dialog.FullName);
            return info;
        }

        internal static Type GetDialog(string info)
        {
            return GetDialog(info, false);
        }

        internal static Type GetDialog(string info, bool validate)
        {
            string[] parts = info.Split('|');

            var assembly = System.Reflection.Assembly.Load(parts[0]);

            if (validate)
                ProjectValidator.ValidateAssemblyCompatibility(assembly);

            return assembly.GetType(parts[1]);
        }

        static void ValidateHandlerInfo(string info)
        {
            try
            {
                GetHandler(info);
            }
            catch (Exception)
            {
                //may need to do extra logging; not important for now
                throw;
            }
        }

        internal static string GetHandlersInfo(MulticastDelegate handlers)
        {
            var result = new StringBuilder();

            foreach (Delegate action in handlers.GetInvocationList())
            {
                var handlerInfo = "{0}|{1}|{2}".FormatWith(
                                     action.Method.DeclaringType.Assembly.FullName,
                                     action.Method.DeclaringType.FullName,
                                     action.Method.Name);

                ValidateHandlerInfo(handlerInfo);

                result.AppendLine(handlerInfo);
            }
            return result.ToString().Trim();
        }

        static MethodInfo GetHandler(string info)
        {
            string[] parts = info.Split('|');

            var assembly = System.Reflection.Assembly.Load(parts[0]);

            Type type = null;

            //Ideally need to iterate through the all types in order to find even private ones
            //Though loading some internal (irrelevant) types can fail because of the dependencies.
            try
            {
                assembly.GetTypes().Single(t => t.FullName == parts[1]);
            }
            catch { }

            //If we failed to iterate through the types then try to load the type explicitly. Though in this case it has to be public.
            if (type == null)
                type = assembly.GetType(parts[1]);

            var method = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Static)
                             .Single(m => m.Name == parts[2]);

            return method;
        }

        static void InvokeClientHandler(string info, SetupEventArgs eventArgs)
        {
            MethodInfo method = GetHandler(info);

            if (method.IsStatic)
                method.Invoke(null, new object[] { eventArgs });
            else
                method.Invoke(Activator.CreateInstance(method.DeclaringType), new object[] { eventArgs });
        }

        internal static ActionResult InvokeClientHandlers(Session session, string eventName, IShellView UIShell = null)
        {
            var eventArgs = Convert(session);
            eventArgs.ManagedUIShell = UIShell;

            try
            {
                string handlersInfo = session.Property("WixSharp_{0}_Handlers".FormatWith(eventName));

                if (!string.IsNullOrEmpty(handlersInfo))
                {
                    foreach (string item in handlersInfo.Trim().Split('\n'))
                    {
                        InvokeClientHandler(item.Trim(), eventArgs);
                        if (eventArgs.Result == ActionResult.Failure || eventArgs.Result == ActionResult.UserExit)
                            break;
                    }

                    eventArgs.SaveData();
                }
            }
            catch (Exception e)
            {
                session.Log("WixSharp aborted the session because of the error:" + Environment.NewLine + e.ToPublicString());
                if (session.AbortOnError())
                    eventArgs.Result = ActionResult.Failure;
            }
            return eventArgs.Result;
        }

        internal static ActionResult Init(Session session)
        {
            //System.Diagnostics.Debugger.Launch();
            var data = new SetupEventArgs.AppData();
            try
            {
                data["Installed"] = session["Installed"];
                data["REMOVE"] = session["REMOVE"];
                data["ProductName"] = session["ProductName"];
                data["ProductCode"] = session["ProductCode"];
                data["UpgradeCode"] = session["UpgradeCode"];
                data["REINSTALL"] = session["REINSTALL"];
                data["MsiFile"] = session["OriginalDatabase"];
                data["UPGRADINGPRODUCTCODE"] = session["UPGRADINGPRODUCTCODE"];
                data["UILevel"] = session["UILevel"];
                data["WIXSHARP_MANAGED_UI"] = session["WIXSHARP_MANAGED_UI"];
                data["WIXSHARP_MANAGED_UI_HANDLE"] = session["WIXSHARP_MANAGED_UI_HANDLE"];
            }
            catch (Exception e)
            {
                session.Log(e.Message);
            }

            data.MergeReplace(session["WIXSHARP_RUNTIME_DATA"]);

            session["WIXSHARP_RUNTIME_DATA"] = data.ToString();

            return ActionResult.Success;
        }

        internal static SetupEventArgs Convert(Session session)
        {
            //Debugger.Launch();
            var result = new SetupEventArgs { Session = session };
            try
            {
                string data = session.Property("WIXSHARP_RUNTIME_DATA");
                result.Data.InitFrom(data);
                result.Data.SetEnvironmentVariables();
                session.CustomActionData.SetEnvironmentVariables();
            }
            catch (Exception e)
            {
                session.Log(e.Message);
            }
            return result;
        }
    }
}