text:
class Application
{
    inputDevice: InputDevice;
    mathDevice: MathDevice;
    graphicsDevice: GraphicsDevice;
    requestHandler: RequestHandler;

    fontManager: FontManager;
    shaderManager: ShaderManager;

    draw2D: Draw2D;

    gameSession: GameSession;
    dataShareManager: DataShareManager;
    notificationsManager: NotificationsManager;
    userProfile: UserProfile;

    setButtons: boolean;
    invalidateButtons: boolean;
    intervalID: number;
    hasShutdown: boolean;
    hasGameSessionClosed: boolean;

    currentDataShare: DataShare;
    joinedDataShares: DataShare[];
    foundDataShares: DataShare[];

    joinedGames:
    {
        [id: string]: TicTacToeGame;
    };
    currentGame: TicTacToeGame;
    spriteTextureNames: string[];
    numTextures: number;
    loadedResources: number;

    textures:
    {
        [id: string]: Texture;
    };
    pieceTextures:
    {
        X: Texture;
        O: Texture;
    };

    boardSprite: Draw2DSprite;
    pieceSprites:
    {
        X: Draw2DSprite[]; // an array of cross texture sprites one for each grid square
        O: Draw2DSprite[]; // an array of nought texture sprites one for each grid square
    };

    oldWidth: number;
    oldHeight: number;

    font: Font;
    fontShader: Shader;
    fontTechnique: Technique;
    fontTechniqueParameters: any; //TechniqueParameters;

    maxPlayers = 2;
    stageWidth = 40;
    stageHeight = 30;

    clearColor: any; // v4
    fontColor: any; // v4
    fontBoldColor: any; // v4

    textScale = 1;
    hoverTextScale = 1.1;
    textSpacingY = 2;

    boardOffsetX = 1;
    boardOffsetY = 3;
    boardSizeX = 10;
    boardSizeY = 10;

    init()
    {
        var that = this;
        var requestHandler = this.requestHandler;

        function mappingTableReceived(mappingTable)
        {
            var urlMapping = mappingTable.urlMapping;
            var assetPrefix = mappingTable.assetPrefix;

            that.fontManager.setPathRemapping(urlMapping, assetPrefix);
            that.fontManager.load('fonts/hero.fnt', function (fontObject)
                {
                    that.font = fontObject;
                });

            that.shaderManager.setPathRemapping(urlMapping, assetPrefix);
            that.shaderManager.load('shaders/font.cgfx', function (shaderObject)
                {
                    that.fontShader = shaderObject;
                });

            function textureParams(src)
            {
                return {
                    src : mappingTable.getURL(src),
                    mipmaps : true,
                    onload : function (texture)
                    {
                        if (texture)
                        {
                            that.textures[src] = texture;
                            that.loadedResources += 1;
                        }
                    }
                };
            }

            var spriteTextureNames = that.spriteTextureNames;
            var spriteTextureNamesLength = spriteTextureNames.length;
            var i;
            for (i = 0; i < spriteTextureNamesLength; i += 1)
            {
                that.graphicsDevice.createTexture(textureParams(spriteTextureNames[i]));
            }
        }

        function sessionCreated(gameSession)
        {
            TurbulenzServices.createMappingTable(
                requestHandler,
                gameSession,
                mappingTableReceived
            );

            that.dataShareManager = DataShareManager.create(requestHandler, gameSession);
            that.notificationsManager = NotificationsManager.create(requestHandler, gameSession);

            function profileRecievedFn(currentUser: UserProfile)
            {
                that.userProfile = currentUser;
                that.findDataShares();
            }
            TurbulenzServices.createUserProfile(requestHandler, profileRecievedFn);
        }

        TurbulenzServices.onGameSessionClosed = () =>
        {
            this.hasGameSessionClosed = true;
        };

        var gameSessionOptions = {
            closeExistingSessions: true
        };
        this.gameSession = TurbulenzServices.createGameSession(requestHandler,
                sessionCreated,
                null,
                gameSessionOptions);

        this.intervalID = TurbulenzEngine.setInterval(this.loadingUpdate.bind(this), 100);
    }

    createGame()
    {
        var dataShareCreated = (createdDataShare: DataShare) =>
        {
            this.currentDataShare = createdDataShare;

            var username = this.userProfile.username;
            var currentGame = this.currentGame = TicTacToeGame.create(username, username);
            this.joinedGames[createdDataShare.id] = currentGame;

            this.invalidateButtons = true;
        };
        this.dataShareManager.createDataShare(dataShareCreated);
    }

    findDataShares()
    {
        // We do 2 find requests:
        // - Find all the data shares that the current user is joined to. These games are the games that the current
        //   user is playing (they are still in progress).
        // - Find with no filters to find the first 64 games that can be joined (if the player wants to join some other
        //   users game). When processing this list of joinable games we remove any games which the current user has
        //   already joined.

        this.foundDataShares = null;
        this.joinedDataShares = null;
        this.invalidateButtons = true;

        var joinedDataSharesCallback = (dataShares: DataShare[]) =>
        {
            var joinedDataShares = this.joinedDataShares = dataShares;
            var dataSharesLength = dataShares.length;
            var dataSharesIndex;
            var getJoinedGameStateFn = (dataShare: DataShare) =>
            {
                return (gameStateStore: DataShareGetCBData) =>
                {
                    var ticTacToeGame = TicTacToeGame.create(this.userProfile.username, dataShare.owner);
                    var currentUsername = this.userProfile.username;
                    var users = dataShare.users;
                    var usersLength = users.length;
                    var usersIndex;

                    // only list the first 2 players as joined (possible race condition in joining)
                    for (usersIndex = 0; usersIndex < usersLength; usersIndex += 1)
                    {
                        if (usersIndex < this.maxPlayers)
                        {
                            ticTacToeGame.playerJoined(users[usersIndex]);
                        }
                        else
                        {
                            // if the current player has managed to join a full game then leave it
                            if (currentUsername === users[usersIndex])
                            {
                                dataShare.leave();
                                return;
                            }
                        }
                    }

                    this.joinedGames[dataShare.id] = ticTacToeGame;

                    // don't allow any more players to join full games
                    if (dataShare.joinable && users.length >= this.maxPlayers)
                    {
                        dataShare.setJoinable(false);
                    }

                    if (gameStateStore)
                    {
                        ticTacToeGame.update(gameStateStore.value);
                    }
                    this.invalidateButtons = true;
                };
            }
            for (dataSharesIndex = 0; dataSharesIndex < dataSharesLength; dataSharesIndex += 1)
            {
                var dataShare = dataShares[dataSharesIndex];
                dataShare.get('game-state', getJoinedGameStateFn(dataShare));
            }
        }
        this.dataShareManager.findDataShares({
                user: this.userProfile.username, // find all games that the current user is joined to
                callback: joinedDataSharesCallback
            });

        var foundDataSharesCallback = (dataShares: DataShare[]) =>
        {
            var foundDataShares = this.foundDataShares = [];
            var dataSharesLength = dataShares.length;
            var dataSharesIndex;
            var currentUsername = this.userProfile.username;

            for (dataSharesIndex = 0; dataSharesIndex < dataSharesLength; dataSharesIndex += 1)
            {
                var dataShare = dataShares[dataSharesIndex];
                if (!dataShare.isJoined(currentUsername))
                {
                    foundDataShares.push(dataShare);
                }
            }
            this.invalidateButtons = true;
        }
        // find any joinable datashares
        this.dataShareManager.findDataShares({callback: foundDataSharesCallback});
    }

    playerJoined(notification)
    {
        if (this.currentGame && this.currentDataShare.id === notification.msg.data.dataShareId)
        {
            this.currentGame.playerJoined(notification.sender);
            // since only 1 notification can be sent at a time read the datashare to check if the other player
            // has moved
            this.readMoves();
        }
    }

    yourTurn(notification)
    {
        if (this.currentGame && this.currentDataShare.id === notification.msg.data.dataShareId)
        {
            this.readMoves();
        }
    }

    leaveGame()
    {
        var dataShareLeft = () =>
        {
            delete this.joinedGames[this.currentDataShare.id];
            this.currentGame = null;

            this.currentDataShare = null;

            this.invalidateButtons = true;
            this.findDataShares();
        }
        this.currentDataShare.leave(dataShareLeft);
    }

    toLobby()
    {
        this.currentDataShare = null;
        this.currentGame = null;
        this.findDataShares();
    }

    forfeitGame()
    {
        var currentGame = this.currentGame;
        var gameStateSet = (wasSet: boolean, reason?: string) =>
        {
            if (wasSet)
            {
                currentGame.update();

                var otherUser = currentGame.otherUser;
                if (otherUser)
                {
                    this.notificationsManager.sendInstantNotification({
                        key: 'forfeit',
                        msg: {
                            data: {
                                dataShareId: this.currentDataShare.id,
                            },
                            text: this.userProfile.username + ' forfeit the game'
                        },
                        recipient: otherUser
                    });
                }
                this.invalidateButtons = true;
            }
            else
            {
                if (reason === DataShare.notSetReason.changed)
                {
                    // other player has moved so read the change and then try to forfeit again
                    this.readMoves(this.forfeitGame.bind(this));
                }
                else
                {
                    // the key must be readOnly so just leave the game
                    this.leaveGame();
                }
            }
        }

        // check the round has not already ended (possible after recursion)
        if (!currentGame.roundEnd)
        {
            currentGame.forfeit();
            // do a compare and set in case the other player has taken the first move
            this.currentDataShare.compareAndSet({
                    key: 'game-state',
                    value: currentGame.serialize(),
                    callback: gameStateSet
                });
        }
    }

