text:
//***********************************************************************************
//Program: Minesweeper
//Description: Allows user to play  game of Minesweeper
//Date: Mar. 24, 2014
//Author: JD Silver
//Course: CNT1700
//Class: CNT2C/D
//***********************************************************************************

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GDIDrawer;

namespace CMPE1700BrandonFooteLAB2
{
    public partial class frmMain : Form
    {
        //Definition of the GDIDrawer window
        public static CDrawer GameField = new CDrawer(500, 500, false, true);
        //Cell state enumeration
        public enum EState { Invisible=1, Visible, Guess, Mine };
        //Game cell array
        public static SCell[,] CellArray = new SCell[10, 10];
        //Tracks debug visibility
        public static bool Invisible = false;
        //Tracks number of mines visible on the game form
        public static int VisibleNumberOfMines = 10;
        //tracks total number of mines revealed
        public static int TotalInvisible = 100;

        //Structure definition for game array cells
        public struct SCell
        {
            public EState _Estate;
            public string _State;

            public SCell(EState estate, string state)
            {
                _Estate = estate;
                _State = "";
            }
        }

        //********************************************************************************************
        //Method: public static void NewGame()
        //Purpose: Creates a new game when the New Game button is clicked
        //Parameters: N/A
        //Returns: nothing
        //*********************************************************************************************
        public static void NewGame()
        {
            //Clears the gamefield
            GameField.Clear();

            int count = 0;      //Sets a counting variable to track mine creation
            Random random = new Random();       //Creates a random number object
            int x = 0;          //Initializes a varaible to track the X value
            int y = 0;          //Initializes a variable to track the Y value

            //Loop to create the array of game cells
            for (int count1 = 0; count1 < 10; count1++)
            {
                for (int count2 = 0; count2 < 10; count2++)
                {
                    //Creates a new Game Cell for each location in the array
                    CellArray[count1, count2] = new SCell(EState.Invisible, "");
                }
            }

            //Loops while fewer than 10 mines have been created
            do
            {
                //Loops while the cell contains a mine
                do
                {
                    x = random.Next(0,10);      //Generates a random number for the X location
                    y = random.Next(0,10);      //Generates a random number for the Y location
                }
                while(CellArray[x,y]._State == "Mine");
                //Sets cell to a mine if it does not contain one
                CellArray[x,y]._State = "Mine";
                //adds one to mine total
                count++;
            }
            while (count < 10);

            //Loop to check all cells in array for mines, and place numbers in
            //surrounding cells for number of mines touching them
            for (int Row = 0; Row < 10; Row++)
            {
                for(int Column = 0; Column < 10; Column++)
                {
                    //tracks number of mines surrounding each cell
                    int MineCount = 0;
                    if (CellArray[Row, Column]._State == "Mine")
                    {
                    }
                    //error checking for top left corner
                    else if (Row == 0 && Column == 0)
                    {
                        if(CellArray[Row+1,Column]._State == "Mine")
                            MineCount++;
                        if(CellArray[Row+1,Column+1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row, Column + 1]._State == "Mine")
                            MineCount++;
                        CellArray[Row, Column]._State = MineCount.ToString();
                    }
                    //error checking for bottom left corner
                    else if (Row == 0 && Column == 9)
                    {
                        if (CellArray[Row + 1, Column-1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row + 1, Column]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row, Column - 1]._State == "Mine")
                            MineCount++;
                        CellArray[Row, Column]._State = MineCount.ToString();
                    }
                        //error checking for top right corner
                    else if (Row == 9 && Column == 0)
                    {
                        if (CellArray[Row - 1, Column]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row - 1, Column + 1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row, Column + 1]._State == "Mine")
                            MineCount++;
                        CellArray[Row, Column]._State = MineCount.ToString();
                    }
                    //Error checking for bottom right corner
                    else if (Row == 9 && Column == 9)
                    {
                        if (CellArray[Row - 1, Column]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row - 1, Column - 1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row, Column - 1]._State == "Mine")
                            MineCount++;
                        CellArray[Row, Column]._State = MineCount.ToString();
                    }
                    //error checking for right wall
                    else if (Row == 0)
                    {
                        if (CellArray[Row + 1, Column-1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row, Column - 1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row, Column + 1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row + 1, Column + 1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row + 1, Column]._State == "Mine")
                            MineCount++;
                        CellArray[Row, Column]._State = MineCount.ToString();
                    }
                    //Error checking for top wall
                    else if (Column == 0)
                    {
                        if (CellArray[Row, Column + 1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row - 1, Column + 1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row + 1, Column + 1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row + 1, Column]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row - 1, Column]._State == "Mine")
                            MineCount++;
                        CellArray[Row, Column]._State = MineCount.ToString();
                    }
                    //Error checking for bottom wall
                    else if (Column == 9)
                    {
                        if (CellArray[Row + 1, Column]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row + 1, Column - 1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row, Column - 1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row - 1, Column]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row - 1, Column - 1]._State == "Mine")
                            MineCount++;
                        CellArray[Row, Column]._State = MineCount.ToString();
                    }
                    //Error checking for right wall
                    else if (Row == 9)
                    {
                        if (CellArray[Row, Column - 1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row, Column + 1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row - 1, Column + 1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row - 1, Column]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row - 1, Column - 1]._State == "Mine")
                            MineCount++;
                        CellArray[Row, Column]._State = MineCount.ToString();
                    }
                    //Runs if cell is not on a wall or corner
                    else
                    {
                        if (CellArray[Row - 1, Column - 1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row - 1, Column]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row - 1, Column + 1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row, Column - 1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row, Column + 1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row + 1, Column - 1]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row + 1, Column]._State == "Mine")
                            MineCount++;
                        if (CellArray[Row + 1, Column + 1]._State == "Mine")
                            MineCount++;
                        CellArray[Row, Column]._State = MineCount.ToString();
                    }
                }
            }
        }

        //********************************************************************************************
        //Method: public static void DisplayGame()
        //Purpose: Displays the game to a GDIDrwaer window
        //Parameters: N/A
        //Returns: nothing
        //*********************************************************************************************
        public static void DisplayGame()
        {
            //Enters if visibility is set to false
            if (Invisible == false)
            {
                //Loops through entire cell array
                for (int count = 0; count < 10; count++)
                {
                    for (int count2 = 0; count2 < 10; count2++)
                    {
                        //Enters if cell EState is set to invisible
                        if (CellArray[count, count2]._Estate == EState.Invisible)
                        {
                            //Draws a black square with a white border to the Drawing window
                            GameField.AddRectangle(count, count2, 1, 1, Color.Black, 1, Color.White);
                        }
                        //Enters if cell EState is set to mine
                        if (CellArray[count, count2]._Estate == EState.Mine)
                        {
                            //Draws a Black square with a white border and a red M to the Drawing window
                            GameField.AddRectangle(count, count2, 1, 1, Color.Black, 1, Color.White);
                            GameField.AddText("M", 25, count, count2, 1, 1, Color.Red);
                        }
                        //Enters is cell EState is set to visible
                        //Checks what number is in the cell state
                        //Draws number with appropriate text color to the window on a white square with black border
                        if (CellArray[count, count2]._Estate == EState.Visible)
                        {
                            if (CellArray[count, count2]._State != "0")
                            {
                                //Draws a blue 1
                                if (CellArray[count, count2]._State == "1")
                                {
                                    GameField.AddRectangle(count, count2, 1, 1, Color.White, 1, Color.Black);
                                    GameField.AddText(CellArray[count, count2]._State, 25, count, count2, 1, 1, Color.Blue);
                                }
                                //Draws a Green 2
                                else if (CellArray[count, count2]._State == "2")
                                {
                                    GameField.AddRectangle(count, count2, 1, 1, Color.White, 1, Color.Black);
                                    GameField.AddText(CellArray[count, count2]._State, 25, count, count2, 1, 1, Color.Green);
                                }
                                //Draws a Gold 3
                                else if (CellArray[count, count2]._State == "3")
                                {
                                    GameField.AddRectangle(count, count2, 1, 1, Color.White, 1, Color.Black);
                                    GameField.AddText(CellArray[count, count2]._State, 25, count, count2, 1, 1, Color.Gold);
                                }
                                //Draws an orange 4
                                else if (CellArray[count, count2]._State == "4")
                                {
                                    GameField.AddRectangle(count, count2, 1, 1, Color.White, 1, Color.Black);
                                    GameField.AddText(CellArray[count, count2]._State, 25, count, count2, 1, 1, Color.Orange);
                                }
                                //Draws a Pink 5
                                else if (CellArray[count, count2]._State == "5")
                                {
                                    GameField.AddRectangle(count, count2, 1, 1, Color.White, 1, Color.Black);
                                    GameField.AddText(CellArray[count, count2]._State, 25, count, count2, 1, 1, Color.Salmon);
                                }
                            }
                            else
                                //Draws a White square with a black border if sell is empty and visible
                                GameField.AddRectangle(count, count2, 1, 1, Color.White, 1, Color.Black);
                        }
                        //Checks if cell EState is a guess and draws a blue '?'
                        if (CellArray[count, count2]._Estate == EState.Guess)
                        {
                            GameField.AddRectangle(count, count2, 1, 1, Color.Black, 1, Color.White);
                            GameField.AddText("?", 25, count, count2, 1, 1, Color.Blue);
                        }
                    }
                }
                //Renders the CDrawer
                GameField.Render();
            }
            //Enters if visibility is set to true (Debug Mode)
            if (Invisible == true)
            {
                //Loops through cell array
                for (int count = 0; count < 10; count++)
                {
                    for (int count2 = 0; count2 < 10; count2++)
                    {
                        //Draws cell as a white square with black border
                        GameField.AddRectangle(count, count2, 1, 1, Color.White, 1, Color.Black);

                        //Cehcks if cell EState is 'mine'
                        if (CellArray[count, count2]._State == "Mine")
                        {
                            //Draws a Red 'M' to the cell
                            GameField.AddText("M", 25, count, count2, 1, 1, Color.Red);
                        }
                        //Checks if cell contains a number between 1 and 5
                        if (CellArray[count, count2]._State == "1"||
                            CellArray[count,count2]._State=="2"||
                            CellArray[count,count2]._State=="3"||
                            CellArray[count,count2]._State=="4"||
                            CellArray[count, count2]._State == "5")
                        {
                            //Checks if cell contains 1 and draws a blue 1
                            if (CellArray[count, count2]._State == "1")
                            {
                                GameField.AddRectangle(count, count2, 1, 1, Color.White, 1, Color.Black);
                                GameField.AddText(CellArray[count, count2]._State, 25, count, count2, 1, 1, Color.Blue);
                            }
                            //Checks if cell contains 2 and draws a green 2
                            else if (CellArray[count, count2]._State == "2")
                            {
                                GameField.AddRectangle(count, count2, 1, 1, Color.White, 1, Color.Black);
                                GameField.AddText(CellArray[count, count2]._State, 25, count, count2, 1, 1, Color.Green);
                            }
                            //Checks if cell contains 3 and draws a gold 3
                            else if (CellArray[count, count2]._State == "3")
                            {
                                GameField.AddRectangle(count, count2, 1, 1, Color.White, 1, Color.Black);
                                GameField.AddText(CellArray[count, count2]._State, 25, count, count2, 1, 1, Color.Gold);
                            }
                            //Checks if cell contains 4 and draws an orange 4
                            else if (CellArray[count, count2]._State == "4")
                            {
                                GameField.AddRectangle(count, count2, 1, 1, Color.White, 1, Color.Black);
                                GameField.AddText(CellArray[count, count2]._State, 25, count, count2, 1, 1, Color.Orange);
                            }
                            //Checks if cell contains 5 and draws a pink 5
                            else if (CellArray[count, count2]._State == "5")
                            {
                                GameField.AddRectangle(count, count2, 1, 1, Color.White, 1, Color.Black);
                                GameField.AddText(CellArray[count, count2]._State, 25, count, count2, 1, 1, Color.Salmon);
                            }
                        }
                    }
                }
                //Renders game field
                GameField.Render();
            }
        }

        //********************************************************************************************
        //Method: public static void ClearGame()
        //Purpose: Clears game field
        //Parameters: N/A
        //Returns: nothing
        //*********************************************************************************************
        public static void ClearGame()
        {
            //Loops through cell array and resets all values
            for (int count = 0; count < 10; count++)
            {
                for (int count2 = 0; count2 < 10; count2++)
                {
                    //Sets state to blank
                    CellArray[count, count2]._State = "";
                    //Sets EState to invisible
                    CellArray[count, count2]._Estate = EState.Invisible;
                }
            }
        }

        //********************************************************************************************
        //Method: public static void ClearEmpty(int x, int y)
        //Purpose: Recursively clears all cells if clicked cell is empty
        //Parameters: int x - the X-location of last mouse left click
        //int y - the Y-location of last mouose left click
        //Returns: nothing
        //*********************************************************************************************
        public static void ClearEmpty(int x, int y)
        {
            if (x >= 0 && x <= 9 && y >= 0 && y <= 9)
            {
                //returns from method if cell is invisible
                if (CellArray[x, y]._Estate != EState.Invisible)
                {
                    return;
                }
                //Returns from method if cell is a mine
                else if (CellArray[x, y]._State == "Mine")
                {
                    return;
                }
                //If cells is not blank sets cell EState fo visible and returns from method
                else if (CellArray[x, y]._State != "")
                {
                    CellArray[x, y]._Estate = EState.Visible;
                    TotalInvisible--;
                    if (CellArray[x, y]._State == "1")
                        return;
                    if (CellArray[x, y]._State == "2")
                        return;
                    if (CellArray[x, y]._State == "3")
                        return;
                    if (CellArray[x, y]._State == "4")
                        return;
                    if (CellArray[x, y]._State == "5")
                        return;
                }
                    //Recursively calls method
                    ClearEmpty(x - 1, y);
                    ClearEmpty(x + 1, y);
                    ClearEmpty(x, y - 1);
                    ClearEmpty(x, y + 1);
                    ClearEmpty(x - 1, y - 1);
                    ClearEmpty(x - 1, y + 1);
                    ClearEmpty(x + 1, y + 1);
                    ClearEmpty(x + 1, y - 1);
                    return;
            }
        }

        //********************************************************************************************
        //Method: public static string CheckWin(Point newPoint)
        //Purpose: Check if user has won or lost
        //Parameters: Point newPoint - Holds value of last mouse left click
        //Returns: string success - holds user win/loss value
        //*********************************************************************************************
        public static string CheckWin(Point newPoint)
        {
            int mineCount = 0;      //Variable to count number of mines found
            string success = "";    //Varaible to store Win/Loss value
            //Checks if user left clicked a mine
            if (CellArray[newPoint.X, newPoint.Y]._State == "Mine")
            {
                success = "Game Over";      //Sets success to Game Over
                return success;             //Returns from method
            }
            //Loops through cell array
            for (int rows = 0; rows < 10; rows++)
            {
                for (int columns = 0; columns < 10; columns++)
                {
                    //Checks if cell EState and state are both 'mine'
                    if (CellArray[rows, columns]._Estate == EState.Mine && CellArray[rows, columns]._State == "Mine")
                        mineCount++;    //Adds one to minecount
                    //Checks if all mines are clicked, or all non-mines are revealed
                    if (mineCount == 10 || TotalInvisible == (10 - mineCount))
                    {
                        success = "You Win";    //Sets success to "You Win"
                        return success;         //Returns from method
                    }
                }
            }
            return success;
        }

        public frmMain()
        {
            InitializeComponent();
        }

        //********************************************************************************************
        //Method: frmMain_Load(object sender, EventArs e)
        //Purpose: Runs on form load
        //Returns: nothing
        //*********************************************************************************************
        private void frmMain_Load(object sender, EventArgs e)
        {
            GameField.Scale = 50;
            lblNumMines.Visible = true;
        }

        //********************************************************************************************
        //Method: btnNewGame_Click(object sender, EventArgs e)
        //Purpose: Button click event for New Game button
        //Returns: nothing
        //*********************************************************************************************
        private void btnNewGame_Click(object sender, EventArgs e)
        {
            Point nPoint = new Point();     //Stores left button click
            Point rPoint = new Point();     //Stroes right button click
            ClearGame();    //Clears game
            NewGame();      //Creates a new game
            DisplayGame();  //Displays game
            GameField.GetLastMouseLeftClickScaled(out nPoint);  //Reads mouse left click
            GameField.GetLastMouseRightClickScaled(out rPoint); //Reads mouse right click
            btnNewGame.Enabled = false;     //Disables NewGame button
            tmrGameTimer.Start();   //Starts timer for game events
        }

        //********************************************************************************************
        //Method: chbxDebug_CheckedChanged(object sender, EventArgs e)
        //Purpose: change event for Debug checkbox
        //Returns: nothing
        //*********************************************************************************************
        private void chbxDebug_CheckedChanged(object sender, EventArgs e)
        {
            //Checks if debug box is selected
            if (chbxDebug.Checked == true)
            {
                Invisible = true;   //Sets visibility to true
                GameField.Clear();  //Clears gamefield
                DisplayGame();      //Redisplays gamefield
            }
            else
            {
                Invisible = false;  //Sets visibility to false
                GameField.Clear();  //Clears gamefield
                DisplayGame();      //Redispalys gamefield
            }
        }

        private void tmrGameTimer_Tick(object sender, EventArgs e)
        {
            Point newPoint = new Point();   //Point variable to store left clicks
            Point RightPoint = new Point(); //Point variable to stroe right clicks
            bool success = false;           //Stores left click success
            bool success2 = false;          //Stores right click success
            string WinLose = "";            //Holds Win/Loss string

            //Reads in a left click and stores the scaled location
            success = GameField.GetLastMouseLeftClickScaled(out newPoint);
            //Reads in a right click and stores the scaled location
            success2 = GameField.GetLastMouseRightClickScaled(out RightPoint);

            //checks if left click and NOT right click
            if (success && !success2)
                ClearEmpty(newPoint.X, newPoint.Y); //Calls ClearEmpty recursive  method

            //Checks if right click and NOT left click
            if (success2 && !success)
            {
                //Checks if cell is visible
                if (CellArray[RightPoint.X, RightPoint.Y]._Estate == EState.Invisible)
                {
                    //sets invisible cell to mine
                    CellArray[RightPoint.X, RightPoint.Y]._Estate = EState.Mine;
                    //decreases number of mines visible on the game form by 1
                    VisibleNumberOfMines--;
                }
                //Checks if cell is a mine
                else if (CellArray[RightPoint.X, RightPoint.Y]._Estate == EState.Mine)
                {
                    //Sets mine cell to a guess
                    CellArray[RightPoint.X, RightPoint.Y]._Estate = EState.Guess;
                    //Increases number of mines visible on game form by 1
                    VisibleNumberOfMines++;
                }
                //Checks if cell is a guess
                else if(CellArray[RightPoint.X,RightPoint.Y]._Estate == EState.Guess)
                    //Changes guess to invisible
                    CellArray[RightPoint.X, RightPoint.Y]._Estate = EState.Invisible;
            }
            //Updates number of mines visible on the form
            lblNumMines.Text = VisibleNumberOfMines.ToString();

            if (success && !success2)
            {
                WinLose = CheckWin(newPoint);
                DisplayGame();
            }

            if (!success && success2)
            {
                WinLose = CheckWin(newPoint);
                DisplayGame();
            }

            //Checks if Win/Loss variable is "Game Over"
            //Displays entire game field if true
            //Diplays "Game Over" in red text over game field
            //resets all global variables
            if (WinLose == "Game Over")
            {
                Invisible = true;
                DisplayGame();
                GameField.AddText("Boom", 50, Color.Red);
                tmrGameTimer.Stop();
                VisibleNumberOfMines = 10;
                Invisible = false;
                btnNewGame.Enabled = true;
            }

            //Checks if Win/Loss variable is "You Win"
            //Displays entire game field if true
            //Displays "You Win" in green text over game field
            //Resets all global variables
            else if (WinLose == "You Win")
            {
                Invisible = true;
                DisplayGame();
                GameField.AddText(WinLose, 50, Color.Green);
                VisibleNumberOfMines = 10;
                tmrGameTimer.Stop();
                Invisible = false;
                btnNewGame.Enabled = true;
            }
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lepiota subvolvata var. subvolvata

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
from django.db import models
from django.utils import timezone

from .tasks import gcm_send_message_task

class InvalidDeviceType(ValueError):
    """
    Exception raised when a device_type other
    than those supported is specified.
    """
    pass

class AbstractBaseDevice(models.Model):
    """
    You should make a subclass of this model that links to your User model.
    """

    DEVICE_TYPE_ANDROID = 'android'
    DEVICE_TYPE_CHOICES = (
        (DEVICE_TYPE_ANDROID, 'Android'),
    )

    device_type = models.CharField(
        max_length=10,
        choices=DEVICE_TYPE_CHOICES)

    added_at = models.DateTimeField(default=timezone.now)
    modified_at = models.DateTimeField(auto_now=True)

    is_active = models.BooleanField(
        default=True)
    invalidated = models.BooleanField(
        default=False)

    app_id = models.CharField(
        max_length=16,
        default=None,
        null=True)

    device_id = models.TextField()

    class Meta:
        abstract = True

    def send_message(self, message):
        if self.invalidated or not self.is_active:
            return

        if self.device_type == self.DEVICE_TYPE_ANDROID:
            return gcm_send_message_task.apply_async(args=[self.pk, message])

        else:
            raise InvalidDeviceType(
                '{} is not supported.'.format(self.get_device_type_display()))


text:
@interface MYBeautyShopController : UIViewController

@end


text:
The tests are run with the help of <http://github.com/sstephenson/bats>.

To run a test, use:

        bats test-file-name.bats

Or use the `make` command:

    cd /path/to/bash-utils
    make tests


text:
using System;
using System.Diagnostics.Contracts;
using System.Globalization;

namespace Orleans.Runtime
{
    [Serializable]
    internal class GrainId : UniqueIdentifier, IEquatable<GrainId>
    {
        private static readonly object lockable = new object();
        private const int INTERN_CACHE_INITIAL_SIZE = InternerConstants.SIZE_LARGE;
        private static readonly TimeSpan internCacheCleanupInterval = InternerConstants.DefaultCacheCleanupFreq;

        private static Interner<UniqueKey, GrainId> grainIdInternCache;

        public UniqueKey.Category Category { get { return Key.IdCategory; } }

        public bool IsSystemTarget { get { return Key.IsSystemTargetKey; } }

        public bool IsGrain { get { return Category == UniqueKey.Category.Grain || Category == UniqueKey.Category.KeyExtGrain; } }

        public bool IsClient { get { return Category == UniqueKey.Category.ClientGrain || Category == UniqueKey.Category.ClientAddressableObject; } }

        internal bool IsClientGrain { get { return Category == UniqueKey.Category.ClientGrain; } }
        internal bool IsClientAddressableObject { get { return Category == UniqueKey.Category.ClientAddressableObject; } }

        private GrainId(UniqueKey key)
            : base(key)
        {
        }

        public static GrainId NewId()
        {
            return FindOrCreateGrainId(UniqueKey.NewKey(Guid.NewGuid(), UniqueKey.Category.Grain));
        }

        public static GrainId NewClientGrainId()
        {
            return FindOrCreateGrainId(UniqueKey.NewKey(Guid.NewGuid(), UniqueKey.Category.ClientGrain));
        }

        public static GrainId NewClientAddressableGrainId()
        {
            return FindOrCreateGrainId(UniqueKey.NewKey(Guid.NewGuid(), UniqueKey.Category.ClientAddressableObject));
        }

        internal static GrainId GetGrainId(UniqueKey key)
        {
            return FindOrCreateGrainId(key);
        }

        internal static GrainId GetSystemGrainId(Guid guid)
        {
            return FindOrCreateGrainId(UniqueKey.NewKey(guid, UniqueKey.Category.SystemGrain));
        }

        // For testing only.
        internal static GrainId GetGrainIdForTesting(Guid guid)
        {
            return FindOrCreateGrainId(UniqueKey.NewKey(guid, UniqueKey.Category.None));
        }

        internal static GrainId NewSystemTargetGrainIdByTypeCode(int typeData)
        {
            return FindOrCreateGrainId(UniqueKey.NewSystemTargetKey(Guid.NewGuid(), typeData));
        }

        internal static GrainId GetSystemTargetGrainId(short systemGrainId)
        {
            return FindOrCreateGrainId(UniqueKey.NewSystemTargetKey(systemGrainId));
        }

        internal static GrainId GetGrainId(long typeCode, long primaryKey, string keyExt=null)
        {
            return FindOrCreateGrainId(UniqueKey.NewKey(primaryKey,
                keyExt == null ? UniqueKey.Category.Grain : UniqueKey.Category.KeyExtGrain,
                typeCode, keyExt));
        }

        internal static GrainId GetGrainId(long typeCode, Guid primaryKey, string keyExt=null)
        {
            return FindOrCreateGrainId(UniqueKey.NewKey(primaryKey,
                keyExt == null ? UniqueKey.Category.Grain : UniqueKey.Category.KeyExtGrain,
                typeCode, keyExt));
        }

        internal static GrainId GetGrainId(long typeCode, string primaryKey)
        {
            return FindOrCreateGrainId(UniqueKey.NewKey(0L,
                UniqueKey.Category.KeyExtGrain,
                typeCode, primaryKey));
        }

        internal long GetPrimaryKeyLong(out string keyExt)
        {
            return Key.PrimaryKeyToLong(out keyExt);
        }

        [Pure]
        internal long GetPrimaryKeyLong()
        {
            return Key.PrimaryKeyToLong();
        }

        internal Guid GetPrimaryKey(out string keyExt)
        {
            return Key.PrimaryKeyToGuid(out keyExt);
        }

        internal Guid GetPrimaryKey()
        {
            return Key.PrimaryKeyToGuid();
        }

        internal string GetPrimaryKeyString()
        {
            string key;
            var tmp = GetPrimaryKey(out key);
            return key;
        }

        internal int GetTypeCode()
        {
            return Key.BaseTypeCode;
        }

        private static GrainId FindOrCreateGrainId(UniqueKey key)
        {
            // Note: This is done here to avoid a wierd cyclic dependency / static initialization ordering problem involving the GrainId, Constants & Interner classes
            if (grainIdInternCache != null) return grainIdInternCache.FindOrCreate(key, () => new GrainId(key));

            lock (lockable)
            {
                if (grainIdInternCache == null)
                {
                    grainIdInternCache = new Interner<UniqueKey, GrainId>(INTERN_CACHE_INITIAL_SIZE, internCacheCleanupInterval);
                }
            }
            return grainIdInternCache.FindOrCreate(key, () => new GrainId(key));
        }

        #region IEquatable<GrainId> Members

        public bool Equals(GrainId other)
        {
            return other != null && Key.Equals(other.Key);
        }

        #endregion

        public override bool Equals(UniqueIdentifier obj)
        {
            var o = obj as GrainId;
            return o != null && Key.Equals(o.Key);
        }

        public override bool Equals(object obj)
        {
            var o = obj as GrainId;
            return o != null && Key.Equals(o.Key);
        }

        // Keep compiler happy -- it does not like classes to have Equals(...) without GetHashCode() methods
        public override int GetHashCode()
        {
            return Key.GetHashCode();
        }

        /// <summary>
        /// Get a uniformly distributed hash code value for this grain, based on Jenkins Hash function.
        /// NOTE: Hash code value may be positive or NEGATIVE.
        /// </summary>
        /// <returns>Hash code for this GrainId</returns>
        public uint GetUniformHashCode()
        {
            return Key.GetUniformHashCode();
        }

        public override string ToString()
        {
            return ToStringImpl(false);
        }

        // same as ToString, just full primary key and type code
        internal string ToDetailedString()
        {
            return ToStringImpl(true);
        }

        // same as ToString, just full primary key and type code
        private string ToStringImpl(bool detailed)
        {
            string name = string.Empty;
            if (Constants.TryGetSystemGrainName(this, out name))
            {
                return name;
            }

            var keyString = Key.ToString();
            // this should grab the least-significant half of n1, suffixing it with the key extension.
            string idString = keyString;
            if (!detailed)
            {
                if (keyString.Length >= 48)
                    idString = keyString.Substring(24, 8) + keyString.Substring(48);
                else
                    idString = keyString.Substring(24, 8);
            }

            string fullString = null;
            switch (Category)
            {
                case UniqueKey.Category.Grain:
                case UniqueKey.Category.KeyExtGrain:
                    var typeString = GetTypeCode().ToString("X");
                    if (!detailed) typeString = typeString.Tail(8);
                    fullString = String.Format("*grn/{0}/{1}", typeString, idString);
                    break;
                case UniqueKey.Category.ClientGrain:
                    fullString = "*cli/" + idString;
                    break;
                case UniqueKey.Category.ClientAddressableObject:
                    fullString =  "*cliObj/" + idString;
                    break;
                case UniqueKey.Category.SystemTarget:
                    string explicitName = Constants.SystemTargetName(this);
                    if (GetTypeCode() != 0)
                    {
                        var typeStr = GetTypeCode().ToString("X");
                        return String.Format("{0}/{1}/{2}", explicitName, typeStr, idString);
                    }
                    fullString = explicitName;
                    break;
                default:
                    fullString = "???/" + idString;
                    break;
            }
            return detailed ? String.Format("{0}-0x{1, 8:X8}", fullString, GetUniformHashCode()) : fullString;
        }

        internal string ToFullString()
        {
            string kx;
            string pks =
                Key.IsLongKey ?
                    GetPrimaryKeyLong(out kx).ToString(CultureInfo.InvariantCulture) :
                    GetPrimaryKey(out kx).ToString();
            string pksHex =
                Key.IsLongKey ?
                    GetPrimaryKeyLong(out kx).ToString("X") :
                    GetPrimaryKey(out kx).ToString("X");
            return
                String.Format(
                    "[GrainId: {0}, IdCategory: {1}, BaseTypeCode: {2} (x{3}), PrimaryKey: {4} (x{5}), UniformHashCode: {6} (0x{7, 8:X8}){8}]",
                    ToDetailedString(),                        // 0
                    Category,                          // 1
                    GetTypeCode(),                     // 2
                    GetTypeCode().ToString("X"),       // 3
                    pks,                               // 4
                    pksHex,                            // 5
                    GetUniformHashCode(),              // 6
                    GetUniformHashCode(),              // 7
                    Key.HasKeyExt ?  String.Format(", KeyExtension: {0}", kx) : "");   // 8
        }

        internal string ToStringWithHashCode()
        {
            return String.Format("{0}-0x{1, 8:X8}", this.ToString(), this.GetUniformHashCode());
        }

        /// <summary>
        /// Return this GrainId in a standard string form, suitable for later use with the <c>FromParsableString</c> method.
        /// </summary>
        /// <returns>GrainId in a standard string format.</returns>
        internal string ToParsableString()
        {
            // NOTE: This function must be the "inverse" of FromParsableString, and data must round-trip reliably.

            return Key.ToHexString();
        }

        /// <summary>
        /// Create a new GrainId object by parsing string in a standard form returned from <c>ToParsableString</c> method.
        /// </summary>
        /// <param name="addr">String containing the GrainId info to be parsed.</param>
        /// <returns>New GrainId object created from the input data.</returns>
        internal static GrainId FromParsableString(string str)
        {
            // NOTE: This function must be the "inverse" of ToParsableString, and data must round-trip reliably.

            var key = UniqueKey.Parse(str);
            return FindOrCreateGrainId(key);
        }
    }
}


text:
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var fs = require('fs');

var ExtractTextPlugin = require("extract-text-webpack-plugin");
var StyleExtHtmlWebpackPlugin = require('style-ext-html-webpack-plugin');
var ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');

const internalCSS = new ExtractTextPlugin('loader.css');

module.exports = {
    entry: {
        'index.js': './src/js/index.js'
    },
    module: {
        loaders: [
            { test: /loader\.scss/, loader: internalCSS.extract("style", "css!sass") },
            { test: /\.scss$/, exclude: /loader\.scss/, loaders: ["style-loader", "css-loader", "sass-loader"] },
            { test: /\.(woff|woff2|eot|ttf)(\?.*$|$)/, loader: 'file-loader' },
            {
                test: /.*\.(gif|png|jpeg|jpg|svg|ico)(\?.*$|$)/i,
                loaders: [
                    'file-loader',
                    'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
                ]
            },
            { test: /\.html$/, loader: 'html-loader' }
        ]
    },
    output: {
        filename: '[hash].js',
        path: __dirname + '/dist'
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify('production')
            }
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: './src/index.html'
        }),
        internalCSS,
        new StyleExtHtmlWebpackPlugin('loader.css'),
        new ScriptExtHtmlWebpackPlugin({
            defaultAttribute: 'async'
        })
    ]
};