    getPlayGameFn(dataShare: DataShare): { (): void; }
    {
        return () =>
        {
            this.currentDataShare = dataShare;
            this.currentGame = this.joinedGames[dataShare.id];
            this.readMoves();
        }
    }

    readMoves(callback?: { (): void; }): void
    {
        var getMovesCallback = (gameStateStore: DataShareGetCBData) =>
        {
            if (gameStateStore)
            {
                var serializedGameState = gameStateStore.value;
                this.currentGame.update(serializedGameState);
            }

            this.invalidateButtons = true;
            if (callback)
            {
                callback();
            }
        }
        this.currentDataShare.get('game-state', getMovesCallback);
    }

    getJoinGameFn(dataShare: DataShare): { (): void; }
    {
        return () =>
        {
            var joinedDataShare = (success: boolean) =>
            {
                if (success)
                {
                    var currentDataShare = this.currentDataShare = dataShare;
                    if (currentDataShare.users.length > 2)
                    {
                        // only 2 players should join a game
                        // this possible if 2 people click to join a game at the same time

                        // only the 3rd player will see 3 users (since users is only updated when join is called)
                        // so the 3rd player should leave
                        currentDataShare.setJoinable(false);
                        this.leaveGame();
                        return;
                    }
                    var setJoinableCallback = () =>
                    {
                        var currentUser = this.userProfile.username
                        this.currentGame = TicTacToeGame.create(currentUser, dataShare.owner);
                        this.joinedGames[dataShare.id] = this.currentGame;
                        this.readMoves();

                        var otherUser = this.currentGame.otherUser;
                        if (otherUser)
                        {
                            this.notificationsManager.sendInstantNotification({
                                key: 'player-joined',
                                msg: {
                                    data: {
                                        dataShareId: currentDataShare.id
                                    },
                                    text: currentUser + ' has joined your game'
                                },
                                recipient: otherUser
                            });
                        }
                    }
                    currentDataShare.setJoinable(false, setJoinableCallback);
                }
                else
                {
                    this.findDataShares();
                }
            }
            dataShare.join(joinedDataShare);
        }
    }

    getOnClickFn(x: number, y: number): { (): void; }
    {
        return () =>
        {
            var currentGame = this.currentGame;
            var gameStateSet = (wasSet: boolean, reason?: string) =>
            {
                if (wasSet)
                {
                    currentGame.update();
                    var otherUser = currentGame.otherUser;
                    if (otherUser)
                    {
                        var msgText = 'It\'s your turn';
                        var roundEnd = currentGame.roundEnd;
                        if (roundEnd)
                        {
                            if (roundEnd.winner)
                            {
                                msgText = 'You\'ve lost the game';
                            }
                            if (roundEnd.forfeit)
                            {
                                msgText = 'You\'ve won the game';
                            }
                            if (roundEnd.draw)
                            {
                                msgText = 'The game is a draw';
                            }
                        }
                        this.notificationsManager.sendInstantNotification({
                            key: 'your-turn',
                            msg: {
                                data: {
                                    dataShareId: this.currentDataShare.id
                                },
                                text: msgText
                            },
                            recipient: otherUser
                        });
                    }
                    if (currentGame.roundEnd)
                    {
                        this.invalidateButtons = true;
                    }
                }
                else
                {
                    if (reason === DataShare.notSetReason.changed)
                    {
                        // other player has taken the first move or forfeit so get the moves again and ignore the click
                        this.readMoves();
                    }
                    else
                    {
                        // the key must be readOnly so just leave the game
                        this.leaveGame();
                    }
                }
            }

            if (currentGame.currentPlayerTurn)
            {
                if (currentGame.canMove(x, y))
                {
                    currentGame.doMove(x, y);
                    // compare and set can fail if the other player has taken the first move or has forfeit (which they
                    // can do even when it's not their turn)
                    this.currentDataShare.compareAndSet({
                            key: 'game-state',
                            value: currentGame.serialize(),
                            callback: gameStateSet
                        });
                }
            }
            else
            {
                // for testing on local and hub where instant notifications are slow the user can click to see if there
                // are any updates
                this.readMoves();
            }
        }
    }

    segmentFont(x: number, y: number, text: string, clickCallback?, id?: string)
    {
        // render some simple GUI text (can be clicked if clickCallback and id are given)
        // this cannot be called inside of the draw2d.begin and draw2d.end calls

        var graphicsDevice = this.graphicsDevice;
        var fontTechniqueParameters = this.fontTechniqueParameters;
        var font = this.font;

        var topLeft = this.draw2D.viewportUnmap(x, y);
        if (clickCallback)
        {
            fontTechniqueParameters.color = this.fontBoldColor;
        }
        else
        {
            fontTechniqueParameters.color = this.fontColor;
        }

        if (this.setButtons && clickCallback)
        {
            var textBlockSize = font.calculateTextDimensions(text, this.hoverTextScale, 0);
            SimpleButtonManager.addButton({
                    id: id,
                    left: topLeft[0],
                    top: topLeft[1],
                    right: topLeft[0] + textBlockSize.width,
                    bottom: topLeft[1] + textBlockSize.height,
                    callback: clickCallback
                });
        }

        var scale = this.textScale;
        if (id)
        {
            var button = SimpleButtonManager.buttons[id];
            if (button && button.hovering)
            {
                scale = this.hoverTextScale;
            }
        }
        graphicsDevice.setTechniqueParameters(fontTechniqueParameters);
        font.drawTextRect(text, {
            rect : [topLeft[0], topLeft[1], 0, 0], // for left-align width and height are ignored
            scale : scale,
            spacing : 0,
            alignment : 0
        });
    }

    renderGame()
    {
        this.graphicsDevice.setTechnique(this.fontTechnique);
        var currentGame = this.currentGame;

        var currentUsername = this.userProfile.username;
        this.segmentFont(0, 0, 'Hello ' + currentUsername);

        var textSpacingY = this.textSpacingY;
        var offsetY = textSpacingY;

        var roundEnd = currentGame.roundEnd;
        if (roundEnd)
        {
            this.segmentFont(0, offsetY, 'Leave', this.leaveGame.bind(this), 'leave');
        }
        else
        {
            this.segmentFont(0, offsetY, 'Back to lobby', this.toLobby.bind(this), 'toLobby');
            this.segmentFont(20, offsetY, 'Forfeit', this.forfeitGame.bind(this), 'forfeitGame');
        }
        offsetY += textSpacingY;

        var users = currentGame.getUsers();
        var usersLength = users.length;
        var usersIndex;

        var boardOffsetX = this.boardOffsetX;
        var boardOffsetY = this.boardOffsetY;
        var boardSizeX = this.boardSizeX;
        var boardSizeY = this.boardSizeY;

        var offsetY = boardOffsetY + boardSizeY + textSpacingY * 2;
        for (usersIndex = 0; usersIndex < usersLength; usersIndex += 1)
        {
            this.segmentFont(3, offsetY, users[usersIndex]);
            offsetY += textSpacingY;
        }

        if (roundEnd)
        {
            if (roundEnd.draw)
            {
                this.segmentFont(0, offsetY, 'Draw');
            }
            else if (roundEnd.forfeit)
            {
                this.segmentFont(0, offsetY, roundEnd.forfeit + ' forfeit!');
            }
            else if (roundEnd.winner)
            {
                this.segmentFont(0, offsetY, roundEnd.winner + ' wins!');
            }
        }
        else
        {
            if (currentGame.firstMove === null)
            {
                this.segmentFont(0, offsetY, 'Either player can take the first move');
            }
            else if (currentGame.currentPlayerTurn)
            {
                this.segmentFont(0, offsetY, 'It\'s your turn');
            }
            else
            {
                this.segmentFont(0, offsetY, 'Waiting for other player\'s turn');
            }
        }
        offsetY += textSpacingY;

        var draw2D = this.draw2D;
        if (draw2D.begin(draw2D.blend.alpha))
        {
            draw2D.drawSprite(this.boardSprite);
            var pieceSprites = this.pieceSprites;

            var x, y;
            for (x = 0; x < 3; x += 1)
            {
                for (y = 0; y < 3; y += 1)
                {
                    var piece = currentGame.boardState[x + y * 3];
                    if (piece)
                    {
                        draw2D.drawSprite(pieceSprites[piece][x + y * 3]);
                    }
                    if (this.setButtons)
                    {
                        var destRectangle = [boardOffsetX + (boardSizeX / 3) * x,
                                             boardOffsetY + (boardSizeY / 3) * y,
                                             boardOffsetX + (boardSizeX / 3) * (x + 1),
                                             boardOffsetY + (boardSizeY / 3) * (y + 1)];
                        var topLeft = draw2D.viewportUnmap(destRectangle[0],
                                                           destRectangle[1]);
                        var bottomRight = draw2D.viewportUnmap(destRectangle[2],
                                                               destRectangle[3]);
                        var onClickFn = this.getOnClickFn(x, y);
                        SimpleButtonManager.addButton({
                                id: 'click-' + x + '-' + y,
                                left: topLeft[0],
                                top: topLeft[1],
                                right: bottomRight[0],
                                bottom: bottomRight[1],
                                callback: onClickFn
                            });
                    }
                }
            }

            offsetY = boardOffsetY + boardSizeY + textSpacingY * 2;
            for (usersIndex = 0; usersIndex < usersLength; usersIndex += 1)
            {
                destRectangle = [0, offsetY,
                                 textSpacingY, offsetY + textSpacingY];
                offsetY += textSpacingY;
                var pieceTexture = this.pieceTextures[currentGame.getPlayerPiece(users[usersIndex])];
                if (pieceTexture)
                {
                    draw2D.draw({
                        texture : pieceTexture,
                        destinationRectangle : destRectangle
                    });
                }
            }

            draw2D.end();
        }
    }