text:
package spark.rdd

import java.util.Random
import cern.jet.random.Poisson
import cern.jet.random.engine.DRand

import spark.RDD
import spark.OneToOneDependency
import spark.Split

private[spark]
class SampledRDDSplit(val prev: Split, val seed: Int) extends Split with Serializable {
  override val index: Int = prev.index
}

class SampledRDD[T: ClassManifest](
    prev: RDD[T],
    withReplacement: Boolean,
    frac: Double,
    seed: Int)
  extends RDD[T](prev.context) {

  @transient
  val splits_ = {
    val rg = new Random(seed)
    prev.splits.map(x => new SampledRDDSplit(x, rg.nextInt))
  }

  override def splits = splits_.asInstanceOf[Array[Split]]

  override val dependencies = List(new OneToOneDependency(prev))

  override def preferredLocations(split: Split) =
    prev.preferredLocations(split.asInstanceOf[SampledRDDSplit].prev)

  override def compute(splitIn: Split) = {
    val split = splitIn.asInstanceOf[SampledRDDSplit]
    if (withReplacement) {
      // For large datasets, the expected number of occurrences of each element in a sample with
      // replacement is Poisson(frac). We use that to get a count for each element.
      val poisson = new Poisson(frac, new DRand(split.seed))
      prev.iterator(split.prev).flatMap { element =>
        val count = poisson.nextInt()
        if (count == 0) {
          Iterator.empty  // Avoid object allocation when we return 0 items, which is quite often
        } else {
          Iterator.fill(count)(element)
        }
      }
    } else { // Sampling without replacement
      val rand = new Random(split.seed)
      prev.iterator(split.prev).filter(x => (rand.nextDouble <= frac))
    }
  }
}


text:
class ShaderPlugin : public Studio::Plugin
{
  Q_OBJECT
  Q_PLUGIN_METADATA(IID "ShaderPlugin" FILE "shaderplugin.json")
  Q_INTERFACES(Studio::Plugin)

  public:
    ShaderPlugin();
    virtual ~ShaderPlugin();

    bool initialise(QStringList const &arguments, QString *errormsg);

    void shutdown();

  public slots:

    QWidget *create_view(QString const &type);

    bool create(QString const &type, QString const &path, QJsonObject metadata);

    bool hash(Studio::Document *document, size_t *key);

    bool build(Studio::Document *document, QString const &path);

    bool pack(Studio::PackerState &asset, std::ofstream &fout);
};


text:
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.ads.dfa.lib.conf;

import com.google.api.ads.common.lib.conf.AdsLibConfiguration;
import com.google.inject.Inject;
import com.google.inject.name.Named;

import org.apache.commons.configuration.Configuration;

/**
 * Configuration information for DFA library.
 *
 * @author Adam Rogal
 */
public class DfaLibConfiguration extends AdsLibConfiguration {

  private static final String KEY_PREFIX = "api.dfa";

  /**
   * Constructor.
   *
   * @param config the backing configuration
   */
  @Inject
  public DfaLibConfiguration(@Named("lib") Configuration config) {
    super(config);
  }