    renderLobby()
    {
        this.graphicsDevice.setTechnique(this.fontTechnique);

        var offsetY = 0;
        var textSpacingY = this.textSpacingY;

        var joinedDataShares = this.joinedDataShares;

        var currentUsername = this.userProfile.username;
        this.segmentFont(0, 0, 'Hello ' + currentUsername);
        offsetY += textSpacingY;

        if (joinedDataShares && joinedDataShares.length > 0)
        {
            this.segmentFont(0, offsetY, 'Playing:');
            offsetY += textSpacingY;

            var joinedDataSharesIndex;
            var joinedDataSharesLength = joinedDataShares.length;
            for (joinedDataSharesIndex = 0; joinedDataSharesIndex < joinedDataSharesLength; joinedDataSharesIndex += 1)
            {
                var dataShare = joinedDataShares[joinedDataSharesIndex];
                var game = this.joinedGames[dataShare.id];
                var playGameFn = this.getPlayGameFn(dataShare);
                if (game && game.roundEnd)
                {
                    this.segmentFont(3, offsetY, 'Game finished (click to see result)', playGameFn,
                        'playGame-' + joinedDataSharesIndex);
                }
                else
                {
                    var users = dataShare.users;
                    if (users.length === 1)
                    {
                        this.segmentFont(3, offsetY, 'Waiting for player', playGameFn,
                            'playGame-' + joinedDataSharesIndex);
                    }
                    else
                    {
                        this.segmentFont(3, offsetY, users[0] + ' vs ' + users[1], playGameFn,
                            'playGame-' + joinedDataSharesIndex);
                    }
                }
                offsetY += textSpacingY;
            }
        }

        var foundDataShares = this.foundDataShares;
        var dataSharesLength = 0;
        var dataSharesIndex;
        if (foundDataShares)
        {
            var noGamesToJoin = true;
            dataSharesLength = foundDataShares.length;
            if (dataSharesLength > 0)
            {
                for (dataSharesIndex = 0; dataSharesIndex < dataSharesLength; dataSharesIndex += 1)
                {
                    var dataShare = foundDataShares[dataSharesIndex];
                    if (dataShare.users.length === 1)
                    {
                        if (noGamesToJoin)
                        {
                            this.segmentFont(0, offsetY, 'Games to join:');
                            offsetY += textSpacingY;
                            noGamesToJoin = false;
                        }
                        var joinGameFn = this.getJoinGameFn(dataShare)
                        this.segmentFont(3, offsetY, dataShare.owner, joinGameFn, 'joinGame-' + dataSharesIndex);
                        offsetY += textSpacingY;
                    }
                }
            }

            if (noGamesToJoin)
            {
                this.segmentFont(0, offsetY, 'No new games to join');
                offsetY += textSpacingY;
            }
        }

        this.segmentFont(0, offsetY, 'Refresh', this.findDataShares.bind(this), 'refresh');
        this.segmentFont(20, offsetY, 'Create new game', this.createGame.bind(this), 'create');
        offsetY += textSpacingY;
    }

    update()
    {
        var graphicsDevice = this.graphicsDevice;
        if (!graphicsDevice.beginFrame())
        {
            return;
        }

        var width = graphicsDevice.width;
        var height = graphicsDevice.height;
        this.setButtons = this.invalidateButtons || this.oldWidth !== width || this.oldHeight !== height;
        if (this.setButtons)
        {
            SimpleButtonManager.clearButtons();
            this.invalidateButtons = false;
            this.fontTechniqueParameters.clipSpace = this.mathDevice.v4Build(2 / width, -2 / height, -1, 1,
                                                                             this.fontTechniqueParameters.clipSpace);
        }
        this.oldWidth = width;
        this.oldHeight = height;

        graphicsDevice.clear(this.clearColor);

        if (this.hasGameSessionClosed)
        {
            this.graphicsDevice.setTechnique(this.fontTechnique);
            this.segmentFont(0, 0, 'Game session closed. Looks like you have started playing somewhere else.');
        }
        else if (this.userProfile.guest)
        {
            this.graphicsDevice.setTechnique(this.fontTechnique);
            this.segmentFont(0, 0, 'Sorry, guests must register before they can play tic-tac-toe.');
        }
        else if (this.currentGame)
        {
            this.renderGame();
        }
        else
        {
            this.renderLobby();
        }

        graphicsDevice.endFrame();
    }

    loadingUpdate()
    {
        var notificationsManager = this.notificationsManager;
        if (this.font &&
            this.fontShader &&
            this.userProfile &&
            this.dataShareManager &&
            notificationsManager && notificationsManager.ready &&
            this.numTextures === this.loadedResources)
        {
            var mathDevice = this.mathDevice;
            var graphicsDevice = this.graphicsDevice;

            this.fontTechnique = this.fontShader.getTechnique('font');
            this.fontTechniqueParameters = graphicsDevice.createTechniqueParameters({
                clipSpace : mathDevice.v4BuildZero(),
                alphaRef : 0.01,
                color : mathDevice.v4BuildOne()
            });

            this.draw2D = Draw2D.create({
                graphicsDevice : graphicsDevice
            });

            this.draw2D.configure({
                viewportRectangle : [0, 0, this.stageWidth, this.stageHeight],
                scaleMode : 'scale'
            });

            var textures = this.textures;
            var pieceTextures = this.pieceTextures;
            var boardOffsetX = this.boardOffsetX;
            var boardOffsetY = this.boardOffsetY;
            var boardSizeX = this.boardSizeX;
            var boardSizeY = this.boardSizeY;

            this.boardSprite = Draw2DSprite.create({
                texture : textures['textures/tictactoeboard.png'],
                x: boardOffsetX,
                y: boardOffsetY,
                width : boardSizeX,
                height: boardSizeY,
                origin: [0, 0]
            });

            pieceTextures.O = textures['textures/nought.png'];
            pieceTextures.X = textures['textures/cross.png'];

            var pieceWidth = boardSizeX / 3;
            var pieceHeight = boardSizeY / 3;
            var pieceSprites = this.pieceSprites;
            var x, y;
            for (x = 0; x < 3; x += 1)
            {
                for (y = 0; y < 3; y += 1)
                {
                    var pieceX = boardOffsetX + pieceWidth * x;
                    var pieceY = boardOffsetY + pieceHeight * y;
                    pieceSprites.O[x + y * 3] = Draw2DSprite.create({
                        texture : pieceTextures.O,
                        x: pieceX,
                        y: pieceY,
                        width : pieceWidth,
                        height: pieceHeight,
                        origin: [0, 0]
                    });
                    pieceSprites.X[x + y * 3] = Draw2DSprite.create({
                        texture : pieceTextures.X,
                        x: pieceX,
                        y: pieceY,
                        width : pieceWidth,
                        height: pieceHeight,
                        origin: [0, 0]
                    });
                }
            }

            notificationsManager.addNotificationListener('player-joined', this.playerJoined.bind(this));
            notificationsManager.addNotificationListener('your-turn', this.yourTurn.bind(this));
            notificationsManager.addNotificationListener('forfeit', this.yourTurn.bind(this));

            TurbulenzEngine.clearInterval(this.intervalID);
            this.intervalID = TurbulenzEngine.setInterval(this.update.bind(this), 1000 / 60);
        }
    }

    // Attempts to free memory - called from onbeforeunload and/or
    // TurbulenzEngine.onUnload
    shutdown()
    {
        if (!this.hasShutdown)
        {
            this.hasShutdown = true;

            if (this.gameSession)
            {
                this.gameSession.destroy();
            }

            TurbulenzEngine.clearInterval(this.intervalID);

            // Attempt to force clearing of the garbage collector
            TurbulenzEngine.flush();

            this.inputDevice     = null;
            this.mathDevice      = null;
            this.graphicsDevice  = null;
        }
    }

    errorCallback(message)
    {
        Utilities.log(message);
    }

    // Application constructor function
    static create()
    {
        var application = new Application();

        var graphicsDevice = application.graphicsDevice = TurbulenzEngine.createGraphicsDevice({});
        var mathDevice = application.mathDevice = TurbulenzEngine.createMathDevice({});
        var inputDevice = application.inputDevice = TurbulenzEngine.createInputDevice({});
        var requestHandler = application.requestHandler = RequestHandler.create({});

        application.hasShutdown = false;
        application.hasGameSessionClosed = false;

        application.fontManager = FontManager.create(graphicsDevice, requestHandler);
        application.shaderManager = ShaderManager.create(graphicsDevice, requestHandler);

        application.dataShareManager = null;
        application.notificationsManager = null;
        application.userProfile = null;

        SimpleButtonManager.init(inputDevice);

        application.currentDataShare = null;
        application.joinedDataShares = null;
        application.foundDataShares = null;

        application.joinedGames = {};
        application.currentGame = null;

        application.draw2D;

        application.clearColor = mathDevice.v4Build(1.0, 1.0, 1.0, 1.0);
        application.fontColor = mathDevice.v4Build(0.5, 0.5, 0.5, 1.0);
        application.fontBoldColor = mathDevice.v4Build(0.3, 0.3, 0.3, 1.0);

        application.fontTechnique;
        application.fontTechniqueParameters;

        // Textures to load:
        var spriteTextureNames = application.spriteTextureNames = [
            'textures/tictactoeboard.png',
            'textures/nought.png',
            'textures/cross.png'
        ];

        // List to store the loaded texture objects.
        application.textures = {};
        application.numTextures = spriteTextureNames.length;
        application.loadedResources = 0;

        application.pieceTextures = {
            'X': null,
            'O': null
        };

        application.pieceSprites = {
            'O': [],
            'X': []
        };
        application.boardSprite;
        application.oldWidth = 0;
        application.oldHeight = 0;

        return application;
    }
}


text:
var Fs     = require("fs")
  , Namer  = require("../lib/namer")
  , Path   = require("path")
  , Renderer = require('../lib/renderer')
  , Locker = require("../lib/locker")
  , Tools  = require("../lib/tools")
  , Url    = require("url");

var Git = app.locals.Git;

exports.index = function(req, res) {
  res.redirect('/wiki/home');
};

exports.search = function(req, res) {

  var items = []
    , record;

  res.locals.matches = [];
  res.locals.term = req.query.term.trim();

  if (res.locals.term.length < 2) {
    res.locals.warning = "Search string is too short.";
    renderResults();
  } else {

    Git.grep(res.locals.term, function(err, items) {

      items.forEach(function(item) {
        if (item.trim() != "") {
          record = item.split(":");
          res.locals.matches.push({
            pageName: Path.basename(record[0].split(".")[0]),
            line: record[1] ? ":" + record[1] : "",
            text: record.slice(2).join('')
          });
        }
      });

      renderResults();
    });
  }

  function renderResults() {
    res.render("search", {
      title: "Search results"
    });
  }
}

exports.pageList = function(req, res) {

  var items = []
    , title
    , len;

  Git.ls(function(err, list) {

    len = list.length;

    list.forEach(function(page) {

      page = Path.basename(page);

      Git.hashes(page,2, function(err, hashes) {

        Git.readFile(page, "HEAD", function(err, content) {

          (function(title) {

            Git.log(page, "HEAD", function(err, metadata) {

              Git.lastMessage(page, "HEAD", function(err, message) {

                items.push({
                  pageTitle: title,
                  message: message,
                  metadata: metadata,
                  hashes: hashes.length == 2 ? hashes.join("..") : ""
                });

                if (items.length === len) {
                  items.sort(function(a, b) {
                    return b.metadata.timestamp - a.metadata.timestamp;
                  });

                  res.render("list", {
                    title: "Document list – Sorted by update date",
                    items: items
                  });
                }
              });
            });
          })(Tools.getPageTitle(content, page));
        });
      });
    });
  });
}

exports.pageShow = function(req, res) {

  var pageName = req.params.page
    , pageVersion = req.params.version || "HEAD";

  Git.readFile(pageName + ".md", pageVersion, function(err, content) {

    if (err) {
      if (req.user) {
        res.redirect('/pages/new/' + pageName);
      } else {
        // Special case for "home", anonymous user and an empty docbase
        if (pageName == 'home') {
          res.render('welcome', {
            title: 'Welcome to ' + app.locals.appTitle
          });
        } else {
          error404(req, res);
          return;
        }
      }

    } else {

      Git.log(pageName + ".md", pageVersion, function(err, metadata) {

        res.locals.canEdit = true;
        if (pageVersion != 'HEAD') {
          res.locals.warning = "You're not reading the latest revision of this page, which is " + "here.";
          res.locals.canEdit = false;
        }

        res.locals.notice = req.session.notice;
        delete req.session.notice;

        res.render('show', {
          title:   app.locals.appTitle + " – " + Tools.getPageTitle(content, pageName),
          content: Tools.hasTitle(content) ? Renderer.render(content) : Renderer.render("# " + pageName + "\n" + content),
          pageName: pageName,
          metadata: metadata
        });

      });
    }
  });
};

exports.pageNew = function(req, res) {

  res.locals.pageName = Namer.normalize(req.params.page);

  if (res.locals.pageName) {
    if (Fs.existsSync(Git.absPath(res.locals.pageName + ".md"))) {
      res.redirect("/wiki/" + res.locals.pageName);
      return;
    }
  }

  res.locals.errors = req.session.errors;
  res.locals.formData = req.session.formData || {};
  delete req.session.errors;
  delete req.session.formData;

  res.render('create', {
    "title": "Create a new page",
    "pageTitle": Namer.denormalize(res.locals.pageName)
  });
}

exports.pageCreate = function(req, res) {

  var errors
    , pageName
    , pageFile
    , hasPageName = !!req.body.pageName;

  pageName = Namer.normalize(req.body.pageName || req.body.pageTitle);

  req.check('pageTitle', 'Page title cannot be empty').notEmpty();
  req.check('content',   'Page content cannot be empty').notEmpty();

  errors = req.validationErrors();

  if (errors) {
    req.session.errors = errors;
    req.session.formData = req.body;
    res.redirect("/pages/new" + (hasPageName ? '/' + pageName : ''));
    return;
  }

  req.sanitize('pageTitle').trim();
  req.sanitize('content').trim();

  pageFile = Git.absPath(pageName + ".md");

  if (Fs.existsSync(pageFile)) {
    req.session.errors = [{msg: "A document with this title already exists"}];
    res.redirect("/pages/new");
    return;
  }

  Fs.writeFile(pageFile, "# " + req.body.pageTitle + "\n" + req.body.content.replace(/\r\n/gm, "\n"), function() {
    Git.add(pageName + ".md", "Page created (" + pageName + ")", req.user.asGitAuthor, function(err) {
      req.session.notice = "Page has been created successfully";
      res.redirect("/wiki/" + pageName);
    });
  });
}

exports.pageEdit = function(req, res) {

  var pageName = res.locals.pageName = req.params.page
    , lock;

  if (lock = Locker.getLock(pageName)) {
    if (lock.user.asGitAuthor != req.user.asGitAuthor) {
      res.locals.warning = "Warning: this page is probably being edited by " + lock.user.displayName;
    }
  }

  Git.pull(app.locals.remote, app.locals.branch, function(err) {

    if (err) {
      error500(req, res, err);
      return;
    }

    Git.readFile(pageName + ".md", "HEAD", function(err, content) {

      if (err) {
        res.redirect('/pages/new/' + pageName);
      } else {

        if (!req.session.formData) {
          res.locals.formData = {
            pageTitle: Tools.getPageTitle(content, pageName),
            content: Tools.getContent(content)
          };
        } else {
          res.locals.formData = req.session.formData;
        }

        res.locals.errors = req.session.errors;

        Locker.lock(pageName, req.user);

        delete req.session.errors;
        delete req.session.formData;

        res.render('edit', {
          title: 'Edit page'
        });
      }
    });
  });
}

exports.pageUpdate = function(req, res) {

  var pageName = res.locals.pageName = Namer.normalize(req.params.page)
    , errors
    , pageFile
    , message
    , content;

  req.check('pageTitle', 'Page title cannot be empty').notEmpty();
  req.check('content',   'Page content cannot be empty').notEmpty();

  errors = req.validationErrors();

  if (errors) {
    req.session.errors = errors;
    req.session.formData = req.body;
    res.redirect("/pages/" + pageName + "/edit");
    return;
  }

  req.sanitize('pageTitle').trim();
  req.sanitize('content').trim();
  req.sanitize('message').trim();

  content = "# " + req.body.pageTitle + "\n" + req.body.content.replace(/\r\n/gm, "\n");
  pageFile = Git.absPath(pageName + ".md");

  message = (req.body.message == "") ? "Content updated (" + pageName + ")" : req.body.message;

  Fs.writeFile(pageFile, content, function() {
    Git.add(pageName + ".md", message, req.user.asGitAuthor, function(err) {
      Locker.unlock(pageName);
      if (pageName == '_footer') {
        app.locals.Components.expire('footer');
      }
      if (pageName == '_sidebar') {
        app.locals.Components.expire('sidebar');
      }
      req.session.notice = "Page has been updated successfully";
      res.redirect("/wiki/" + pageName);
    });
  });
}

exports.pageDestroy = function(req, res) {

  var pageName = Namer.normalize(req.params.page);

  if (pageName == 'home') {
    res.redirect("/");
    return;
  }

  Git.rm(pageName + ".md", "Page removed (" + pageName + ")", req.user.asGitAuthor, function(err) {
    Locker.unlock(pageName);
    if (pageName == '_footer') {
      app.locals._footer = null;
    }
    if (pageName == '_sidebar') {
      app.locals._sidebar = null;
    }
    req.session.notice = "Page has been deleted successfully";
    res.redirect("/");
  });
}