  /**
   * Gets if OAuth2 token should be automatically refreshed. Default is
   * {@code true}.
   */
  @Override
  public boolean isAutoRefreshOAuth2TokenEnabled() {
    return config.getBoolean(KEY_PREFIX + "." + AUTO_REFRESH_OAUTH2_TOKEN_POSTFIX, true);
  }

  @Override
  public boolean isCompressionEnabled() {
    return config.getBoolean(KEY_PREFIX + "." + USE_COMPRESSION_POSTFIX, false);
  }
}


text:
<?php

use PrestaShop\PrestaShop\Core\Payment\PaymentOption;

if (!defined('_PS_VERSION_'))
    exit;

define('CULQI_SDK_VERSION', '1.3.0');

/**
 * Calling dependencies
 */
include_once dirname(__FILE__).'/libraries/Requests/library/Requests.php';

Requests::register_autoloader();

include_once dirname(__FILE__).'/libraries/culqi-php/lib/culqi.php';

class Culqi extends PaymentModule
{

    private $_postErrors = array();

    const MODULE_NAME = "culqi";
    const MODULE_AUTHOR = "Team Culqi (Brayan Cruces, Willy Aguirre) - Space-Kid  configurado por christian benavides";
    const MODULE_NAME_DISP = "Culqi";

    public function __construct()
    {
        $this->name = 'culqi';
        $this->tab = 'payments_gateways';
        $this->version = '3.0.2';
        $this->controllers = array('chargeajax','postpayment');
        $this->author = 'Team Culqi (Willy Aguirre)';
        $this->ps_versions_compliancy = array('min' => '1.7', 'max' => _PS_VERSION_);
        $this->bootstrap = true;
        $this->display = 'view';

        parent::__construct();

        $this->meta_title = 'Culqi';
        $this->displayName = 'Culqi';
        $this->description = $this->l('Acepta tarjetas de crédito y débito en tu tienda online .');
        $this->confirmUninstall = $this->l('¿Estás seguro que quieres desintalar el módulo de Culqi?');

    }

    public function install()
    {
        $this->createStates();

        return (
            parent::install() &&
            $this->registerHook('header') &&
            $this->registerHook('paymentOptions') &&
            Configuration::updateValue('CULQI_LLAVE_SECRETA', '') &&
            Configuration::updateValue('CULQI_LLAVE_PUBLICA', '')
        );
    }

    private function getAddress($address)
    {
        if(empty($address->address1)) {
            return $address->address2;
        } else {
            return $address->address1;
        }
    }

    private function getPhone($address)
    {
        if(empty($address->phone_mobile))
        {
            return $address->phone;
        } else {
            return $address->phone_mobile;
        }
    }

    private function getCustomerId()
    {
        if ($this->context->customer->isLogged())
        {
            return (int) $this->context->customer->id;
        } else {
            return 0;
        }
    }

    public function errorPayment($mensaje)
    {
        $smarty = $this->context->smarty;
        $smarty->assign('culqi_error_pago', $mensaje);
    }