exports.pageCompare = function(req, res) {

  var pageName = req.params.page
    , revisions = req.params.revisions;

  res.locals.revisions = revisions.split("..");
  res.locals.lines = [];

  Git.diff(pageName + ".md", revisions, function(err, diff) {

    diff.split("\n").slice(4).forEach(function(line) {

      if (line.slice(0,1) != '\\') {
        res.locals.lines.push({
          text: line,
          ldln: leftDiffLineNumber(0, line),
          rdln: rightDiffLineNumber(0, line),
          class: lineClass(line)
        });
      }

    });

    res.render('compare', {
      title: "Compare Revisions"
    });

  });

  var ldln = 0
    , cdln;
  function leftDiffLineNumber(id, line) {

    var li;

    switch(true) {

      case line.slice(0,2) == '@@':
        li = line.match(/\-(\d+)/)[1];
        ldln = parseInt(li, 10);
        cdln = ldln;
        return '...';

      case line.slice(0,1) == '+':
        return "";

      case line.slice(0,1) == '-':
      default:
        ldln++
        cdln = ldln - 1;
        return cdln;
    }
  }

   var rdln = 0;
   function rightDiffLineNumber(id, line) {

    var ri;

    switch(true) {

      case line.slice(0,2) == '@@':
        ri = line.match(/\+(\d+)/)[1];
        rdln = parseInt(ri, 10)
        cdln = rdln;
        return '...';

      case line.slice(0,1) == '-':
        return ' ';

      case line.slice(0,1) == '+':
      default:
        rdln += 1
        cdln = rdln - 1;
        return cdln;
    }
  }

  function lineClass(line) {
    if (line.slice(0,2) === '@@') {
      return "gc";
    }
    if (line.slice(0,1) === '-') {
      return "gd";
    }
    if (line.slice(0,1) === '+') {
      return "gi";
    }
  }
}

exports.pageHistory = function(req, res) {

  var pageName = req.params.page
    , pageTitle;

  Git.readFile(pageName + ".md", "HEAD", function(err, content) {

    // FIXME This is a 404
    if (err) { res.redirect('/'); }

    Git.log(pageName + ".md", "HEAD", 30, function(err, metadata) {
      res.locals.pageTitle = Tools.getPageTitle(content, pageName);
      res.locals.pageName = pageName;
      res.locals.items = metadata;
      res.render('history', {
        title: "Revisions of"
      });
    });
  });
}

exports.miscPreview = function(req, res) {
  res.render('preview', {
    content: Renderer.render(req.body.data)
  });
}

exports.miscSyntaxReference = function(req, res) {
  res.render('syntax');
}

// Filters out pages that do not exist in the index
exports.miscExistence = function(req, res) {

  if (!req.query.data) {
    res.send(JSON.stringify({data: []}));
    return;
  }

  var result = []
    , n = req.query.data.length;

  req.query.data.forEach(function(pageName, idx) {
    (function(page, index) {
      if (!Fs.existsSync(Git.absPath(page + ".md"))) {
        result.push(page);
      }
      if (index == (n - 1)) {
        res.send(JSON.stringify({data: result}));
      }
    })(pageName, idx);
  });
}

exports.authDone = function(req, res) {

  if (!res.locals.user) {
    res.redirect("/");
    return;
  }

console.log(req.session.destination);
  if (!app.locals.authentication.alone.used && !Tools.isAuthorized(res.locals.user.email, app.locals.authorization.validMatches)) {
    req.logout();
    req.session = null;
    res.statusCode = 403;
    res.end('
Forbidden
');
  } else {
    var dst = req.session.destination || "/";
    delete req.session.destination;
    res.redirect(dst);
  }
}

/*
 * GET Login page.
 */
exports.login = function(req, res) {

  req.session.destination = req.query.destination; // (req.headers.referer ? Url.parse(req.headers.referer).path : null);

  if (req.session.destination == '/login') {
    req.session.destination = '/';
  }

  res.locals.errors = req.flash();

  res.render('login', {
    title: app.locals.appTitle,
    auth: app.locals.authentication
  });
};

exports.logout = function(req, res) {
  req.logout();
  req.session = null;
  res.redirect('/');
};

error404 = exports.error404 = function(req, res) {
  res.locals.title = "404 - Not found";
  res.statusCode = 404;
  res.render('404.jade');
}

error500 = exports.error500 = function(req, res, message) {
  res.locals.title = "500 - Internal server error";
  res.statusCode = 500;
  res.render('500.jade', {
    error: message
  });
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Quote Machine</title>

  <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css'>

  <link rel="stylesheet" href="css/style.css">

Quote machine beta

    <button id="q" class="btn btn-default btn-block">New Quote</button>

    Tweet


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="definitions"
  xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
  xmlns:camunda="http://camunda.org/schema/1.0/bpmn"
  targetNamespace="Examples">

  <process id="twoSubProcessInParallelWithinSubProcess">

    <startEvent id="theStart" />
    <sequenceFlow id="flow1" sourceRef="theStart" targetRef="outerSubProcess" />

    <subProcess id="outerSubProcess">

      <startEvent id="outerSubProcessStart" />
      <sequenceFlow id="flow2" sourceRef="outerSubProcessStart" targetRef="fork" />

	    <parallelGateway id="fork"/>
	    <sequenceFlow id="flow3" sourceRef="fork" targetRef="subProcessA" />
	    <sequenceFlow id="flow4" sourceRef="fork" targetRef="subProcessB" />

	    <subProcess id="subProcessA">

	      <startEvent id="subProcessAStart" />
	      <sequenceFlow id="flow5" sourceRef="subProcessAStart" targetRef="subProcessATask" />
	      <userTask id="subProcessATask" name="Task in subprocess A" />
	      <sequenceFlow id="flow6" sourceRef="subProcessATask" targetRef="subProcessAEnd" />
	      <endEvent id="subProcessAEnd" />

	    </subProcess>
	    <sequenceFlow id="flow7" sourceRef="subProcessA" targetRef="join" />

	    <subProcess id="subProcessB">

	      <startEvent id="subProcessBStart" />
	      <sequenceFlow id="flow8" sourceRef="subProcessBStart" targetRef="subProcessBTask" />
	      <userTask id="subProcessBTask" name="Task in subprocess B" />
	      <sequenceFlow id="flow9" sourceRef="subProcessBTask" targetRef="subProcessBEnd" />
	      <endEvent id="subProcessBEnd" />

	    </subProcess>
	    <sequenceFlow id="flow10" sourceRef="subProcessB" targetRef="join" />

	    <parallelGateway id="join" />
	    <sequenceFlow id="flow11" sourceRef="join" targetRef="outerSubProcessEnd" />
	    <endEvent id="outerSubProcessEnd" />

    </subProcess>

    <sequenceFlow id="flow12" sourceRef="outerSubProcess" targetRef="taskAfterSubProcess" />
    <userTask id="taskAfterSubProcess" name="Task after subprocess" />
    <sequenceFlow id="flow13" sourceRef="taskAfterSubProcess" targetRef="theEnd" />
    <endEvent id="theEnd" />

  </process>

</definitions>


text:
#include <osquery/core/flags.h>

namespace osquery {

/**
 * The Auditd/OpenBSM subsystem may have a performance impact on the system.
 *
 * This flag controls Auditd on Linux and OpenBSM on macOS.
 */
FLAG(bool,
     disable_audit,
     true,
     "Disable receiving events from the audit subsystem");

/// Control the audit subsystem by allowing subscriptions to apply rules.
FLAG(bool,
     audit_allow_config,
     false,
     "Allow the audit publisher to change auditing configuration");

FLAG(bool,
     audit_allow_sockets,
     false,
     "Allow the audit publisher to install socket-related rules");

FLAG(bool,
     audit_allow_process_events,
     true,
     "Allow the audit publisher to install process-related rules");

FLAG(bool,
     audit_allow_user_events,
     true,
     "Allow the audit publisher to install user-related rules");

FLAG(bool,
     audit_allow_fim_events,
     false,
     "Allow the audit publisher to install filesystem-related rules");

} // namespace osquery


text:
// MyJFrame.java
// See copyright.txt for license and terms of use.

package util.swing;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

/** Like JFrame, but closes in response to window close button,
  * plus some other utility methods. */
public class MyJFrame extends JFrame {
    /** Generated ID. */
    private static final long serialVersionUID = 7425587687068601846L;

    public MyJFrame(String title)
    {
        super(title);

        // Respond to window close button.
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                MyJFrame.this.dispose();
            }
        });
    }

    /** Pop up a modal dialog box with an error message. */
    public void errorBox(String title)
    {
        ModalDialog.errorBox(this, title);
    }
}

// EOF


text:
This document describes the design of Elektra's C-API and provides hints for
binding writers. It is not aimed at plugin writers, since it does not
talk about the implementation details of Elektra.

Elektra [aims](GOALS.md) at following design principles:

1. To make the API futureproof so that it can remain compatible and stable
   over a long period of time,
2. to make it hard to use the API the wrong way by making it simple&robust, and
3. to make the API easy to use for programmers reading and writing
   configuration.

The C-API is suitable to be reimplemented, also in non-C-languages, like Rust.
Elektra provides a full blown architecture to support configuring systems, and
the C-API is the core of this endeavour.

## Data Structures

The `Key`, `KeySet` and `KDB` data structures are defined in
`kdbprivate.h` to allow ABI compatibility.
This means, it is not possible to put one of Elektra's data structures
on the stack. You must use the memory management facilities mentioned
in the next section.

## Memory Management

Elektra provides functions that create and free data.
For example after you call:

```c
KDB * kdbOpen();
```

you need to use:

```c
int kdbClose(KDB *handle);
```

to get rid of the resources again. The second function may also shut
down connections. Therefore it must be called before the end of a program.

```c
Key *keyNew(const char *keyName, ...);
int keyDel(Key *key);

KeySet *ksNew(int alloc, ...);
int ksDel(KeySet *ks);
```

In the above pairs, the first function reserves the necessary amount
of memory. The second function frees the allocated data segment. There
are more allocations happening but they are invisible to the user of
the API and happen implicitly within any of these 3 classes:
`KDB`, `Key` and `KeySet`.

Key names and values cannot be handled as easy, because Elektra
does not provide a string library. There are 2 ways to access the
mentioned attributes. The function

```c
const char *keyString(const Key *key);
```

returns a string. You are not allowed to change the returned string.
The function

```c
ssize_t keyGetValueSize(const Key *key);
```

shows how long the string is for the specified key. The returned value
also specifies the minimum buffer size that `keyGetString` will
reserve for the copy of the key.

```c
ssize_t keyGetString(const Key *key, char *returnedValue, size_t maxSize);
```

writes the comment in a buffer maintained by you.

## Variable Arguments

The constructors for `Key` and `KeySet` take a variable sized list of
arguments. They can be used as an alternatives to the various `keySet*`
methods and `ksAppendKey`. With them you are able to generate any `Key`
or `KeySet` with a single C-statement. This can be done
programmatically by the plugin `c`.

To just retrieve a key, use

```c
Key *k = keyNew("/", KEY_END);
```

To obtain a `keyset`, use

```c
KeySet *k = ksNew(0, KS_END);
```

Alternatively pass a list as described in the documentation.
The idea of these variable arguments is, that one function call
can create any `KeySet`. For binding writers `keyVNew` might be
useful.

## Off-by-one

We avoid off-by-one errors by starting all indices with 0, as
usual in C. The size returned by the `*GetSize` functions
(`keyGetValueSize`, `keyGetCommentSize` and `keyGetOwnerSize`) is
exactly the size you need to allocate. So if you add 1 to it, too much
space is allocated, but no error will occur.

The same is true for `elektraStrLen` which also already has the
null byte included.

## Minimal Set

`kdb.h` contains a minimal set of functions to fully work with a key
database. The functions are implemented in `src/libs/elektra` in ANSI C.

Useful extensions are available in [further libraries](/src/libs).

## Value, String or Binary

Sometimes people confuse the terms "value", "string" and "binary":

- Value is just a name which does not specify if data is stored as
  string or in binary form.

- A string is a char array, with a terminating `'\0'`.

- Binary data is stored in an array of type void, and not terminated by
  `'\0'`.

See also [the glossary](/doc/help/elektra-glossary.md) for further
terminology.

In Elektra `char*` are used as null-terminated strings, while `void*`
might contain `0`-bytes:

```c
const void *keyValue(const Key *key);
```

does not specify whether the returned value is binary or a string. The
function just returns the pointer to the value. When `key` is a string
(check with `keyIsString`) at least `""` will be returned. See section
"Return Values" to learn more about common values returned by Elektra's
functions. For binary data a `NULL` pointer is also possible to
distinguish between no data and `'\0'`.

```c
ssize_t keyGetValueSize(const Key *key);
```

does not specify whether the key type is binary or string. The function
just returns the size which can be passed to `elektraMalloc` to hold
the entire value.

```c
ssize_t keyGetString(const Key *key, char *returnedString, size_t maxSize);
```

stores the string into a buffer maintained by you.

```c
ssize_t keySetString(Key *key, const char *newString);
```

sets the null terminated string value for a certain key.

```c
ssize_t keyGetBinary(const Key *key, void *returnedBinary, size_t maxSize);
```

retrieves binary data which might contain `'\0'`.

```c
ssize_t keySetBinary(Key *key, const void *newBinary, size_t dataSize);
```

sets the binary data which might contain `'\0'`. The length is given
by `dataSize`.

## Return Values

Elektra's function share common error codes. Every function must return
`-1` on error, if its return type is integer (like `int`, `ssize_t`). If
the function returns a pointer, `0` (`NULL`) will indicate an error.

Elektra uses integers for the length of C strings, reference counting, `KeySet` length and internal `KeySet` allocations.

The interface always accepts `ssize_t` and internally uses `size_t`,
which is able to store larger numbers than `ssize_t`.

The real size of C strings and buffers is limited to `SSIZE_MAX`.
When a string exceeds that limit `-1` or a `NULL` pointer (see above)
must be returned.

The following functions return an internal string:

```c
const char *keyName(const Key *key);
const char *keyBaseName(const Key *key);
```

and in the case that `keyIsBinary(key)==0`:

```c
const void *keyValue(const Key *key);
```

does so, too. If in any of the functions above `key` is a `NULL`
pointer, then they also return `NULL`.

If there is no string you will get back `""`, that is a pointer to the
value `'\0'`. The function to determine the size will return `1` in
that case. That means that an empty string – nothing except the NULL
terminator – has size `1`.

This is not true for `keyValue` in the case of binary data, because the
value `'\0'` in the first byte is perfectly legal binary data.
`keyGetValueSize` may also return `0` for that reason.

## Error Handling

For `KDB` functions the user does not only get the return value but
also a more elaborate error information, including an error message,
in the metadata of the `parentKey` or `errorKey`. Furthermore, it is
also possible to get warnings, even if the calls succeeded.

Using different error categories, the user of the API can have suitable
reactions on specific error situations. Additional information about
error handling is available [here](/doc/dev/error-handling.md).

Elektra does not set `errno`. If a function you call sets `errno`, make
sure to set it back to the old value again.

## Naming

All function names begin with their class name, e.g. `kdb`, `ks` or
`key`. We use capital letters to separate single words (CamelCase).
This leads to short names, but might be not as readable as separating
names by other means.

_Get_ and _Set_ are used for getters/and setters. We use _Is_ to ask
about a flag or state and _Needs_ to ask about state related to
databases. For allocation/deallocation we use C++ styled names (e.g
`*New`, `*Del`).

Macros and Enums are written in capital letters. Flags start with
`KDB_`, namespaces with `KEY_NS_` and macros with `ELEKTRA_`.

Data structures start with a capital letter for every part of the word:

- `KDB` ... Key Data Base Handle
- `KeySet` ... Key Set
- `Key` ... Key

We use singular for all names.

Function names not belonging to one of the three classes use the
prefix `elektra*`.

## const

Wherever possible functions should use the keyword `const` for
parameters. The API uses this keyword for parameters, to show that a
function does not modify a `Key` or a `KeySet`, e.g.:

```c
const char *keyName(const Key *key);
const char *keyBaseName(const Key *key);
const void *keyValue(const Key *key);
const char *keyString(const Key *key);
const Key  *keyGetMeta(const Key *key, const char* metaName);
```

The reason behind this is, that the above functions – as their name
suggest – only retrieve values. The returned value must not be modified
directly.

## Design Guidelines Checklist