    /* Se crea un Cargo con la nueva api v2 de Culqi PHP */
    public function charge($token_id, $installments)
    {

      try {

        $cart = $this->context->cart;

        $userAddress = new Address((int)$cart->id_address_invoice);
        $userCountry = new Country((int)$userAddress->id_country);

        $culqi = new Culqi\Culqi(array('api_key' => Configuration::get('CULQI_LLAVE_SECRETA')));

        $charge = $culqi->Charges->create(
            array(
              "amount" => $this->removeComma(ceil($cart->getOrderTotal(true, Cart::BOTH))*1.05),
              "antifraud_details" => array(
                  "address" => $this->getAddress($userAddress),
                  "address_city" => $userAddress->city,
                  "country_code" => $userCountry->iso_code,
                  "first_name" => $this->context->customer->firstname,
                  "last_name" => $this->context->customer->lastname,
                  "phone_number" => $this->getPhone($userAddress)
              ),
              "capture" => true,
              "currency_code" => "PEN",
              "description" => "Orden de compra ".$cart->id,
              "installments" => $installments,
              "metadata" => array("order_id"=>(string)$cart->id),
              "email" => $this->context->customer->email,
              "source_id" => $token_id
            )
        );
        //return $cargo;
        return $charge;
      } catch(Exception $e){
        return $e->getMessage();
      }

    }

    public function hookPaymentOptions($params)
    {
        if (!$this->active)
        {
          return;
        }
        if (!$this->checkCurrency($params['cart']))
        {
          return;
        }

        $newOption = new PaymentOption();

        $this->context->smarty->assign(
          $this->getCulqiInfoCheckout()
        );

        $newOption->setModuleName($this->name)
                ->setCallToActionText($this->trans('Pagar con tarjeta de credito', array(), 'Pagar con tarjeta de credito'))
                ->setAction($this->context->link->getModuleLink($this->name, 'postpayment', array(), true))
                ->setAdditionalInformation($this->context->smarty->fetch('module:culqi/views/templates/hook/payment.tpl'))
                ->setLogo(Media::getMediaPath(_PS_MODULE_DIR_.$this->name.'/views/img/logo_culqi.png'));

        $payment_options = [
            $newOption,
        ];

        return $payment_options;
    }

    public function checkCurrency($cart)
    {
        $currency_order = new Currency((int)($cart->id_currency));
        $currencies_module = $this->getCurrency((int)$cart->id_currency);

        if (is_array($currencies_module))
        {
          foreach ($currencies_module as $currency_module)
          {
            if ($currency_order->id == $currency_module['id_currency'])
            {
              return true;
            }
          }
        }

        return false;
    }

    public function getCulqiInfoCheckout(){
      $cart = $this->context->cart;
      return array(
        "module_dir" => $this->_path,
        "descripcion" => "Orden de compra ".$cart->id,
        "orden" => $cart->id,
        "total" => $cart->getOrderTotal(true, Cart::BOTH),
        "llave_publica" => Configuration::get('CULQI_LLAVE_PUBLICA')
      );
    }

    public function uninstallStates()
    {
        if (Db::getInstance()->Execute("DELETE FROM " . _DB_PREFIX_ . "order_state WHERE id_order_state = ( SELECT value
                FROM " . _DB_PREFIX_ . "configuration WHERE name =  'CULQI_STATE_OK' )") &&
            Db::getInstance()->Execute("DELETE FROM " . _DB_PREFIX_ . "order_state_lang WHERE id_order_state = ( SELECT value
                FROM " . _DB_PREFIX_ . "configuration WHERE name =  'CULQI_STATE_OK' )") &&
            Db::getInstance()->Execute("DELETE FROM " . _DB_PREFIX_ . "order_state WHERE id_order_state = ( SELECT value
                FROM " . _DB_PREFIX_ . "configuration WHERE name =  'CULQI_STATE_ERROR' )") &&
            Db::getInstance()->Execute("DELETE FROM " . _DB_PREFIX_ . "order_state_lang WHERE id_order_state = ( SELECT value
                FROM " . _DB_PREFIX_ . "configuration WHERE name =  'CULQI_STATE_ERROR' )")
        ) return true;
        return false;
    }

    public function uninstall()
    {
        if (!parent::uninstall()
        || !Configuration::deleteByName('CULQI_STATE_OK')
        || !Configuration::deleteByName('CULQI_STATE_ERROR')
        || !Configuration::deleteByName('CULQI_LLAVE_SECRETA')
        || !Configuration::deleteByName('CULQI_LLAVE_PUBLICA')
        || !$this->uninstallStates())
            return false;
        return true;
    }

    private function _postValidation()
    {
        if (Tools::isSubmit('btnSubmit'))
        {
            if (!Tools::getValue('CULQI_LLAVE_SECRETA'))
            {
              $this->_postErrors[] = $this->l('El campo llave de comercio es requerido.');
            }

            if (!Tools::getValue('CULQI_LLAVE_PUBLICA'))
            {
              $this->_postErrors[] = $this->l('El campo código de comercio es requerido.');
            }
        }
    }

    private function _displayInfo()
    {
        return $this->display(__FILE__, 'info.tpl');
    }

    public function getContent()
    {

        $this->_html = '';

        if (Tools::isSubmit('btnSubmit'))
        {
            $this->_postValidation();
            if (!count($this->_postErrors))
            {
              $this->_postProcess();
            } else {
              foreach ($this->_postErrors as $err) {
                $this->_html .= $this->displayError($err);
              }
            }
        }

        $this->_html .= $this->_displayInfo();
        $this->_html .= $this->renderForm();

        return $this->_html;
    }

    private function createStates()
    {
        if (!Configuration::get('CULQI_STATE_OK'))
        {
            $order_state = new OrderState();
            $order_state->name = array();
            foreach (Language::getLanguages() as $language) {
              $order_state->name[$language['id_lang']] = 'Exitoso';
            }
            $order_state->send_email = false;
            $order_state->color = '#39CC98';
            $order_state->hidden = false;
            $order_state->paid = true;
            $order_state->module_name = 'culqi';
            $order_state->delivery = false;
            $order_state->logable = false;
            $order_state->invoice = true;
            $order_state->pdf_invoice = true;
            $order_state->add();
            Configuration::updateValue('CULQI_STATE_OK', (int)$order_state->id);
        }
        if (!Configuration::get('CULQI_STATE_ERROR'))
        {
            $order_state = new OrderState();
            $order_state->name = array();
            foreach (Language::getLanguages() as $language) {
              $order_state->name[$language['id_lang']] = 'Incorrecto';
            }
            $order_state->send_email = false;
            $order_state->color = '#FF2843';
            $order_state->module_name = 'culqi';
            $order_state->hidden = false;
            $order_state->delivery = false;
            $order_state->logable = false;
            $order_state->invoice = false;
            $order_state->add();
            Configuration::updateValue('CULQI_STATE_ERROR', (int)$order_state->id);
        }
    }

    /**
     * Admin Zone
     */
    public function renderForm()
    {
        $fields_form = array(
            'form' => array(
                'legend' => array(
                    'title' => $this->l('CONFIGURACIONES GENERALES CULQI'),
                    'icon' => 'icon-money'
                ),
                'input' => array(
                    array(
                        'type' => 'text',
                        'label' => $this->l('Llave Pública'),
                        'name' => 'CULQI_LLAVE_PUBLICA',
                        'required' => true
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('Llave Secreta'),
                        'name' => 'CULQI_LLAVE_SECRETA',
                        'required' => true
                    )
                ),
                'submit' => array(
                    'title' => $this->l('Guardar'),
                )
            ),
        );

        $helper = new HelperForm();
        $helper->show_toolbar = false;
        $helper->table = $this->table;
        $lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
        $helper->default_form_language = $lang->id;
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
        $this->fields_form = array();
        $helper->id = (int)Tools::getValue('id_carrier');
        $helper->identifier = $this->identifier;
        $helper->submit_action = 'btnSubmit';
        $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');
        $helper->tpl_vars = array(
            'fields_value' => $this->getConfigFieldsValues(),
            'languages' => $this->context->controller->getLanguages(),
            'id_language' => $this->context->language->id
        );

        return $helper->generateForm(array($fields_form));
    }

    public function getConfigFieldsValues()
    {
        return array(
            'CULQI_LLAVE_SECRETA' => Tools::getValue('CULQI_LLAVE_SECRETA', Configuration::get('CULQI_LLAVE_SECRETA')),
            'CULQI_LLAVE_PUBLICA' => Tools::getValue('CULQI_LLAVE_PUBLICA', Configuration::get('CULQI_LLAVE_PUBLICA'))
        );
    }

    private function _postProcess()
    {
        if (Tools::isSubmit('btnSubmit'))
        {
            Configuration::updateValue('CULQI_LLAVE_SECRETA', Tools::getValue('CULQI_LLAVE_SECRETA'));
            Configuration::updateValue('CULQI_LLAVE_PUBLICA', Tools::getValue('CULQI_LLAVE_PUBLICA'));
        }
        $this->_html .= $this->displayConfirmation($this->l('Se actualizaron las configuraciones'));
    }

    public function removeComma($amount) {
        return str_replace(".","",str_replace(',', '', number_format($amount,2,'.',',')));
    }

    // Display Header Hook Execute Functions
	public function hookdisplayheader($params) {
        $this->context->controller->addCSS($this->_path.'views/css/waitMe.min.css');
      /*  $this->context->controller->addCSS($this->_path.'views/css/culqi.css');*/
        $this->context->controller->addJS($this->_path.'views/js/waitMe.min.js');
     }

  }

class CulqiPago
{
    public static $llaveSecreta;
    public static $codigoComercio;
}


text:
package com.asakusafw.utils.java.jsr269.bridge;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.io.IOError;
import java.io.IOException;

import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;

/**
 * Call back from {@link DelegateProcessor}.
 */
public abstract class Callback {

    private RuntimeException runtimeException;

    private Error error;