On potential changes of the API/ABI as detected by the
[`build server`](https://build.libelektra.org/job/libelektra/job/master/),
please make sure the API has been reviewed according to the
following 2 checklists:

## Checklist for overall API

### Consistency

- [ ] Consistent naming schemes for enums, macros, typedefs and functions
- [ ] Same things are named the same and included in [Glossary](/doc/help/elektra-glossary.md)
- [ ] Different things are named differently
- [ ] The order of arguments should be consistent across similar functions

### Structural Clarity

- [ ] Functions with similar functionality have the same prefix

### Compatibility

- [ ] All bindings have been updated to reflect the new API and work properly

### Extensibility

- [ ] New API is easily extensible with additional functionality
- [ ] Components only depend on each other if needed

## Checklist for each function

There are several checklists for functions, depending on the language in which
the function is written:

- [C](/scripts/api_review/template.c.md)
- [Rust](/scripts/api_review/template.rs.md)
- [Java](/scripts/api_review/template.java.md)


text:
<?php

namespace Lego\Foundation\Concerns;

interface QueryOperators
{
    const QUERY_EQ = '=';
    const QUERY_GT = '>';
    const QUERY_GTE = '>=';
    const QUERY_LT = '<';
    const QUERY_LTE = '<=';
    const QUERY_CONTAINS = 'contains';
    const QUERY_STARTS_WITH = 'starts_with';
    const QUERY_ENDS_WITH = 'ends_with';
}


text:
require('@babel/register');

const config = require('./src/config/config');
const dbConfig = config.resolve().db;

module.exports = Object.assign({}, dbConfig, {
  migrations: {
    directory: './src/migrations'
  }
});


text:
Mature.class_eval do
  has_many :landgraf_expression_levels
  has_one :landgraf_clone_count
end

Species.class_eval do
  has_many :landgraf_libraries
end


text:
package io.leao.codecolors.plugin.source;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import io.leao.codecolors.plugin.file.FileUtils;
import io.leao.codecolors.plugin.res.ColorUtils;
import io.leao.codecolors.plugin.util.ResourceUtils;
import io.leao.codecolors.plugin.xml.XmlUtils;

/**
 * After parsing the list of CodeColors colors, replaces its entries defined in {@code values.xml} files, by a
 * ColorStateList file with the same name.
 */
public class ResourcesGenerator {
    private static final String RESOURCE_NAME_COLOR_BASE = "cc_color_base.xml";
    private static final String RESOURCE_PLACE_HOLDER_COLOR_BASE = "%s";

    private static final String FILE_NAME_XML_BASE = "%s.xml";
    private static final String FILE_NAME_VALUES = "values.xml";

    private static final String FOLDER_COLOR = "color";
    private static final String ATTRIBUTE_NAME = "name";

    private static final String NODE_RESOURCES = "resources";
    private static final String NODE_COLOR = "color";

    private File mResDir;
    private String mColorBaseFileContent;
    private Map<String, Map<String, String>> mFolderColorValue = new HashMap<>();

    public ResourcesGenerator(File resDir) {
        mResDir = resDir;
        mColorBaseFileContent = ResourceUtils.readResource(RESOURCE_NAME_COLOR_BASE);
    }

    public void addColor(String folderName, String color, String value) {
        Map<String, String> colorValue = mFolderColorValue.get(folderName);
        if (colorValue == null) {
            colorValue = new HashMap<>();
            mFolderColorValue.put(folderName, colorValue);
        }
        colorValue.put(color, value);
    }

    public void generate() {
        if (mFolderColorValue.size() > 0) {
            File colorDir = FileUtils.ensureDir(new File(mResDir, FOLDER_COLOR));

            for (String folderName : mFolderColorValue.keySet()) {
                Map<String, String> colorValue = mFolderColorValue.get(folderName);

                generateColors(colorDir, colorValue);
                generateColorsDefaultValues(folderName, colorValue);
            }
        }
    }

    private void generateColors(File colorDir, Map<String, String> colorValue) {
        for (String color : colorValue.keySet()) {
            String outputFileContent = mColorBaseFileContent.replaceAll(
                    RESOURCE_PLACE_HOLDER_COLOR_BASE, ColorUtils.getDefaultValueReference(color));

            File outputFile = new File(colorDir, String.format(FILE_NAME_XML_BASE, color));
            if (!outputFile.exists()) {
                try {
                    //noinspection ResultOfMethodCallIgnored
                    outputFile.createNewFile();

                    FileOutputStream outputStream = new FileOutputStream(outputFile);
                    outputStream.write(outputFileContent.getBytes());
                    outputStream.close();
                } catch (IOException e) {
                    System.out.println("Failed to create color " + color + ": " + e.toString());
                }
            }
        }
    }

    private void generateColorsDefaultValues(String folderName, Map<String, String> colorValue) {
        try {
            DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();

            // Resources root node.
            Document document = documentBuilder.newDocument();
            Element resourcesElement = document.createElement(NODE_RESOURCES);
            document.appendChild(resourcesElement);

            // Color nodes.
            for (String color : colorValue.keySet()) {
                Element colorElement = document.createElement(NODE_COLOR);
                resourcesElement.appendChild(colorElement);

                // Set name attribute to color element.
                Attr nameAttr = document.createAttribute(ATTRIBUTE_NAME);
                nameAttr.setValue(ColorUtils.getDefaultValue(color));
                colorElement.setAttributeNode(nameAttr);

                // Color value.
                colorElement.appendChild(document.createTextNode(colorValue.get(color)));
            }

            File valuesDir = FileUtils.ensureDir(new File(mResDir, folderName));
            File valuesFile = FileUtils.ensureFile(new File(valuesDir, FILE_NAME_VALUES));
            XmlUtils.writeTo(document, valuesFile);
        } catch (ParserConfigurationException e) {
            System.out.println("Failed to create values file in " + folderName + " folder: " + e.toString());
        }
    }
}


text:
from nova import exception
from nova.scheduler.filter_scheduler import FilterScheduler
from nova.scheduler import driver, scheduler_options
import random
from oslo.config import cfg
from nova.compute import rpcapi as compute_rpcapi
from nova import notifier
from nova.openstack.common.gettextutils import _
from nova.openstack.common import log as logging
from nova.pci import pci_request
from nova.scheduler import utils as scheduler_utils
from no_multi_tenancy import NoMultiTenancy
from compute_node_selection import ComputeNodeSelection
from nova.scheduler import vf_allocation_migration_patch
from nova.scheduler import vf_allocation
from nova.openstack.common import log as logging
LOG = logging.getLogger(__name__)

PCI_ALIAS_NAME = 'CaveCreek'

class FilterSchedulerPatch(FilterScheduler):

    """Extension of nova.scheduler.filter_scheduler.FilterScheduler class supports
	execution of no multi tenancy algorithm,
	compute node selection algorithm and vf allocation algorithm while scheduling"""
    def __init__(self, *args, **kwargs):
	"""Initilaize member variables"""
        super(FilterSchedulerPatch, self).__init__(*args, **kwargs)
        self.options = scheduler_options.SchedulerOptions()
        self.compute_rpcapi = compute_rpcapi.ComputeAPI()
        self.notifier = notifier.get_notifier('scheduler')

    def schedule_run_instance(self, context, request_spec,
                              admin_password, injected_files,
                              requested_networks, is_first_time,
                              filter_properties, legacy_bdm_in_spec):

        payload = dict(request_spec=request_spec)
        self.notifier.info(context, 'scheduler.run_instance.start', payload)

        instance_uuids = request_spec.get('instance_uuids')
        LOG.info(_("Attempting to build %(num_instances)d instance(s) "
                    "uuids: %(instance_uuids)s"),
                  {'num_instances': len(instance_uuids),
                   'instance_uuids': instance_uuids})
        LOG.debug(_("Request Spec: %s") % request_spec)
        weighed_hosts = self._schedule(context, request_spec,
                                       filter_properties, instance_uuids)

        """ EPA_QA part start """
        """  No Multitenancy algorithm  """
        if request_spec['instance_properties']['workload_type'] and \
                        filter_properties.has_key('pci_requests') and  weighed_hosts:
            selected_hosts = [ host.obj.nodename for host in  weighed_hosts]

            tenant_id = filter_properties['project_id']

            pci_requests = filter_properties['pci_requests']
            nmt = NoMultiTenancy()
            node_cck_dict = nmt.execute_no_multitenancy(selected_hosts, tenant_id)
            node_cck_values = node_cck_dict.values()
            node_cck_list = []

            for i in range(len(node_cck_values)):
                for j in range(len(node_cck_values[i])):
                    node_cck_list.append(node_cck_values[i][j])
            cns = ComputeNodeSelection(weighed_hosts, pci_requests)
            if node_cck_list:
                """ Compute node selection """
                weighed_hosts = cns.execute_compute_node_selection(node_cck_dict)
            else:
                raise exception.NoValidHost(reason="Other tenancy found on all cave creeks")

        """ EPA QA part end """

        # NOTE: Pop instance_uuids as individual creates do not need the
        # set of uuids. Do not pop before here as the upper exception
        # handler fo NoValidHost needs the uuid to set error state
        instance_uuids = request_spec.pop('instance_uuids')

        # NOTE(comstud): Make sure we do not pass this through.  It
        # contains an instance of RpcContext that cannot be serialized.
        filter_properties.pop('context', None)

        for num, instance_uuid in enumerate(instance_uuids):
            request_spec['instance_properties']['launch_index'] = num

            try:
                try:
                    weighed_host = weighed_hosts.pop(0)
		    """ VF allocation algorithm """
                    if request_spec['instance_properties']['policy'] and request_spec['instance_properties']['workload_type'] \
                                               and filter_properties.has_key('pci_requests') and weighed_host:
                        weighed_host.obj.limits['selected_vfs'] = {}
                        req_vf = self.get_requested_number_of_vf_from_pci_requests(filter_properties['pci_requests'])
                        los =  request_spec['instance_properties']['policy']
                        req_work_load_type = request_spec['instance_properties']['workload_type']
                        cck_list = node_cck_dict[weighed_host.obj.nodename]
                        address_list =  vf_allocation.execute_vf_allocation(req_vf, los, req_work_load_type, cck_list)
                        if address_list == []:
                            raise exception.NoValidHost(reason="No suitable vf's found for the instance")
                        else:
                            weighed_host.obj.limits['selected_vfs'][PCI_ALIAS_NAME] = address_list
                    LOG.info(_("Choosing host %(weighed_host)s "
                                "for instance %(instance_uuid)s"),
                              {'weighed_host': weighed_host,
                               'instance_uuid': instance_uuid})
                except IndexError:
                    raise exception.NoValidHost(reason="")
                except Exception as ex:
                    print ex
                    raise ex

                self._provision_resource(context, weighed_host,
                                         request_spec,
                                         filter_properties,
                                         requested_networks,
                                         injected_files, admin_password,
                                         is_first_time,
                                         instance_uuid=instance_uuid,
                                         legacy_bdm_in_spec=legacy_bdm_in_spec)
            except Exception as ex:
                # NOTE(vish): we don't reraise the exception here to make sure
                #             that all instances in the request get set to
                #             error properly
                driver.handle_schedule_error(context, ex, instance_uuid,
                                             request_spec)
            # scrub retry host list in case we're scheduling multiple
            # instances:
            retry = filter_properties.get('retry', {})
            retry['hosts'] = []

        self.notifier.info(context, 'scheduler.run_instance.end', payload)

    def get_requested_number_of_vf_from_pci_requests(self, pci_requests):
	"""Returns requested number of vf from pci requests"""
        for pci_request in pci_requests:
            if pci_request['alias_name'] == PCI_ALIAS_NAME:
                return pci_request['count']

def notify_decorator(name, fn):
    """ Default decorator for notify which is used from utils.monkey_patch(). DONT REMOVE IT."""
    return fn

@classmethod
def filter_scheduler_new(cls, *args, **kwargs):
    """Function which helps overridden of __new__ method in nova.scheduler.filter_scheduler_patch.FilterSchedulerPatch"""
    filter_scheduler = object.__new__(FilterSchedulerPatch)
    return filter_scheduler

def FilterSchedulerPatchMain():
    FilterScheduler.__new__ = filter_scheduler_new

FilterSchedulerPatchMain()


text:
from ironic.common import network
from ironic.common import utils
from ironic.conductor import task_manager
from ironic.db import api as dbapi
from ironic.tests.conductor import utils as mgr_utils
from ironic.tests.db import base as db_base
from ironic.tests.db import utils as db_utils
from ironic.tests.objects import utils as object_utils

class TestNetwork(db_base.DbTestCase):

    def setUp(self):
        super(TestNetwork, self).setUp()
        mgr_utils.mock_the_extension_manager(driver='fake')
        self.dbapi = dbapi.get_instance()
        self.node = object_utils.create_test_node(self.context)

    def _create_test_port(self, **kwargs):
        p = db_utils.get_test_port(**kwargs)
        return self.dbapi.create_port(p)

    def test_get_node_vif_ids_no_ports(self):
        expected = {}
        with task_manager.acquire(self.context, self.node.uuid) as task:
            result = network.get_node_vif_ids(task)
        self.assertEqual(expected, result)

    def test_get_node_vif_ids_one_port(self):
        port1 = self._create_test_port(node_id=self.node.id,
                                       id=6,
                                       address='aa:bb:cc',
                                       uuid=utils.generate_uuid(),
                                       extra={'vif_port_id': 'test-vif-A'},
                                       driver='fake')
        expected = {port1.uuid: 'test-vif-A'}
        with task_manager.acquire(self.context, self.node.uuid) as task:
            result = network.get_node_vif_ids(task)
        self.assertEqual(expected, result)

    def test_get_node_vif_ids_two_ports(self):
        port1 = self._create_test_port(node_id=self.node.id,
                                       id=6,
                                       address='aa:bb:cc',
                                       uuid=utils.generate_uuid(),
                                       extra={'vif_port_id': 'test-vif-A'},
                                       driver='fake')
        port2 = self._create_test_port(node_id=self.node.id,
                                       id=7,
                                       address='dd:ee:ff',
                                       uuid=utils.generate_uuid(),
                                       extra={'vif_port_id': 'test-vif-B'},
                                       driver='fake')
        expected = {port1.uuid: 'test-vif-A', port2.uuid: 'test-vif-B'}
        with task_manager.acquire(self.context, self.node.uuid) as task:
            result = network.get_node_vif_ids(task)
        self.assertEqual(expected, result)


text:
package com.alipay.api.domain;

import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;

/**
 * 单发模板消息
 *
 * @author auto create
 * @since 1.0, 2018-03-07 10:30:34
 */
public class AlipayOpenPublicMessageSingleSendModel extends AlipayObject {

	private static final long serialVersionUID = 6315693642484693657L;

	/**
	 * 消息模板相关参数,其中包括templateId模板ID和context模板上下文
	 */
	@ApiField("template")
	private Template template;

	/**
	 * 消息接收用户的userid
	 */
	@ApiField("to_user_id")
	private String toUserId;

	public Template getTemplate() {
		return this.template;
	}
	public void setTemplate(Template template) {
		this.template = template;
	}

	public String getToUserId() {
		return this.toUserId;
	}
	public void setToUserId(String toUserId) {
		this.toUserId = toUserId;
	}

}


text:
namespace Microsoft.Azure.Management.ResourceManager
{
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using Microsoft.Rest.Azure;
    using Models;

    /// <summary>
    /// </summary>
    public partial class ResourceManagementClient : ServiceClient<ResourceManagementClient>, IResourceManagementClient, IAzureClient
    {
        /// <summary>
        /// The base URI of the service.
        /// </summary>
        public Uri BaseUri { get; set; }

        /// <summary>
        /// Gets or sets json serialization settings.
        /// </summary>
        public JsonSerializerSettings SerializationSettings { get; private set; }

        /// <summary>
        /// Gets or sets json deserialization settings.
        /// </summary>
        public JsonSerializerSettings DeserializationSettings { get; private set; }

        /// <summary>
        /// Gets Azure subscription credentials.
        /// </summary>
        public ServiceClientCredentials Credentials { get; private set; }

        /// <summary>
        /// Gets subscription credentials which uniquely identify Microsoft Azure
        /// subscription. The subscription ID forms part of the URI for every service
        /// call.
        /// </summary>
        public string SubscriptionId { get; set; }

        /// <summary>
        /// Client Api Version.
        /// </summary>
        public string ApiVersion { get; private set; }

        /// <summary>
        /// Gets or sets the preferred language for the response.
        /// </summary>
        public string AcceptLanguage { get; set; }

        /// <summary>
        /// Gets or sets the retry timeout in seconds for Long Running Operations.
        /// Default value is 30.
        /// </summary>
        public int? LongRunningOperationRetryTimeout { get; set; }

        /// <summary>
        /// When set to true a unique x-ms-client-request-id value is generated and
        /// included in each request. Default is true.
        /// </summary>
        public bool? GenerateClientRequestId { get; set; }

        public virtual IDeploymentsOperations Deployments { get; private set; }

        public virtual IProvidersOperations Providers { get; private set; }

        public virtual IResourceGroupsOperations ResourceGroups { get; private set; }

        public virtual IResourcesOperations Resources { get; private set; }

        public virtual ITagsOperations Tags { get; private set; }

        public virtual IDeploymentOperationsOperations DeploymentOperations { get; private set; }

        /// <summary>
        /// Initializes a new instance of the ResourceManagementClient class.
        /// </summary>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        protected ResourceManagementClient(params DelegatingHandler[] handlers) : base(handlers)
        {
            this.Initialize();
        }

        /// <summary>
        /// Initializes a new instance of the ResourceManagementClient class.
        /// </summary>
        /// <param name='rootHandler'>
        /// Optional. The http client handler used to handle http transport.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        protected ResourceManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
        {
            this.Initialize();
        }

        /// <summary>
        /// Initializes a new instance of the ResourceManagementClient class.
        /// </summary>
        /// <param name='baseUri'>
        /// Optional. The base URI of the service.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        protected ResourceManagementClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
        {
            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }
            this.BaseUri = baseUri;
        }

        /// <summary>
        /// Initializes a new instance of the ResourceManagementClient class.
        /// </summary>
        /// <param name='baseUri'>
        /// Optional. The base URI of the service.
        /// </param>
        /// <param name='rootHandler'>
        /// Optional. The http client handler used to handle http transport.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        protected ResourceManagementClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
        {
            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }
            this.BaseUri = baseUri;
        }

        /// <summary>
        /// Initializes a new instance of the ResourceManagementClient class.
        /// </summary>
        /// <param name='credentials'>
        /// Required. Gets Azure subscription credentials.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        public ResourceManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            this.Credentials = credentials;
            if (this.Credentials != null)
            {
                this.Credentials.InitializeServiceClient(this);
            }
        }

        /// <summary>
        /// Initializes a new instance of the ResourceManagementClient class.
        /// </summary>
        /// <param name='credentials'>
        /// Required. Gets Azure subscription credentials.
        /// </param>
        /// <param name='rootHandler'>
        /// Optional. The http client handler used to handle http transport.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        public ResourceManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            this.Credentials = credentials;
            if (this.Credentials != null)
            {
                this.Credentials.InitializeServiceClient(this);
            }
        }

        /// <summary>
        /// Initializes a new instance of the ResourceManagementClient class.
        /// </summary>
        /// <param name='baseUri'>
        /// Optional. The base URI of the service.
        /// </param>
        /// <param name='credentials'>
        /// Required. Gets Azure subscription credentials.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        public ResourceManagementClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
        {
            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            this.BaseUri = baseUri;
            this.Credentials = credentials;
            if (this.Credentials != null)
            {
                this.Credentials.InitializeServiceClient(this);
            }
        }

        /// <summary>
        /// Initializes a new instance of the ResourceManagementClient class.
        /// </summary>
        /// <param name='baseUri'>
        /// Optional. The base URI of the service.
        /// </param>
        /// <param name='credentials'>
        /// Required. Gets Azure subscription credentials.
        /// </param>
        /// <param name='rootHandler'>
        /// Optional. The http client handler used to handle http transport.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        public ResourceManagementClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
        {
            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            this.BaseUri = baseUri;
            this.Credentials = credentials;
            if (this.Credentials != null)
            {
                this.Credentials.InitializeServiceClient(this);
            }
        }

        /// <summary>
        /// Initializes client properties.
        /// </summary>
        private void Initialize()
        {
            this.Deployments = new DeploymentsOperations(this);
            this.Providers = new ProvidersOperations(this);
            this.ResourceGroups = new ResourceGroupsOperations(this);
            this.Resources = new ResourcesOperations(this);
            this.Tags = new TagsOperations(this);
            this.DeploymentOperations = new DeploymentOperationsOperations(this);
            this.BaseUri = new Uri("https://management.azure.com");
            this.ApiVersion = "2016-07-01";
            this.AcceptLanguage = "en-US";
            this.LongRunningOperationRetryTimeout = 30;
            this.GenerateClientRequestId = true;
            SerializationSettings = new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                DateFormatHandling = DateFormatHandling.IsoDateFormat,
                DateTimeZoneHandling = DateTimeZoneHandling.Utc,
                NullValueHandling = NullValueHandling.Ignore,
                ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                ContractResolver = new ReadOnlyJsonContractResolver(),
                Converters = new List<JsonConverter>
                    {
                        new Iso8601TimeSpanConverter()
                    }
            };
            SerializationSettings.Converters.Add(new ResourceJsonConverter());
            DeserializationSettings = new JsonSerializerSettings
            {
                DateFormatHandling = DateFormatHandling.IsoDateFormat,
                DateTimeZoneHandling = DateTimeZoneHandling.Utc,
                NullValueHandling = NullValueHandling.Ignore,
                ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                ContractResolver = new ReadOnlyJsonContractResolver(),
                Converters = new List<JsonConverter>
                    {
                        new Iso8601TimeSpanConverter()
                    }
            };
            DeserializationSettings.Converters.Add(new ResourceJsonConverter());
            DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
        }
    }
}