    /**
     * The processing environment.
     */
    protected ProcessingEnvironment env;

    /**
     * The type environment.
     */
    protected Types types;

    /**
     * The element utilities.
     */
    protected Elements elements;

    /**
     * The current rounding environment.
     */
    protected RoundEnvironment round;

    /**
     * Runs {@link #test()} method.
     * @param env processing environment
     * @param round rounding environment
     */
    @SuppressWarnings("hiding")
    public void run(ProcessingEnvironment env, RoundEnvironment round) {
        this.env = env;
        this.round = round;
        this.types = env.getTypeUtils();
        this.elements = env.getElementUtils();
        try {
            test();
        } catch (IOException e) {
            this.error = new IOError(e);
        } catch (RuntimeException e) {
            this.runtimeException = e;
        } catch (Error e) {
            this.error = e;
        }
    }

    /**
     * Throws exceptions/errors which are thrown in {@link #test()}.
     */
    public void rethrow() {
        if (runtimeException != null) {
            throw runtimeException;
        } else if (error != null) {
            throw error;
        }
    }

    /**
     * Performs the test.
     * @throws IOException if compilation was failed
     */
    protected abstract void test() throws IOException;

    /**
     * Returns the type mirror.
     * @param aClass target raw type
     * @param arguments type arguments
     * @return the declared type
     */
    protected TypeMirror getType(Class<?> aClass, TypeMirror...arguments) {
        TypeElement type = elements.getTypeElement(aClass.getName());
        assertThat(aClass.getName(), type, not(nullValue()));
        if (arguments.length == 0) {
            return types.erasure(type.asType());
        } else {
            return types.getDeclaredType(type, arguments);
        }
    }
}


text:
package com.zavakid.learn.parser.intermediate;

public interface ICode {

}


text:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Samples.Debugging.CorDebug;
using Microsoft.Samples.Debugging.CorDebug.Utility;
using System.Runtime.InteropServices;
using System.IO;
using Microsoft.Samples.Debugging.Native;

namespace Microsoft.Samples.Debugging.MdbgEngine
{
    /// <summary>
    /// A simple ICLRDebuggingLibraryProvider implementation that scans all
    /// the installed runtime directories looking for a matching file
    /// </summary>
    public class LibraryProvider : ICLRDebuggingLibraryProvider
    {
        public int ProvideLibrary(string fileName, int timestamp, int sizeOfImage, out IntPtr hModule)
        {
            CLRMetaHost mh = new CLRMetaHost();
            foreach (CLRRuntimeInfo rti in mh.EnumerateInstalledRuntimes())
            {
                string libPath = Path.Combine(rti.GetRuntimeDirectory(), fileName);
                if (DoesFileMatch(libPath, timestamp, sizeOfImage))
                {
                    hModule = LoadLibrary(libPath);
                    if (hModule != IntPtr.Zero)
                    {
                        UpdateLastLoaded(fileName, libPath);
                        return 0;
                    }
                    else
                    {
                        return -1;
                    }
                }
            }

            // not found
            hModule = IntPtr.Zero;
            return -1;
        }

        const string s_kernel = "kernel32";
        [DllImport(s_kernel, CharSet = CharSet.Auto, BestFitMapping = false, SetLastError = true)]
        private static extern IntPtr LoadLibrary(string fileName);

        /// <summary>
        /// Determines if the file at the given path matches the timestamp and sizeOfImage values
        /// </summary>
        /// <param name="filePath">the file to check</param>
        /// <param name="timestamp">the PE timestamp value to verifiy</param>
        /// <param name="sizeOfImage">the PE sizeOfImage value to verify</param>
        /// <returns>true if the file is a match and false otherwise</returns>
        bool DoesFileMatch(string filePath, int timestamp, int sizeOfImage)
        {
            try
            {
                // quick check to avoid exception handling for a common error
                // this check is not required for correctness
                if (!File.Exists(filePath))
                    return false;

                using (FileStream fs = File.OpenRead(filePath))
                {
                    PEReader peReader = new PEReader(fs);
                    return peReader.SizeOfImage == sizeOfImage &&
                        peReader.TimeStamp == timestamp;
                }
            }
            catch (IOException)
            {
                return false;
            }
        }

        public string LastLoadedDbi
        {
            get { return m_lastDbi;}
        }

        public string LastLoadedDac
        {
            get { return m_lastDac; }
        }

        private void UpdateLastLoaded(string fileName, string libPath)
        {
            if (String.Compare(fileName, "mscordacwks.dll", true) == 0)
            {
                m_lastDac = libPath;
            }
            else if (String.Compare(fileName, "mscordbi.dll", true) == 0)
            {
                m_lastDbi = libPath;
            }
        }

        private string m_lastDbi;
        private string m_lastDac;
    }
}


text:
package com.learning.japstu.japstu.objects;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.learning.japstu.japstu.services.APIService;

import java.util.ArrayList;

public class Exercise extends CourseLearning{

    public ArrayList<Question> lQuestion;
    public class Question{
        public String mQuestionContent = "";
        public String mQuestionType = "";
        public String mAnswerType = "";
        public int iMark = 0;
        public int iCountDownTime = 0;
        public boolean[] bResult;
        public String[] sAnswersContent;
        public Question(String questionType, String answerType, String questionContent, int mark, int countdown,
                        String answer1, String answer2, String answer3, String answer4, String answer5,
                        String result){

            mQuestionContent = questionContent;
            mQuestionType = questionType;
            mAnswerType = answerType;
            iMark = mark;
            iCountDownTime = countdown;
            char[] chrArray = result.toCharArray();
            bResult = new boolean[chrArray.length];
            for(int i = 0; i < chrArray.length; i++){
                bResult[i] =  (chrArray[i] == '1');
            }
            sAnswersContent = new String[5];
            sAnswersContent[0] = answer1;
            sAnswersContent[1] = answer2;
            sAnswersContent[2] = answer3;
            sAnswersContent[3] = answer4;
            sAnswersContent[4] = answer5;
        }
    }
    public boolean bIsTest = false;

    public Exercise(long lessonID){super(lessonID);}
    public Exercise(long lessonID, boolean isTest){
        bIsTest = isTest;
        lLessonID = lessonID;
        queryContent();
    }

    private boolean hasErrorOccured = false;
    private String err = "";
    private String errMsg = "";
    public boolean queryContent(){
        if(!bIsTest)
            content = APIService.searchExercise(lLessonID);
        else
            content = APIService.createTest(lLessonID, new Long(5), new Long(5),
                    new Long(5), new Long(5), new Long(5),
                    new Long(5));
        if(content.isJsonArray()) {
            lQuestion = new ArrayList<Question>(0);
            if( fillData()) {
                hasErrorOccured = true;
                return true;
            }
        }
        hasErrorOccured = false;
        return false;
    }

    public boolean fillData(){
        JsonArray arr  = content.getAsJsonArray();
        for(int i = 0; i < arr.size(); i++){
            JsonObject input = arr.get(i).getAsJsonObject();
            if(valiadateQuestionContent(input)){
                Question quest = new Question(input.get("questionType").getAsString(),
                                              input.get("answerType").getAsString(),
                                              input.get("questionContent").getAsString(),
                                              input.get("mark").getAsInt(),
                                              input.get("time").getAsInt(),
                                              input.get("answer1").getAsString(),
                                              input.get("answer2").getAsString(),
                                              input.get("answer3").getAsString(),
                                              input.get("answer4").getAsString(),
                                              input.get("answer5").getAsString(),
                                              input.get("answerChoose").getAsString());
                lQuestion.add(quest);
            }
        }
        return true;
    }

    public boolean valiadateQuestionContent(JsonObject input){
        boolean result = true;
        result &= (input.has("questionType") &
                  input.has("answerType") &
                  input.has("questionContent") &
                  input.has("mark") &
                  input.has("time") &
                  input.has("answer1") &
                  input.has("answer2") &
                  input.has("answer3") &
                  input.has("answer4") &
                  input.has("answer5") &
                  input.has("answerChoose"));
        if(result){
            result &= (input.get("mark").getAsDouble() > 0);
            result &= (input.get("time").getAsInt() > 0);
            result &= (input.get("answerChoose").getAsString().toCharArray().length == 5);
        }
        return result;
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--BSD License (2 clause-->
<!--Copyright (c) 2006 - 2016, Stephan Pfab-->
<!--All rights reserved.-->

<!--Redistribution and use in source and binary forms, with or without-->
<!--modification, are permitted provided that the following conditions are met:-->
<!--Redistributions of source code must retain the above copyright-->
<!--notice, this list of conditions and the following disclaimer.-->
<!--Redistributions in binary form must reproduce the above copyright-->
<!--notice, this list of conditions and the following disclaimer in the-->
<!--documentation and/or other materials provided with the distribution.-->

<!--THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND-->
<!--ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED-->
<!--WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE-->
<!--DISCLAIMED. IN NO EVENT SHALL Stephan Pfab BE LIABLE FOR ANY-->
<!--DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAM  AGES-->
<!--(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;-->
<!--LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND-->
<!--ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT-->
<!--(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS-->
<!--SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>de.pfabulist</groupId>
        <artifactId>opencage-checks-parent</artifactId>
        <version>3.2</version>
        <relativePath>../opencage-checks-parent/pom.xml</relativePath>
    </parent>

    <groupId>de.pfabulist.lindwurm</groupId>
    <artifactId>niodav</artifactId>
    <version>0.4.5</version>

    <name>niodav</name>
    <description>A webdav server based on any Java 7 filesystem</description>
    <url>http://www.github.com/openCage/niodav</url>

    <licenses>
        <license>
            <name>The BSD 2-Clause License</name>
            <url>http://opensource.org/licenses/BSD-2-Clause</url>
        </license>
    </licenses>

    <developers>
        <developer>
            <name>Stephan Pfab</name>
            <email>openCage@gmail.com</email>
            <organization>pfabulist</organization>
            <organizationUrl>http://www.pfabulist.de</organizationUrl>
        </developer>
    </developers>

    <scm>
        <url>git://git@github.com:openCage/niodav.git</url>
        <connection>scm:git:git@github.com:openCage/niodav</connection>
        <developerConnection>scm:git:git@github.com:openCage/niodav.git</developerConnection>
    </scm>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>commons-codec</groupId>
                <artifactId>commons-codec</artifactId>
                <version>1.2</version>
            </dependency>

        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-webapp</artifactId>
            <!--<version>9.2.0.M0</version>-->
            <version>9.3.6.v20151106</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.jackrabbit</groupId>
            <artifactId>jackrabbit-webdav</artifactId>
            <!--<version>2.10.0</version>-->
            <version>2.11.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.jackrabbit</groupId>
            <artifactId>jackrabbit-jcr-server</artifactId>
            <version>2.11.3</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>de.pfabulist</groupId>
            <artifactId>kleinod</artifactId>
            <version>0.33</version>
        </dependency>

        <dependency>
            <groupId>com.github.lookfirst</groupId>
            <artifactId>sardine</artifactId>
            <!--<version>5.4</version>-->
            <version>5.6</version>
            <scope>test</scope>
        </dependency>

        <dependency>
                <groupId>de.pfabulist.lindwurm</groupId>
            <artifactId>memoryfs</artifactId>
            <version>0.33</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>de.pfabulist.lindwurm</groupId>
            <artifactId>niotest</artifactId>
            <version>0.33</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.google.jimfs</groupId>
            <artifactId>jimfs</artifactId>
            <version>1.1</version>
            <scope>test</scope>
        </dependency>

    </dependencies>
</project>


text:
//
//  KBADependencyInjector.m
//  Kiba
//
//  Created by Markus Fasselt on 19.11.13.
//  Copyright (c) 2013 KiBa App. All rights reserved.
//

#import "KBADependencyInjector.h"

static NSMutableDictionary* dependencies;

@implementation KBADependencyInjector

+ (void) initialize {
    dependencies = [NSMutableDictionary new];
}

/**
 * get the registered dependency for {key}.
 *
 */
+ (id) getByKey:(NSString *)key {
    id dependency = [dependencies valueForKey: key];
    NSAssert(dependency != nil, @"Requested dependency is not set");
    return dependency;
}

/**
 * save an dependency with key {key}
 *
 */
+ (void) setObject:(id)object withKey:(NSString*)key {
    [dependencies setValue:object forKey:key];
}

/**
 *  Return true, if a dependency exists.
 *
 *  @param key The key of the dependecy
 *
 *  @return true if exists
 */
+ (BOOL)hasDependency:(NSString *)key {
    return [dependencies objectForKey:key] != nil;
}

@end


text:
/**
 * \file opt_algebraic.cpp
 *
 * Takes advantage of association, commutivity, and other algebraic
 * properties to simplify expressions.
 */

#include "ir.h"
#include "ir_visitor.h"
#include "ir_rvalue_visitor.h"
#include "ir_optimization.h"
#include "glsl_types.h"

namespace {

/**
 * Visitor class for replacing expressions with ir_constant values.
 */

class ir_algebraic_visitor : public ir_rvalue_visitor {
public:
   ir_algebraic_visitor()
   {
      this->progress = false;
      this->mem_ctx = NULL;
   }

   virtual ~ir_algebraic_visitor()
   {
   }

   ir_rvalue *handle_expression(ir_expression *ir);
   void handle_rvalue(ir_rvalue **rvalue);
   bool reassociate_constant(ir_expression *ir1,
			     int const_index,
			     ir_constant *constant,
			     ir_expression *ir2);
   void reassociate_operands(ir_expression *ir1,
			     int op1,
			     ir_expression *ir2,
			     int op2);
   ir_rvalue *swizzle_if_required(ir_expression *expr,
				  ir_rvalue *operand);

   void *mem_ctx;

   bool progress;
};

} /* unnamed namespace */

static inline bool
is_vec_zero(ir_constant *ir)
{
   return (ir == NULL) ? false : ir->is_zero();
}

static inline bool
is_vec_one(ir_constant *ir)
{
   return (ir == NULL) ? false : ir->is_one();
}

static inline bool
is_vec_basis(ir_constant *ir)
{
   return (ir == NULL) ? false : ir->is_basis();
}

static void
update_type(ir_expression *ir)
{
   if (ir->operands[0]->type->is_vector())
   {
      ir->type = ir->operands[0]->type;
	  ir->set_precision (ir->operands[0]->get_precision());
   }
   else
   {
      ir->type = ir->operands[1]->type;
	  ir->set_precision (ir->operands[1]->get_precision());
   }
}

void
ir_algebraic_visitor::reassociate_operands(ir_expression *ir1,
					   int op1,
					   ir_expression *ir2,
					   int op2)
{
   ir_rvalue *temp = ir2->operands[op2];
   ir2->operands[op2] = ir1->operands[op1];
   ir1->operands[op1] = temp;

   /* Update the type of ir2.  The type of ir1 won't have changed --
    * base types matched, and at least one of the operands of the 2
    * binops is still a vector if any of them were.
    */
   update_type(ir2);

   this->progress = true;
}

/**
 * Reassociates a constant down a tree of adds or multiplies.
 *
 * Consider (2 * (a * (b * 0.5))).  We want to send up with a * b.
 */
bool
ir_algebraic_visitor::reassociate_constant(ir_expression *ir1, int const_index,
					   ir_constant *constant,
					   ir_expression *ir2)
{
   if (!ir2 || ir1->operation != ir2->operation)
      return false;

   /* Don't want to even think about matrices. */
   if (ir1->operands[0]->type->is_matrix() ||
       ir1->operands[1]->type->is_matrix() ||
       ir2->operands[0]->type->is_matrix() ||
       ir2->operands[1]->type->is_matrix())
      return false;

   ir_constant *ir2_const[2];
   ir2_const[0] = ir2->operands[0]->constant_expression_value();
   ir2_const[1] = ir2->operands[1]->constant_expression_value();

   if (ir2_const[0] && ir2_const[1])
      return false;

   if (ir2_const[0]) {
      reassociate_operands(ir1, const_index, ir2, 1);
      return true;
   } else if (ir2_const[1]) {
      reassociate_operands(ir1, const_index, ir2, 0);
      return true;
   }

   if (reassociate_constant(ir1, const_index, constant,
			    ir2->operands[0]->as_expression())) {
      update_type(ir2);
      return true;
   }

   if (reassociate_constant(ir1, const_index, constant,
			    ir2->operands[1]->as_expression())) {
      update_type(ir2);
      return true;
   }

   return false;
}

/* When eliminating an expression and just returning one of its operands,
 * we may need to swizzle that operand out to a vector if the expression was
 * vector type.
 */
ir_rvalue *
ir_algebraic_visitor::swizzle_if_required(ir_expression *expr,
					  ir_rvalue *operand)
{
   if (expr->type->is_vector() && operand->type->is_scalar()) {
      return new(mem_ctx) ir_swizzle(operand, 0, 0, 0, 0,
				     expr->type->vector_elements);
   } else
      return operand;
}

ir_rvalue *
ir_algebraic_visitor::handle_expression(ir_expression *ir)
{
   ir_constant *op_const[3] = {NULL, NULL, NULL};
   ir_expression *op_expr[3] = {NULL, NULL, NULL};
   ir_expression *temp;
   unsigned int i;

   assert(ir->get_num_operands() <= 3);
   for (i = 0; i < ir->get_num_operands(); i++) {
      if (ir->operands[i]->type->is_matrix())
	 return ir;

      op_const[i] = ir->operands[i]->constant_expression_value();
      op_expr[i] = ir->operands[i]->as_expression();
   }

   if (this->mem_ctx == NULL)
      this->mem_ctx = ralloc_parent(ir);

   switch (ir->operation) {
   case ir_unop_logic_not: {
      enum ir_expression_operation new_op = ir_unop_logic_not;

      if (op_expr[0] == NULL)
	 break;

      switch (op_expr[0]->operation) {
      case ir_binop_less:    new_op = ir_binop_gequal;  break;
      case ir_binop_greater: new_op = ir_binop_lequal;  break;
      case ir_binop_lequal:  new_op = ir_binop_greater; break;
      case ir_binop_gequal:  new_op = ir_binop_less;    break;
      case ir_binop_equal:   new_op = ir_binop_nequal;  break;
      case ir_binop_nequal:  new_op = ir_binop_equal;   break;
      case ir_binop_all_equal:   new_op = ir_binop_any_nequal;  break;
      case ir_binop_any_nequal:  new_op = ir_binop_all_equal;   break;

      default:
	 /* The default case handler is here to silence a warning from GCC.
	  */
	 break;
      }

      if (new_op != ir_unop_logic_not) {
	 this->progress = true;
	 return new(mem_ctx) ir_expression(new_op,
					   ir->type,
					   op_expr[0]->operands[0],
					   op_expr[0]->operands[1]);
      }

      break;
   }

	case ir_unop_neg: {
		if (op_expr[0] && op_expr[0]->operation == ir_binop_sub) {
			// -(A-B) => (B-A)
			this->progress = true;
			return new(mem_ctx) ir_expression(ir_binop_sub,
											  ir->type,
											  op_expr[0]->operands[1],
											  op_expr[0]->operands[0]);
		}
		break;
	}

   case ir_binop_add:
      if (is_vec_zero(op_const[0])) {
	 this->progress = true;
	 return swizzle_if_required(ir, ir->operands[1]);
      }
      if (is_vec_zero(op_const[1])) {
	 this->progress = true;
	 return swizzle_if_required(ir, ir->operands[0]);
      }

      /* Reassociate addition of constants so that we can do constant
       * folding.
       */
      if (op_const[0] && !op_const[1])
	 reassociate_constant(ir, 0, op_const[0],
			      ir->operands[1]->as_expression());
      if (op_const[1] && !op_const[0])
	 reassociate_constant(ir, 1, op_const[1],
			      ir->operands[0]->as_expression());
      break;

   case ir_binop_sub:
      if (is_vec_zero(op_const[0])) {
	 this->progress = true;
	 temp = new(mem_ctx) ir_expression(ir_unop_neg,
					   ir->operands[1]->type,
					   ir->operands[1],
					   NULL);
	 return swizzle_if_required(ir, temp);
      }
      if (is_vec_zero(op_const[1])) {
	 this->progress = true;
	 return swizzle_if_required(ir, ir->operands[0]);
      }
      break;

   case ir_binop_mul:
      if (is_vec_one(op_const[0])) {
	 this->progress = true;
	 return swizzle_if_required(ir, ir->operands[1]);
      }
      if (is_vec_one(op_const[1])) {
	 this->progress = true;
	 return swizzle_if_required(ir, ir->operands[0]);
      }

      if (is_vec_zero(op_const[0]) || is_vec_zero(op_const[1])) {
	 this->progress = true;
	 return ir_constant::zero(ir, ir->type);
      }

      /* Reassociate multiplication of constants so that we can do
       * constant folding.
       */
      if (op_const[0] && !op_const[1])
	 reassociate_constant(ir, 0, op_const[0],
			      ir->operands[1]->as_expression());
      if (op_const[1] && !op_const[0])
	 reassociate_constant(ir, 1, op_const[1],
			      ir->operands[0]->as_expression());

      break;

   case ir_binop_div:
      if (is_vec_one(op_const[0]) && ir->type->base_type == GLSL_TYPE_FLOAT) {
	 this->progress = true;
	 temp = new(mem_ctx) ir_expression(ir_unop_rcp,
					   ir->operands[1]->type,
					   ir->operands[1],
					   NULL);
	 return swizzle_if_required(ir, temp);
      }
      if (is_vec_one(op_const[1])) {
	 this->progress = true;
	 return swizzle_if_required(ir, ir->operands[0]);
      }
      break;

   case ir_binop_dot:
      if (is_vec_zero(op_const[0]) || is_vec_zero(op_const[1])) {
	 this->progress = true;
	 return ir_constant::zero(mem_ctx, ir->type);
      }
      if (is_vec_basis(op_const[0])) {
	 this->progress = true;
	 unsigned component = 0;
	 for (unsigned c = 0; c < op_const[0]->type->vector_elements; c++) {
	    if (op_const[0]->value.f[c] == 1.0)
	       component = c;
	 }
	 return new(mem_ctx) ir_swizzle(ir->operands[1], component, 0, 0, 0, 1);
      }
      if (is_vec_basis(op_const[1])) {
	 this->progress = true;
	 unsigned component = 0;
	 for (unsigned c = 0; c < op_const[1]->type->vector_elements; c++) {
	    if (op_const[1]->value.f[c] == 1.0)
	       component = c;
	 }
	 return new(mem_ctx) ir_swizzle(ir->operands[0], component, 0, 0, 0, 1);
      }
      break;

   case ir_binop_logic_and:
      /* FINISHME: Also simplify (a && a) to (a). */
      if (is_vec_one(op_const[0])) {
	 this->progress = true;
	 return ir->operands[1];
      } else if (is_vec_one(op_const[1])) {
	 this->progress = true;
	 return ir->operands[0];
      } else if (is_vec_zero(op_const[0]) || is_vec_zero(op_const[1])) {
	 this->progress = true;
	 return ir_constant::zero(mem_ctx, ir->type);
      }
      break;

   case ir_binop_logic_xor:
      /* FINISHME: Also simplify (a ^^ a) to (false). */
      if (is_vec_zero(op_const[0])) {
	 this->progress = true;
	 return ir->operands[1];
      } else if (is_vec_zero(op_const[1])) {
	 this->progress = true;
	 return ir->operands[0];
      } else if (is_vec_one(op_const[0])) {
	 this->progress = true;
	 return new(mem_ctx) ir_expression(ir_unop_logic_not, ir->type,
					   ir->operands[1], NULL);
      } else if (is_vec_one(op_const[1])) {
	 this->progress = true;
	 return new(mem_ctx) ir_expression(ir_unop_logic_not, ir->type,
					   ir->operands[0], NULL);
      }
      break;

   case ir_binop_logic_or:
      /* FINISHME: Also simplify (a || a) to (a). */
      if (is_vec_zero(op_const[0])) {
	 this->progress = true;
	 return ir->operands[1];
      } else if (is_vec_zero(op_const[1])) {
	 this->progress = true;
	 return ir->operands[0];
      } else if (is_vec_one(op_const[0]) || is_vec_one(op_const[1])) {
	 ir_constant_data data;

	 for (unsigned i = 0; i < 16; i++)
	    data.b[i] = true;

	 this->progress = true;
	 return new(mem_ctx) ir_constant(ir->type, &data);
      }
      break;

   case ir_unop_rcp:
      if (op_expr[0] && op_expr[0]->operation == ir_unop_rcp) {
	 this->progress = true;
	 return op_expr[0]->operands[0];
      }

      /* FINISHME: We should do rcp(rsq(x)) -> sqrt(x) for some
       * backends, except that some backends will have done sqrt ->
       * rcp(rsq(x)) and we don't want to undo it for them.
       */

      /* As far as we know, all backends are OK with rsq. */
      if (op_expr[0] && op_expr[0]->operation == ir_unop_sqrt) {
	 this->progress = true;
	 temp = new(mem_ctx) ir_expression(ir_unop_rsq,
					   op_expr[0]->operands[0]->type,
					   op_expr[0]->operands[0],
					   NULL);
	 return swizzle_if_required(ir, temp);
      }

      break;

   case ir_triop_lrp:
      /* Operands are (x, y, a). */
      if (is_vec_zero(op_const[2])) {
         this->progress = true;
         return swizzle_if_required(ir, ir->operands[0]);
      } else if (is_vec_one(op_const[2])) {
         this->progress = true;
         return swizzle_if_required(ir, ir->operands[1]);
      }
      break;

   default:
      break;
   }

   return ir;
}

void
ir_algebraic_visitor::handle_rvalue(ir_rvalue **rvalue)
{
   if (!*rvalue)
      return;

   ir_expression *expr = (*rvalue)->as_expression();
   if (!expr || expr->operation == ir_quadop_vector)
      return;

   *rvalue = handle_expression(expr);
}

bool
do_algebraic(exec_list *instructions)
{
   ir_algebraic_visitor v;

   visit_list_elements(&v, instructions);

   return v.progress;
}


text:
/*
 * Powered By [柳丰]
 * Web Site: http://www.trend.com.cn
 */

package com.trend.hbny.model;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import javax.persistence.*;

import java.util.*;

import javacommon.base.*;
import javacommon.util.*;

import cn.org.rapid_framework.util.*;
import cn.org.rapid_framework.web.util.*;
import cn.org.rapid_framework.page.*;
import cn.org.rapid_framework.page.impl.*;

import com.trend.hbny.model.*;
import com.trend.hbny.dao.*;
import com.trend.hbny.service.*;

/**
 * @author neolf  email:neolf(a)foxmail.com
 * @version 1.0
 * @since 1.0
 */

public class SHbnyRResource extends BaseEntity {

	//alias
	public static final String TABLE_ALIAS = "SHbnyRResource";
	public static final String ALIAS_RESOURCE_ID = "resourceId";
	public static final String ALIAS_RID = "rid";
	public static final String ALIAS_RESOURCE_STR = "resourceStr";
	public static final String ALIAS_CONO = "cono";
	public static final String ALIAS_ID = "id";

	//date formats

	//columns START
	private Long resourceId;
	private Long rid;
	private String resourceStr;
	private String cono;
	private Long id;
	//columns END

	//注意: spring_jdbc的MetadataCreateUtils.fromTable(Entity.class) 可以读取JPA annotation的标注信息
	//现支持 @Id,@Column,@Table标注

	public SHbnyRResource(){
	}

	public SHbnyRResource(
		java.lang.Long id
	){
		this.id = id;
	}

	public java.lang.Long getResourceId() {
		return this.resourceId;
	}

	public void setResourceId(java.lang.Long value) {
		this.resourceId = value;
	}

	public java.lang.Long getRid() {
		return this.rid;
	}

	public void setRid(java.lang.Long value) {
		this.rid = value;
	}

	public java.lang.String getResourceStr() {
		return this.resourceStr;
	}

	public void setResourceStr(java.lang.String value) {
		this.resourceStr = value;
	}

	public java.lang.String getCono() {
		return this.cono;
	}

	public void setCono(java.lang.String value) {
		this.cono = value;
	}

	@Id
	public java.lang.Long getId() {
		return this.id;
	}

	public void setId(java.lang.Long value) {
		this.id = value;
	}

	public String toString() {
		return new ToStringBuilder(this)
			.append("ResourceId",getResourceId())
			.append("Rid",getRid())
			.append("ResourceStr",getResourceStr())
			.append("Cono",getCono())
			.append("Id",getId())
			.toString();
	}

	public int hashCode() {
		return new HashCodeBuilder()
			.append(getResourceId())
			.append(getRid())
			.append(getResourceStr())
			.append(getCono())
			.append(getId())
			.toHashCode();
	}

	public boolean equals(Object obj) {
		if(obj instanceof SHbnyRResource == false) return false;
		if(this == obj) return true;
		SHbnyRResource other = (SHbnyRResource)obj;
		return new EqualsBuilder()
			.append(getResourceId(),other.getResourceId())
			.append(getRid(),other.getRid())
			.append(getResourceStr(),other.getResourceStr())
			.append(getCono(),other.getCono())
			.append(getId(),other.getId())
			.isEquals();
	}
}