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

namespace CSharpExercises
{
    public struct GridDetails
    {
        public int[] GridTempValues;
        public int[] GridValues;
        public long Product;
        public string Direction;
        public string[] GridIndexes;
        public string[] GridTempIndexes;
    }

    public class IntegerExercises
    {
        #region Helper Methods
        static void AlterGridDetails(ref GridDetails gridDetails, int adjacentNumbers, ref long product, long tempProduct, string direction)
        {
            product = tempProduct;
            Array.Copy(gridDetails.GridTempIndexes, gridDetails.GridIndexes, adjacentNumbers);
            Array.Copy(gridDetails.GridTempValues, gridDetails.GridValues, adjacentNumbers);
            gridDetails.Product = product;
            gridDetails.Direction = direction;
        }

        public static int[,] GenerateGrid()
        {
            Console.WriteLine("Enter a non-zero whole number.");
            int arrayLeftInit = 0;
            Int32.TryParse(Console.ReadLine(), out arrayLeftInit);

            Console.WriteLine("Enter a non-zero whole number.");
            int arrayRightInit = 0;
            Int32.TryParse(Console.ReadLine(), out arrayRightInit);
            if (arrayLeftInit == 0 || arrayRightInit == 0)
            {
                Console.WriteLine("For one or both inputs, you did not enter a number, you entered a zero, or you entered a number " +
                    "with a decimal.");
                Console.ReadKey();
                Environment.Exit(0);
            }
            int[,] grid = new int[arrayLeftInit, arrayRightInit];
            Random rand = new Random();
            for(int j = 0; j < arrayLeftInit; j++)
            {
                for(int k = 0; k < arrayRightInit; k++)
                {
                    grid[arrayLeftInit, arrayRightInit] = rand.Next(0, 99);
                }
            }
            return grid;
        }

        public static int GetIntegerInput()
        {
            Console.WriteLine("Enter a non-zero whole number.");
            int response = 0;
            Int32.TryParse(Console.ReadLine(), out response);
            if (response == 0)
            {
                Console.WriteLine("You did not enter a number, you entered a zero, or you entered a number " +
                    "with a decimal.");
                Console.ReadKey();
                Environment.Exit(0);
            }
            return response;
        }

        public static string GetIntegerStringInput()
        {
            Console.WriteLine("Enter a series of numbers.");
            string response = Console.ReadLine();

            return response;
        }

        public static int GetPositiveIntegerInput()
        {
            Console.WriteLine("Enter a non-zero positive whole number.");
            int response = 0;
            Int32.TryParse(Console.ReadLine(), out response);
            if (response <= 0)
            {
                Console.WriteLine("You did not enter a number, you entered a zero, you entered a negative number, you entered a number " +
                    "with a decimal, or you entered a number that exceeded the max possible value.");
                Console.ReadKey();
                Environment.Exit(0);
            }
            return response;
        }

        public static long GetPositiveLongInput()
        {
            Console.WriteLine("Enter a non-zero positive whole number.");
            long response = 0;
            long.TryParse(Console.ReadLine(), out response);
            if (response <= 0)
            {
                Console.WriteLine("You did not enter a number, you entered a zero, you entered a negative number, you entered a number " +
                    "with a decimal, or you entered a number that exceeded the max possible value.");
                Console.ReadKey();
                Environment.Exit(0);
            }
            return response;
        }

        public void ExecuteFunction()
        {
            Console.WriteLine("Enter an integer to choose which method to execute:\n1) FizzBuzz\n2) Get Factors Of Composite Number\n3) Find LCD Of Two Numbers" +
                "\n4) Prime Number Sieve\n5) Fibonacci Sequence\n6) Multiples of 3 and 5\n7) Even Fibonacci Numbers Sum\n8) Largest Prime Factor\n9) Largest Palindrome Product"+
                "\n10) Smallest Multiple\n11) Sum Square Difference\n12) Check If Number Is Composite\n13) Find N-Prime\n14) Largest Product In Series\n15) Find Pythagorean Triplet"+
                "\n16)Summation Of Primes\n17) Largest Product In A Grid\n18) Find Triangle Divisor");
            string key = Console.ReadLine();
            switch (key)
            {
                case "1":
                    {
                        FizzBuzz(GetIntegerInput());
                        break;
                    }
                case "2":
                    {
                        int input = GetIntegerInput();
                        List<int> numList = GetFactorsOfCompositeNumber(input);
                        if (numList.Count != 0)
                        {
                            Console.WriteLine(input + " is a composite number. Its factor(s) are " + string.Join(", ", numList) + ".");
                        }
                        else
                        {
                            Console.WriteLine(input + " is not a composite number.");
                        }
                        break;
                    }
                case "3":
                    {
                        int input1 = GetPositiveIntegerInput();
                        int input2 = GetPositiveIntegerInput();
                        int lcdNum = FindLeastCommonDenominator(input1, input2);
                        Console.WriteLine("The LCD of {0} and {1} is {2}.", input1, input2, lcdNum);
                        break;
                    }
                case "4":
                    {
                        int input = GetPositiveIntegerInput();
                        List<int> primeNumList = PrimeNumberSieve(input);
                        Console.WriteLine("The prime numbers from 1 to " + input + " are " + string.Join(", ", primeNumList) + ".");
                        break;
                    }
                case "5":
                    {
                        int input = GetPositiveIntegerInput();
                        List<int> sequence = FibonacciSequence(input);
                        Console.WriteLine("The Fibonacci sequence is " + string.Join(" ", sequence) + ".");
                        break;
                    }
                case "6":
                    {
                        int input = GetIntegerInput();
                        int sum = MultiplesOf3And5(input);
                        Console.WriteLine("The sum of the 3 and 5 multiples of " + input + " is " + sum + ".");
                        break;
                    }
                case "7":
                    {
                        int input = GetPositiveIntegerInput();
                        int sum = EvenFibonacciNumbersSum(input);
                        Console.WriteLine("The sum of the even numbers in the Fibonacci sequence is " + sum + ".");
                        break;
                    }
                case "8":
                    {
                        int input = GetPositiveIntegerInput();
                        int primeFactor = LargestPrimeFactor(input);
                        Console.WriteLine("The largest prime number of {0} is {1}.", input, primeFactor);
                        break;
                    }
                case "9":
                    {
                        Tuple<int, int, bool> tuple = LargestPalindromeProduct(GetPositiveIntegerInput(), GetPositiveIntegerInput());
                        if (tuple.Item3)
                        {
                            Console.WriteLine("The numbers {0} and {1} created the palindrome {2}.", tuple.Item1, tuple.Item2, tuple.Item1 * tuple.Item2);
                        }
                        else
                        {
                            Console.WriteLine("The inputted numbers did not create a palindrome.");
                        }
                        break;
                    }
                case "10":
                    {
                        int smallestMultiple = SmallestMultiple(GetPositiveIntegerInput());
                        if (smallestMultiple > 0)
                        {
                            Console.WriteLine("The smallest multiple is {0}.", smallestMultiple);
                        }
                        else
                        {
                            Console.WriteLine("There is no smallest multiple.");
                        }
                        break;
                    }
                case "11":
                    {
                        int input = GetPositiveIntegerInput();
                        long difference = SumSquareDifferences(input);
                        if (difference < 0)
                        {
                            Console.WriteLine("The number you entered exceeded the max possible value.");
                        }
                        else
                        {
                            Console.WriteLine("The difference computed from the input {0} is {1}.", input, difference);
                        }
                        break;
                    }
                case "12":
                    {
                        int input = GetIntegerInput();
                        bool isComposite = CheckIfNumberIsComposite(input);
                        if (isComposite)
                        {
                            Console.WriteLine("The number {0} is composite.", input);
                        }
                        else
                        {
                            Console.WriteLine("The number {0} is not composite.", input);
                        }
                        break;
                    }
                case "13":
                    {
                        int input = GetIntegerInput();
                        int primeNum = FindNPrime(input);
                        Console.WriteLine("The {0}st/th prime number is {1}.", input, primeNum);
                        break;
                    }
                case "14":
                    {
                        string numSeries = GetIntegerStringInput();
                        int numOfAdjacentDigits = GetPositiveIntegerInput();
                        long product = LargestProductInSeries(numSeries, numOfAdjacentDigits);
                        if (product < 0)
                        {
                            Console.WriteLine("Either the second number you entered is larger than the length of the series of numbers you entered or the "
                                + "product exceeded the max possible value.");
                        }
                        else
                        {
                            Console.WriteLine("The largest product in the series derived from {0} adjacent digits is {1}.", numOfAdjacentDigits, product);
                        }
                        break;
                    }
                case "15":
                    {
                        int input = GetPositiveIntegerInput();
                        var pythagoreanTriplet = FindPythagoreanTriplet(input);
                        if (pythagoreanTriplet.Item5)
                        {
                            Console.WriteLine("Your input produced the pythagorean triplet of a: {0}, b: {1}, and c: {2} with a product of {3}",
                                pythagoreanTriplet.Item1, pythagoreanTriplet.Item2, pythagoreanTriplet.Item3, pythagoreanTriplet.Item4);
                        }
                        else
                        {
                            Console.WriteLine("Your input did not produce a pythagorean triplet.");
                        }
                        break;
                    }
                case "16":
                    {
                        int input = GetPositiveIntegerInput();
                        long sum = SummationOfPrimes(input);
                        Console.WriteLine("The sum of the primes derived from the input {0} is {1}.", input, sum);
                        break;
                    }
                case "17":
                    {
                        int[,] grid = GenerateGrid();
                        int adjacentNumbers = GetPositiveIntegerInput();
                        GridDetails gridDetails = LargestProductInAGrid(grid, adjacentNumbers);
                        Console.WriteLine("The largest product in the grid is " + gridDetails.Product);
                        Console.WriteLine("The direction used to derive the largest product is " + gridDetails.Direction);
                        break;
                    }
                case "18":
                    {
                        int input = GetPositiveIntegerInput();
                        List<int> numList = FindTriangleDivisor(input);
                        Console.WriteLine("The value of the first number to have {0} or more divisors is {1}.",
                            input, numList[numList.Count - 1]);
                        Console.WriteLine("The number of divisors is {0}.", numList.Count);
                        break;
                    }
                default:
                    {
                        Console.WriteLine("You entered a number unassociated with the methods.");
                        break;
                    }
            }
        }
        #endregion

        public bool CheckIfNumberIsComposite(int input)
        {
            bool isComposite = false;
            if (input > 0)
            {
                for (int i = 2; i < (input / 2 + 1); i++)
                {
                    if (input % i == 0)
                    {
                        isComposite = true;
                        break;
                    }
                }
            }
            else
            {
                for (int i = -2; i > (input / 2 - 1); i--)
                {
                    if (input % i == 0)
                    {
                        isComposite = true;
                        break;
                    }
                }
            }
            return isComposite;
        }

        public int EvenFibonacciNumbersSum(int input)
        {
            int num1 = 0, num2 = 1, sum = 0, tempnum = 0;
            if (input == 1)
            {
                return 0;
            }
            if (input == 2)
            {
                return 1;
            }
            for (int i = 2; i < input; i++)
            {
                tempnum = num1 + num2;
                if (tempnum % 2 == 0)
                {
                    sum += tempnum;
                }
                num1 = num2;
                num2 = tempnum;
            }
            return sum;
        }

        public List<int> FibonacciSequence(int input)
        {
            int num1 = 0;
            int num2 = 1;
            int tempNum = 0;
            List<int> sequence = new List<int>();
            if (input == 1)
            {
                sequence.Add(num1);
                return sequence;
            }
            sequence.Add(num1);
            sequence.Add(num2);
            for (int i = 2; i < input; i++)
            {
                tempNum = num1 + num2;
                sequence.Add(tempNum);
                num1 = num2;
                num2 = tempNum;
            }
            return sequence;
        }

        public int FindLeastCommonDenominator(int input1, int input2)
        {
            int lcdInt = 0;
            if (input1 < input2)
            {
                for (lcdInt = input1; lcdInt < input1 * input2; lcdInt += input1)
                {
                    if (lcdInt % input1 == 0 && lcdInt % input2 == 0)
                    {
                        break;
                    }
                }
            }
            else
            {
                for (lcdInt = input2; lcdInt < input1 * input2; lcdInt += input2)
                {
                    if (lcdInt % input1 == 0 && lcdInt % input2 == 0)
                    {
                        break;
                    }
                }
            }
            return lcdInt;
        }

        public int FindNPrime(int input)
        {
            bool isComposite = false;
            int primeNum = 0, primeNumCounter = 0, incrementor = 2;
            while (primeNumCounter < input)
            {
                isComposite = CheckIfNumberIsComposite(incrementor);
                if (!isComposite)
                {
                    primeNum = incrementor;
                    primeNumCounter++;
                }
                incrementor++;
            }

            return primeNum;
        }

        public Tuple<int, int, int, int, bool> FindPythagoreanTriplet(int input)
        {
            bool isPerfectSquare = false;
            double square = 0;
            int aSide = 0, bSide = 1, cSide = 0, product = 0;
            for (aSide = 2; aSide + bSide + cSide <= input; aSide++)
            {
                for (bSide = aSide + 1; aSide + bSide + cSide <= input; bSide++)
                {
                    square = Math.Sqrt(aSide * aSide + bSide * bSide);
                    if ((int)Math.Ceiling(square) == (int)Math.Floor(square))
                    {
                        cSide = (int)square;

                        if (aSide + bSide + cSide == input)
                        {
                            product = aSide * bSide * cSide;
                            isPerfectSquare = true;
                            return Tuple.Create(aSide, bSide, cSide, product, isPerfectSquare);
                        }
                    }
                }
                bSide = aSide + 1;
            }

            return Tuple.Create(0, 0, 0, 0, isPerfectSquare);
        }

        //this runs very slowly for large inputs, implement a better algorithm in the future
        public List<int> FindTriangleDivisor(int input)
        {
            List<int> divisorList = new List<int>();

            if (input == 1)
            {
                divisorList.Add(1);
                return divisorList;
            }

            int iterator = 3;
            int triangleNum = 3;

            while (divisorList.Count < input)
            {
                divisorList.Clear();
                for (int divisor = 1; divisor < triangleNum / 2 + 1; divisor++)
                {
                    if (triangleNum % divisor == 0)
                    {
                        divisorList.Add(divisor);
                    }
                }
                divisorList.Add(triangleNum);
                triangleNum += iterator;
                iterator++;
            }

            return divisorList;
        }

        public void FizzBuzz(int input)
        {
            if (input > 0)
            {
                for (int i = 1; i <= input; i++)
                {
                    if (i % 5 == 0 && i % 3 == 0)
                    {
                        Console.WriteLine(i + ": FizzBuzz.");
                    }
                    else if (i % 5 == 0)
                    {
                        Console.WriteLine(i + ": Fizz.");
                    }
                    else if (i % 3 == 0)
                    {
                        Console.WriteLine(i + ": Buzz.");
                    }
                }
            }
            else
            {
                for (int i = -1; i >= input; i--)
                {
                    if (i % 5 == 0 && i % 3 == 0)
                    {
                        Console.WriteLine(i + ": FizzBuzz.");
                    }
                    else if (i % 5 == 0)
                    {
                        Console.WriteLine(i + ": Fizz.");
                    }
                    else if (i % 3 == 0)
                    {
                        Console.WriteLine(i + ": Buzz.");
                    }
                }
            }
        }

        public List<int> GetFactorsOfCompositeNumber(int input)
        {
            List<int> numList = new List<int>();
            if (input > 0)
            {
                for (int i = 2; i < (input / 2 + 1); i++)
                {
                    if (input % i == 0)
                    {
                        numList.Add(i);
                    }
                }
            }
            else
            {
                for (int i = -2; i > (input / 2 - 1); i--)
                {
                    if (input % i == 0)
                    {
                        numList.Add(i);
                    }
                }
            }
            return numList;
        }

        public Tuple<int, int, bool> LargestPalindromeProduct(int input1, int input2)
        {
            bool isPalindrome = false;
            int num1 = 0;
            int num2 = 0;
            string str = "";
            StringExercises strExercises = new StringExercises();

            for (num1 = input1; num1 > 0; num1--)
            {
                for (num2 = input2; num2 > 0; num2--)
                {
                    str = (num1 * num2).ToString();
                    isPalindrome = strExercises.CheckIsPalindrome(str);
                    if (isPalindrome)
                    {
                        return Tuple.Create(num1, num2, isPalindrome);
                    }
                }
            }

            return Tuple.Create(0, 0, isPalindrome);
        }

        public int LargestPrimeFactor(int input)
        {
            int primeFactor = 0;
            if (input.Equals(1))
            {
                return 1;
            }
            bool isPrime = false;
            for (int i = input/2; i > 0; i--)
            {
                isPrime = true;
                if (input % i == 0)
                {
                    for (int j = 2; j < i/2; j++)
                    {
                        if (i % j == 0)
                        {
                            isPrime = false;
                            break;
                        }
                    }
                    if (isPrime == true)
                    {
                        primeFactor = i;
                        break;
                    }
                }
            }
            return primeFactor;
        }

        public GridDetails LargestProductInAGrid(int[,] grid, int adjacentNumbers)
        {
            int arrayLeftLength = grid.GetLength(0);
            int arrayRightLength = grid.GetLength(1);
            if (adjacentNumbers > arrayLeftLength && adjacentNumbers > arrayRightLength)
            {
                Console.WriteLine("The adjacent number is greater than the bounds of the array.");
                Environment.Exit(0);
            }

            long product = 0;
            long tempProduct = 1;

            GridDetails gridDetails = new GridDetails();
            if (arrayLeftLength == 1 && arrayRightLength == 1)
            {
                gridDetails.Direction = "None";
                gridDetails.Product = grid[0, 0];
                gridDetails.GridIndexes = new string[1];
                gridDetails.GridIndexes[0] = "[" + 0 + "," + 0 + "]";
                gridDetails.GridValues = new int[1];
                gridDetails.GridValues[0] = grid[0, 0];
                return gridDetails;
            }

            gridDetails.GridIndexes = new string[adjacentNumbers];
            gridDetails.GridTempValues = new int[adjacentNumbers];
            gridDetails.GridTempIndexes = new string[adjacentNumbers];
            gridDetails.GridValues = new int[adjacentNumbers];

            if (arrayRightLength > 1 && arrayRightLength > adjacentNumbers)
            {
                //left to right starting from top to bottom
                for (int leftIndex = 0; leftIndex < arrayLeftLength; leftIndex++)
                {
                    int tempRightLength = 0;
                    while (tempRightLength <= arrayRightLength - adjacentNumbers)
                    {
                        tempProduct = 1;
                        for (int rightIndex = tempRightLength, iterator = 0; iterator < adjacentNumbers; rightIndex++, iterator++)
                        {
                            tempProduct *= grid[leftIndex, rightIndex];
                            gridDetails.GridTempIndexes[iterator] = "[" + leftIndex + "," + rightIndex + "]";
                            gridDetails.GridTempValues[iterator] = grid[leftIndex, rightIndex];
                        }
                        if (tempProduct > product)
                        {
                            AlterGridDetails(ref gridDetails, adjacentNumbers, ref product, tempProduct, "Horizontal");
                        }
                        Array.Clear(gridDetails.GridTempIndexes, 0, gridDetails.GridTempIndexes.Length);
                        Array.Clear(gridDetails.GridTempValues, 0, gridDetails.GridTempValues.Length);
                        tempRightLength++;
                    }
                }
            }
            if (arrayLeftLength > 1 && arrayLeftLength > adjacentNumbers)
            {
                //top to bottom starting from left to right
                for (int rightIndex = 0; rightIndex < arrayRightLength; rightIndex++)
                {
                    int tempLeftLength = 0;
                    while (tempLeftLength <= arrayLeftLength - adjacentNumbers)
                    {
                        tempProduct = 1;
                        for (int leftIndex = tempLeftLength, iterator = 0; iterator < adjacentNumbers; leftIndex++, iterator++)
                        {
                            tempProduct *= grid[leftIndex, rightIndex];
                            gridDetails.GridTempIndexes[iterator] = "[" + leftIndex + "," + rightIndex + "]";
                            gridDetails.GridTempValues[iterator] = grid[leftIndex, rightIndex];
                        }
                        if (tempProduct > product)
                        {
                            AlterGridDetails(ref gridDetails, adjacentNumbers, ref product, tempProduct, "Vertical");
                        }
                        Array.Clear(gridDetails.GridTempIndexes, 0, gridDetails.GridTempIndexes.Length);
                        Array.Clear(gridDetails.GridTempValues, 0, gridDetails.GridTempValues.Length);
                        tempLeftLength++;
                    }
                }
            }
            if (arrayLeftLength > 1 && arrayRightLength > 1)
            {
                //diagonal left to right starting from top to bottom
                for (int leftIndex = 0; leftIndex <= arrayLeftLength - adjacentNumbers; leftIndex++)
                {
                    int tempRightindex = 0;
                    while (tempRightindex <= arrayRightLength - adjacentNumbers)
                    {
                        tempProduct = 1;
                        for (int rightIndex = tempRightindex, iterator = 0; iterator < adjacentNumbers; rightIndex++, iterator++)
                        {
                            tempProduct *= grid[leftIndex + iterator, rightIndex];
                            gridDetails.GridTempIndexes[iterator] = "[" + (leftIndex + iterator) + "," + rightIndex + "]";
                            gridDetails.GridTempValues[iterator] = grid[leftIndex + iterator, rightIndex];
                        }
                        if (tempProduct > product)
                        {
                            AlterGridDetails(ref gridDetails, adjacentNumbers, ref product, tempProduct, "Left-to-right diagonal");
                        }
                        Array.Clear(gridDetails.GridTempIndexes, 0, gridDetails.GridTempIndexes.Length);
                        Array.Clear(gridDetails.GridTempValues, 0, gridDetails.GridTempValues.Length);
                        tempRightindex++;
                    }
                }
                //diagonal right to left starting from top to bottom
                for (int leftIndex = 0; leftIndex <= arrayLeftLength - adjacentNumbers; leftIndex++)
                {
                    int tempRightIndex = arrayRightLength - 1;
                    while (tempRightIndex >= adjacentNumbers - 1)
                    {
                        tempProduct = 1;
                        for (int rightIndex = tempRightIndex, iterator = 0; iterator < adjacentNumbers; rightIndex--, iterator++)
                        {
                            tempProduct *= grid[leftIndex + iterator, rightIndex];
                            gridDetails.GridTempIndexes[iterator] = "[" + (leftIndex + iterator) + "," + rightIndex + "]";
                            gridDetails.GridTempValues[iterator] = grid[leftIndex + iterator, rightIndex];
                        }
                        if (tempProduct > product)
                        {
                            AlterGridDetails(ref gridDetails, adjacentNumbers, ref product, tempProduct, "Right-to-left diagonal");
                        }
                        Array.Clear(gridDetails.GridTempIndexes, 0, gridDetails.GridTempIndexes.Length);
                        Array.Clear(gridDetails.GridTempValues, 0, gridDetails.GridTempValues.Length);
                        tempRightIndex--;
                    }
                }
            }

            return gridDetails;
        }

        public long LargestProductInSeries(string numSeries, int numOfAdjacentDigits)
        {
            if (numOfAdjacentDigits > numSeries.Length)
            {
                return -1;
            }
            long product = 0, tempProduct = 0;
            int stringCount = numSeries.Length;
            int[] numArray = new int[stringCount];
            for (int i = 0; i < stringCount; i++)
            {
                numArray[i] = (int)Char.GetNumericValue(numSeries[i]);
            }
            for (int i = 0; i < stringCount - numOfAdjacentDigits + 1; i++)
            {
                tempProduct = 1;
                for (int j = 0; j < numOfAdjacentDigits; j++)
                {
                    tempProduct *= numArray[i + j];
                }
                if (tempProduct > product)
                {
                    product = tempProduct;
                }
            }
            return product;
        }

        public int MultiplesOf3And5(int input)
        {
            int sum = 0;
            if (input > 0)
            {
                for (int i = 3; i <= input; i++)
                {
                    if (i % 3 == 0 || i % 5 == 0)
                    {
                        sum += i;
                    }
                }
            }
            else
            {
                for (int i = -3; i >= input; i--)
                {
                    if (i % 3 == 0 || i % 5 == 0)
                    {
                        sum += i;
                    }
                }
            }
            return sum;
        }

        public List<int> PrimeNumberSieve(int input)
        {
            List<int> primeNumList = new List<int>();
            List<int> tempNumList = new List<int>();
            primeNumList = Enumerable.Range(1, input).ToList();
            foreach (int num in primeNumList.Skip(3))
            {
                for (int i = 2; i < Math.Sqrt(num) + 1; i++)
                {
                    if (num % i == 0)
                    {
                        tempNumList.Add(num);
                        break;
                    }
                }
            }
            primeNumList = primeNumList.Except(tempNumList).ToList();
            return primeNumList;
        }

        public int SmallestMultiple(int input)
        {
            bool isDivisible;
            int smallestMultiple = 0;
            for (int i = input; i < int.MaxValue; i++)
            {
                isDivisible = true;
                for (int j = input; j > 0; j--)
                {
                    if (i % j != 0)
                    {
                        isDivisible = false;
                        break;
                    }
                }
                if (isDivisible)
                {
                    smallestMultiple = i;
                    return smallestMultiple;
                }
            }
            return smallestMultiple;
        }

        //this runs very slowly for large inputs, implement a better algorithm in the future
        public long SummationOfPrimes(int input)
        {
            long sum = 0;
            for (int j = 2; j <= input; j++)
            {
                bool isComposite = CheckIfNumberIsComposite(j);
                if (!isComposite)
                {
                    sum += j;
                }
            }
            return sum;
        }

        public long SumSquareDifferences(int input)
        {
            long difference = 0;
            long squareOfTheSum = 0;
            long sumOfTheSquares = 0;
            for (int i = 1; i <= input; i++)
            {
                squareOfTheSum += i;
                sumOfTheSquares += (i * i);
            }
            squareOfTheSum = squareOfTheSum * squareOfTheSum;
            difference = squareOfTheSum - sumOfTheSquares;

            return difference;
        }
    }
}


text:
package matrix

type Move struct {
	file byte
	rank int
}

func NewMove(file byte, rank int) *Move {
	move := new(Move)
	move.file = file
	move.rank = rank
	return move
}

func (move Move) ToPoint() Point {
	return Point{SIDE - move.rank, int(move.file - 'a')}
}

redpajama_set_name: RedPajamaGithub


text:
layout: default
---

Stop The Spies

Take a stand against online surveillance

          Take Action Now

              The Australian government is on the verge of ordering your ISP to track and record your movements online. These plans are made on the pretext of fighting terrorism, but they really belong in a police state. Mandatory data retention policies treat every single citizen as a suspect worthy of constant intrusive surveillance.

              This website hopes to provide you with the information you need to be informed and tools to contact your representatives to let them know how you feel about this issue. With your help, we can stop the spies.

            Share on Twitter

          0

            Share on Facebook

          0

            Share on Google+

          0

What it's about

My representatives

Progress

#stopthespies

What else can I do?

Update: Public statements from officials have noted that search data will not be included in data retention.

Update: Public statements from officials have stated that browser history will not be recorded. It is also reported by the media that the websites you visit will not be logged contrary to previous statements by officials.

Your privacy is under attack

Your personal life, exposed

        Under the proposed data retention laws, details about everything you do online or on your phone would be compulsorily collected and stored.

        Information about the apps you use, the emails you send, and even the places you go and who you communicate with—all of this data will be collected.

    <canvas width="1280" height="500" style="margin-left: -640px; margin-top: -250px;"></canvas>

Why you should be worried

It's only data, right?

        By piecing together information about your online life from multiple sources, the government plans to use your ISP to build a secret online dossier on every Australian.

       Even if this information were only being collected to fight terrorism—and this is far from clear—there remains a frightening risk that it will be misused or fall into the wrong hands.

    <canvas width="1280" height="500" style="margin-left: -640px; margin-top: -250px;"></canvas>

DATA RETENTION AROUND THE WORLD

AUSTRALIA IS FLOUTING HUMAN RIGHTS

        The Court of Justice of the European Union this year ruled a similar European data retention mandate as illegal, being "an interference with the fundamental rights of practically the entire European population."

        The United Nations High Commissioner for Human Rights also recently criticised mandatory data retention rules as being neither necessary nor proportionate.

    <canvas width="1280" height="500" style="margin-left: -640px; margin-top: -250px;"></canvas>

Who's paying for all this?

The Australian public

        Australia's second-largest ISP has estimated the cost of the mandatory data retention proposal at an extra $130 per customer, per year.

$$$

You can stop the spies

   <canvas width="1280" height="700" style="margin-left: -640px; margin-top: -350px;"></canvas>

Take Action

Contact your Representative

              By contacting your representative, you'll show that you're part of a movement that condemns compulsory data retention as a violation of international human rights law.

              Not in Australia?

Mass surveillance is a global issue, find campaigns relevant to your country in the table below.

Country	Campaign

US	Stand Against Spying

UK	Don't Spy On Us

Auto Lookup

                        <button class="btn btn-info btn-autolookup" style="border-radius: 3px;margin: auto; width: 130px; float: none;" type="submit">Auto-Lookup!</button>

Accept the browser request to share your location.

                      Oh no! We couldn't find you. Try your postcode instead.

Postcode Lookup

                    <form class="postcode-lookup">

                        <input type="text" class="form-control" pattern="[0-9]{4}" required>
                        <button class="btn btn-info" type="submit">Lookup!</button>

                    </form>

      <canvas width="1280" height="500" style="margin-left: -640px; margin-top: -250px;"></canvas>

Searching for your representatives...

Just a bit longer...

Oops! There was a problem loading your results, the servers might be very busy.

                Try again

Not your representatives?

Search again

We use your postcode to find legislators that represent you, it is not stored and, is transferred over a secure connection.

                Legislator data is provided by OpenAustralia.org

Here are some talking points you can use

I oppose mandatory data retention in Australia. As my representative, I'm asking you to reject this proposal.

I value my digital privacy. When I use the Internet, I want secure, private communication. I don't want to be surveilled and spied on when I'm not suspected of a crime.

The proposal would push all the costs of data retention onto Internet Service Providers, who would pass the costs onto their customers. That means higher bills for Australians, as well as higher costs for new ISPs looking to enter the market.

Courts around the world are finding data retention mandates unconstitutional because they violate individual privacy rights. Let's do the right thing in Australia and stop these proposals before they become the law.

Campaign Progress

0

Legislator lookups

0

Attempted legislator tweets

0

Legislator contact page visits

0

Legislator Facebook page visits

                    0

                    0

                    0

                    0

0 tweets about #StopTheSpies and #StopDataRetention

              By tweeting “#StopTheSpies”, “#StopDataRetention” or sharing the URL of this site on Twitter, you will automatically be added to the list below.

Take Action

What else can I do?

Sign a Petition

                        Aside from contacting your representatives, you can also sign a petition that calls on the Federal Government to drop its proposed mandatory, indiscriminate data retention regime, and to treat ordinary, law-abiding Australians as citizens, not suspects.

                      Sign a petition now

Spread the Word

                                Share on Twitter

                                Share on Facebook

                                Share on Google+

Learn more about the proposed laws

Australian Proposal Would Require Suspicionless Domestic Spying by ISPs

Data Retention as Mass Surveillance An Australian Perspective

Access to and retention of internet 'metadata'

Protecting your privacy: Our stand against 'mandatory data retention' - IInet

Data retention scheme would lead to surveillance tax on consumers, say telcos

Supporters

      <canvas width="1280" height="500" style="margin-left: -640px; margin-top: -250px;"></canvas>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources >
	<color name="colorPrimary" >#3F51B5</color >
	<color name="colorPrimaryDark" >#303F9F</color >
	<color name="colorAccent" >#FF4081</color >
</resources >


text:
#pragma once
#include <aws/workmail/WorkMail_EXPORTS.h>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace WorkMail
{
namespace Model
{
  class AWS_WORKMAIL_API CancelMailboxExportJobResult
  {
  public:
    CancelMailboxExportJobResult();
    CancelMailboxExportJobResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    CancelMailboxExportJobResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

  };

} // namespace Model
} // namespace WorkMail
} // namespace Aws


text:
class AddMoreSetupToGoggleCup < ActiveRecord::Migration[5.1]

  def change
    # Add columns to increase calculation variety
    change_table :goggle_cups, bulk: true do |t|
      t.column(:is_team_limited, :boolean, default: true)
      t.column(:career_step, :integer, default: 100)
      t.column(:career_bonus, :decimal, precision: 10, scale: 2, default: 0.0)
    end
  end

end


text:
class SlackRegularWorker
  include Sidekiq::Worker

  def perform(issue_id, state)
    issue = Issue.find_by(id: issue_id) || return
    project = issue.project

    return unless Intouch::Regular::Checker::Base.new(
      issue: issue,
      state: state,
      project: project
    ).required?

    slack_accounts = SlackAccount.where(
        user_id: Intouch::Regular::RecipientsList.new(
            issue: issue,
            state: state,
            protocol: 'slack'
        ).call.map(&:id)
    ).to_a

    return if slack_accounts.empty?

    client = RedmineBots::Slack.bot_client

    channels = client.im_list

    return unless channels['ok']

    channels = client.im_list

    return unless channels['ok']

    channels.ims.select { |im| im.user.in?(slack_accounts.map(&:slack_id)) }.each do |channel|
      client.chat_postMessage(text: issue.as_markdown, channel: channel.id)
    end
  end
end


text:
<?php

namespace Alpixel\Bundle\SEOBundle\Annotation;

use Doctrine\Common\Annotations\Annotation;

/**
 * The MetaTag class handles the MetaTag annotation parts.
 *
 *
 * @author Benjamin HUBERT <benjamin@alpixel.fr>
 * @Annotation
 * @Target("METHOD")
 */
class MetaTag extends Annotation
{
    public $value;
    public $title;
    public $providerClass;
}


text:
using Entitas;

[Input]
public sealed class JumpComponent : IComponent {
    public GameEntity entity;
}


text:
namespace JsonToEnum.Export {
 	public enum  BucketScope
 	{
 		 Character = 0,
 		 Account = 1
 	}
 }


text:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { BookComponent } from './book.component';
import { MyBooksComponent } from './mybooks/my-books.component';
import { BookListComponent } from './booklist/book-list.component';
import { BookDetailComponent } from './book-detail/book-detail.component';
import { AuthGuard } from '../core/auth-guard.service';
import { TradeService } from '../core/trade.service';
import { AuthService } from '../core/auth.service';
import { MyBooksService } from '../core/my-books.service';
import { BookDetailService } from '../book/book-detail/book-detail.service';

const bookRoutes: Routes = [
  {
    path: 'book',
    component: BookComponent,
    canActivate: [AuthGuard],
    children: [
      { path: 'me', component: MyBooksComponent },
      {
        path: '',
        component: BookListComponent,
        children: [
          {
            path: ':volumeID',
            component: BookDetailComponent,
            resolve: {
              bookDetail: BookDetailService,
              user: AuthService,
              myRequests: TradeService,
              myBooks: MyBooksService,
            },
          },
        ],
      },
    ],
  },
];

@NgModule({
  imports: [
    RouterModule.forChild(bookRoutes),
  ],

  exports: [
    RouterModule,
  ],
})
export class BookRoutingModule {
}


text:
package processors.microblaze_3sp.instruction;

import processors.microblaze_3sp.*;
import system.cpu.*;

/**
 * The brk instruction class.
 */
public class brk extends Instruction
{
 /** The Fireworks Three Stage Pipeline processor to which instruction belongs. */
 private fw_3sp cpu;
 /** The memory's address of the instruction. Or memory's address of the instruction in the moment it was fetched. */
 private int pc;
 /** The destination register. */
 private int rD;
 /** The source register B. */
 private int rB;
 /** The instruction's latency in the execute stage. */
 private int latency;
 /** The number of cycles performed in the execute stage. */
 private int cycles = 1;

 /**
  * Instantiates a new brk instruction.
  *
  * @param cpu the Fireworks Three Stage Pipeline processor to which instruction belongs.
  * @param address the memory's address of the instruction.
  * @param rD the destination register.
  * @param rB the source register B.
  * @param latency the instruction's latency in the execute stage.
  */
 public brk(fw_3sp cpu,int address,int rD,int rB,int latency)
 {
  this.cpu = cpu;
  pc = address;
  this.rD = rD;
  this.rB = rB;
  this.latency = latency;
 }

 // -----------------------------------------------
 // methods to operate instructions in the pipeline
 // -----------------------------------------------

 /**
  * Performs one operation cycle of the instruction in the pipeline stage. The pipeline stage is define by the parameter stage.

  * In Fireworks Three Stage Pipeline processor the instruction only operates in the execute pipeline stage. Because of that the parameter stage in practice is never used.
  *
  * @param stage the pipeline stage where the instruction is operating.

  * 1 - fetch stage.

  * 2 - decode stage.

  * 3 - execute stage.
  * @return the cpu status after the instruction operates the cycle.
  * @see system.cpu.Instruction#Stage(int)
  */
 public final int Stage(int stage)
 {
  int aux_b;
  int msr;

  if(cycles < latency)
  {
   cycles++;
   return cpu_status.STALL;
  }
  cycles = 1;
  cpu.putGeneral(rD,pc);
  aux_b = cpu.getGeneral(rB);
  cpu.putPC(aux_b);
  msr = cpu.getMSR();
  msr = msr | 0x8;
  cpu.putMSR(msr);
  return cpu_status.JUMP;
 }

 // -------------------
 // methods auxiliaries
 // -------------------

 /**
  * Returns the Program Counter (PC) of the instruction.

  * If the instruction is accessed from the memory returns the address of its position in the memory.

  * If the instruction is accessed from any pipeline stage returns the address of its position in the memory on the moment it was fetched.
  * @return the Program Counter (PC) of the instruction.
  * @see system.cpu.Instruction#getPC()
  */
 public final int getPC()
 {
  return pc;
 }

 // -----------------------------------
 // methods used to display information
 // -----------------------------------

 /**
  * Returns the instruction name.
  *
  * @return the instruction name.
  * @see java.lang.Object#toString()
  */
 public String toString()
 {
  return "brk";
 }
}


text:
using Vipr.Core.CodeModel;

namespace CSharpWriter
{
    public class ContainerNavigationCollectionProperty : FetcherNavigationCollectionProperty
    {
        protected ContainerNavigationCollectionProperty(OdcmProperty odcmProperty) : base(odcmProperty)
        {
        }

        public static ContainerNavigationCollectionProperty ForService(OdcmProperty odcmProperty)
        {
            return new ContainerNavigationCollectionProperty(odcmProperty);
        }
    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/ads/googleads/v12/enums/feed_origin.proto

namespace Google\Ads\GoogleAds\V12\Enums\FeedOriginEnum;

use UnexpectedValueException;

/**
 * Possible values for a feed origin.
 *
 * Protobuf type google.ads.googleads.v12.enums.FeedOriginEnum.FeedOrigin
 */
class FeedOrigin
{
    /**
     * Not specified.
     *
     * Generated from protobuf enum UNSPECIFIED = 0;
     */
    const UNSPECIFIED = 0;
    /**
     * Used for return value only. Represents value unknown in this version.
     *
     * Generated from protobuf enum UNKNOWN = 1;
     */
    const UNKNOWN = 1;
    /**
     * The FeedAttributes for this Feed are managed by the
     * user. Users can add FeedAttributes to this Feed.
     *
     * Generated from protobuf enum USER = 2;
     */
    const USER = 2;
    /**
     * The FeedAttributes for an GOOGLE Feed are created by Google. A feed of
     * this type is maintained by Google and will have the correct attributes
     * for the placeholder type of the feed.
     *
     * Generated from protobuf enum GOOGLE = 3;
     */
    const GOOGLE = 3;

    private static $valueToName = [
        self::UNSPECIFIED => 'UNSPECIFIED',
        self::UNKNOWN => 'UNKNOWN',
        self::USER => 'USER',
        self::GOOGLE => 'GOOGLE',
    ];

    public static function name($value)
    {
        if (!isset(self::$valueToName[$value])) {
            throw new UnexpectedValueException(sprintf(
                    'Enum %s has no name defined for value %s', __CLASS__, $value));
        }
        return self::$valueToName[$value];
    }

    public static function value($name)
    {
        $const = __CLASS__ . '::' . strtoupper($name);
        if (!defined($const)) {
            throw new UnexpectedValueException(sprintf(
                    'Enum %s has no value defined for name %s', __CLASS__, $name));
        }
        return constant($const);
    }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(FeedOrigin::class, \Google\Ads\GoogleAds\V12\Enums\FeedOriginEnum_FeedOrigin::class);


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/google_height"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/google_height">

        <ProgressBar
            android:id="@+id/loading_footer_progressbar"
            android:layout_width="26dp"
            android:layout_height="26dp"
            android:layout_centerInParent="true"
            android:layout_margin="11dp"
            android:indeterminateDrawable="@drawable/ui_rotate_shape_loading" />
    </RelativeLayout>
</LinearLayout>


text:
package ro.szzsa.utils.converter;

/**
 *
 */
public class ConverterException extends RuntimeException {

  public ConverterException(Throwable cause) {
    super(cause);
  }
}


text:
<?php

namespace Alloy\Observers;

use Alloy\Core\IObservable;
use Alloy\Core\IObserver;

abstract class Observable implements IObservable
{
    /**
     * @var IObserver[]
     */
    private $_observers = array();

    /**
     * {@inheritdoc}
     */
    public function addObserver(IObserver $observer)
    {
        $this->_observers[] = $observer;
    }

    /**
     * Returns tag for current object
     *
     * @return string
     */
    protected function _getObservableTag()
    {
        $tag = get_class($this);
        if (strpos($tag, '\\') !== false) {
            $tag = explode('\\', $tag);
            $tag = $tag[count($tag) - 1];
        }
        return $tag;
    }

    /**
     * {@inheritdoc}
     */
    public function notify(Packet $packet)
    {
        if (count($this->_observers) === 0) {
            return;
        }

        foreach ($this->_observers as $observer) {
            $observer->handlePacket($packet);
        }
    }

    /**
     * Register an exception and rethrows it
     *
     * @param \Exception $exception
     * @param string $tag
     * @throws \Exception
     */
    protected function _oRethrow($exception, $tag = null)
    {
        if (count($this->_observers) === 0) {
            throw $exception;
        }
        if ($tag === null) {
            $tag = $this->_getObservableTag();
        }
        $this->notify(new Packet($exception, $tag, Packet::LEVEL_ERROR));
        throw $exception;
    }

    /**
     * Sends message to observers, using WARNING level
     *
     * @param mixed  $message
     * @param string $tag
     */
    protected function _oWarn($message, $tag = null)
    {
        if (count($this->_observers) === 0) {
            return;
        }
        if ($tag === null) {
            $tag = $this->_getObservableTag();
        }
        $this->notify(new Packet($message, $tag, Packet::LEVEL_WARNING));
    }

    /**
     * Sends message to observers, using DEBUG level
     *
     * @param mixed  $message
     * @param string $tag
     */
    protected function _oDebug($message, $tag = null)
    {
        if (count($this->_observers) === 0) {
            return;
        }
        if ($tag === null) {
            $tag = $this->_getObservableTag();
        }
        $this->notify(new Packet($message, $tag, Packet::LEVEL_DEBUG));
    }

    /**
     * Sends message to observers, using NOTICE level
     *
     * @param mixed  $message
     * @param string $tag
     */
    protected function _oLog($message, $tag = null)
    {
        if (count($this->_observers) === 0) {
            return;
        }
        if ($tag === null) {
            $tag = $this->_getObservableTag();
        }
        $this->notify(new Packet($message, $tag, Packet::LEVEL_NOTICE));
    }

}


text:
void test_one_input(const std::vector<uint8_t>& buffer)
{
    FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
    const std::string format_string = fuzzed_data_provider.ConsumeRandomLengthString(64);

    const int digits_in_format_specifier = std::count_if(format_string.begin(), format_string.end(), IsDigit);

    // Avoid triggering the following crash bug:
    // * strprintf("%987654321000000:", 1);
    //
    // Avoid triggering the following OOM bug:
    // * strprintf("%.222222200000000$", 1.1);
    //
    // Upstream bug report: https://github.com/c42f/tinyformat/issues/70
    if (format_string.find("%") != std::string::npos && digits_in_format_specifier >= 7) {
        return;
    }

    // Avoid triggering the following crash bug:
    // * strprintf("%1$*1$*", -11111111);
    //
    // Upstream bug report: https://github.com/c42f/tinyformat/issues/70
    if (format_string.find("%") != std::string::npos && format_string.find("$") != std::string::npos && format_string.find("*") != std::string::npos && digits_in_format_specifier > 0) {
        return;
    }

    // Avoid triggering the following crash bug:
    // * strprintf("%.1s", (char*)nullptr);
    //
    // (void)strprintf(format_string, (char*)nullptr);
    //
    // Upstream bug report: https://github.com/c42f/tinyformat/issues/70

    try {
        (void)strprintf(format_string, (signed char*)nullptr);
    } catch (const tinyformat::format_error&) {
    }
    try {
        (void)strprintf(format_string, (unsigned char*)nullptr);
    } catch (const tinyformat::format_error&) {
    }
    try {
        (void)strprintf(format_string, (void*)nullptr);
    } catch (const tinyformat::format_error&) {
    }
    try {
        (void)strprintf(format_string, (bool*)nullptr);
    } catch (const tinyformat::format_error&) {
    }
    try {
        (void)strprintf(format_string, (float*)nullptr);
    } catch (const tinyformat::format_error&) {
    }
    try {
        (void)strprintf(format_string, (double*)nullptr);
    } catch (const tinyformat::format_error&) {
    }
    try {
        (void)strprintf(format_string, (int16_t*)nullptr);
    } catch (const tinyformat::format_error&) {
    }
    try {
        (void)strprintf(format_string, (uint16_t*)nullptr);
    } catch (const tinyformat::format_error&) {
    }
    try {
        (void)strprintf(format_string, (int32_t*)nullptr);
    } catch (const tinyformat::format_error&) {
    }
    try {
        (void)strprintf(format_string, (uint32_t*)nullptr);
    } catch (const tinyformat::format_error&) {
    }
    try {
        (void)strprintf(format_string, (int64_t*)nullptr);
    } catch (const tinyformat::format_error&) {
    }
    try {
        (void)strprintf(format_string, (uint64_t*)nullptr);
    } catch (const tinyformat::format_error&) {
    }

    try {
        switch (fuzzed_data_provider.ConsumeIntegralInRange(0, 13)) {
        case 0:
            (void)strprintf(format_string, fuzzed_data_provider.ConsumeRandomLengthString(32));
            break;
        case 1:
            (void)strprintf(format_string, fuzzed_data_provider.ConsumeRandomLengthString(32).c_str());
            break;
        case 2:
            (void)strprintf(format_string, fuzzed_data_provider.ConsumeIntegral<signed char>());
            break;
        case 3:
            (void)strprintf(format_string, fuzzed_data_provider.ConsumeIntegral<unsigned char>());
            break;
        case 4:
            (void)strprintf(format_string, fuzzed_data_provider.ConsumeIntegral<char>());
            break;
        case 5:
            (void)strprintf(format_string, fuzzed_data_provider.ConsumeBool());
            break;
        case 6:
            (void)strprintf(format_string, fuzzed_data_provider.ConsumeFloatingPoint<float>());
            break;
        case 7:
            (void)strprintf(format_string, fuzzed_data_provider.ConsumeFloatingPoint<double>());
            break;
        case 8:
            (void)strprintf(format_string, fuzzed_data_provider.ConsumeIntegral<int16_t>());
            break;
        case 9:
            (void)strprintf(format_string, fuzzed_data_provider.ConsumeIntegral<uint16_t>());
            break;
        case 10:
            (void)strprintf(format_string, fuzzed_data_provider.ConsumeIntegral<int32_t>());
            break;
        case 11:
            (void)strprintf(format_string, fuzzed_data_provider.ConsumeIntegral<uint32_t>());
            break;
        case 12:
            (void)strprintf(format_string, fuzzed_data_provider.ConsumeIntegral<int64_t>());
            break;
        case 13:
            (void)strprintf(format_string, fuzzed_data_provider.ConsumeIntegral<uint64_t>());
            break;
        default:
            assert(false);
        }
    } catch (const tinyformat::format_error&) {
    }
}


text:
package org.pageseeder.ox;

import org.junit.Assert;
import org.junit.Test;

/**
 * @author Ciber Cai
 * @since 17 Jun 2016
 */
public class OXExceptionTest {

  @Test
  public void test_Object() {
    Assert.assertNotNull(new OXException());
  }

}


text:
#ifndef __MODULE__TEXTURE_HPP__
#define __MODULE__TEXTURE_HPP__

#include <stdint.h>
#include "ModuleDefines.hpp"
namespace Module {

	/**
	 * A pure virtual class meant to be subclassed for interface implementation.
	 * Subclasses store an implentation-specific representation of a texture.
	 */
	class Texture {
	protected:
	public:
		/**
		 * Returns the color of a pixel at a given integer position
		 */
		virtual Color getPixel(uint16_t x, uint16_t y) = 0;
		/**
		 * Returns the color of a pixel at a given floating-point position
		 */
		virtual Color getPixel(float x, float y) = 0;
	};
}

#endif


text:
package org.carbon.sample.v2.app.oauth.def;

/**
 * @author Shota Oda 2017/07/30.
 */
public enum GrantType {
    authorization_code,
    password,
    assertion,
    refresh_token,
    none,
}


text:
{-| Balancing task of the maintenance daemon.

This module carries out the automated balancing done by the
maintenance daemon. The actual balancing algorithm is imported
from htools.

-}
{-

Copyright (C) 2015 Google Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2. 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 THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

-}

module Ganeti.MaintD.Balance
  ( balanceTask
  ) where

import Control.Exception.Lifted (bracket)
import Control.Monad (liftM, unless, when)
import Control.Monad.IO.Class (liftIO)
import Data.IORef (IORef)
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.Maybe (mapMaybe, isJust)
import qualified Data.Traversable as Traversable
import System.IO.Error (tryIOError)
import Text.Printf (printf)

import Ganeti.BasicTypes ( ResultT, mkResultT, mkResultT'
                         , GenericResult(..), Result)
import Ganeti.Cpu.Types (emptyCPUavgload, CPUavgload(..))
import Ganeti.HTools.AlgorithmParams (AlgorithmOptions(..), defaultOptions)
import qualified Ganeti.HTools.Backend.MonD as MonD
import qualified Ganeti.HTools.Cluster as Cluster
import qualified Ganeti.HTools.Cluster.Metrics as Metrics
import qualified Ganeti.HTools.Cluster.Utils as ClusterUtils
import qualified Ganeti.HTools.Container as Container
import qualified Ganeti.HTools.Instance as Instance
import qualified Ganeti.HTools.Node as Node
import Ganeti.JQueue (currentTimestamp)
import Ganeti.JQueue.Objects (Timestamp)
import Ganeti.Jobs (submitJobs)
import Ganeti.HTools.Types ( zeroUtil, DynUtil(cpuWeight), addUtil, subUtil
                           , MoveJob)
import Ganeti.Logging.Lifted (logDebug)
import Ganeti.MaintD.MemoryState ( MemoryState, getEvacuated
                                 , addEvacuated, rmEvacuated)
import Ganeti.MaintD.Utils (annotateOpCode)
import qualified Ganeti.Luxi as L
import Ganeti.OpCodes (MetaOpCode)
import qualified Ganeti.Path as Path
import qualified Ganeti.Query.Language as Qlang
import Ganeti.Types (JobId)
import Ganeti.Utils (logAndBad)

-- * Collection of dynamic load data

data AllReports = AllReports { rTotal :: MonD.Report
                             , rIndividual :: MonD.Report
                             }

-- | Empty report. It describes an idle node and can be used as
-- default value for nodes marked as offline.
emptyReports :: AllReports
emptyReports = AllReports (MonD.CPUavgloadReport emptyCPUavgload)
                          (MonD.InstanceCpuReport Map.empty)

-- | Query a node unless it is offline and return all
-- CPU reports. For offline nodes return the empty report.
queryNode :: Node.Node -> ResultT String IO AllReports
queryNode node = do
  let getReport dc = mkResultT
                     . liftM (maybe (Bad $ "Failed collecting "
                                           ++ MonD.dName dc
                                           ++ " from " ++ Node.name node) Ok
                              . MonD.mkReport dc)
                     $ MonD.fromCurl dc node
  if Node.offline node
    then return emptyReports
    else do
      total <- getReport MonD.totalCPUCollector
      xeninstances <- getReport MonD.xenCPUCollector
      return $ AllReports total xeninstances

-- | Get a map with the CPU live data for all nodes; for offline nodes
-- the empty report is guessed.
queryLoad :: Node.List -> ResultT String IO (Container.Container AllReports)
queryLoad = Traversable.mapM queryNode

-- | Ask luxid about the hypervisors used. As, at the moment, we only
-- have specialised CPU collectors for xen, we're only interested which
-- instances run under the Xen hypervisor.
getXenInstances :: ResultT String IO (Set.Set String)
getXenInstances = do
  let query = L.Query (Qlang.ItemTypeOpCode Qlang.QRInstance)
              ["name", "hypervisor"] Qlang.EmptyFilter
  luxiSocket <- liftIO Path.defaultQuerySocket
  raw <- bracket (mkResultT . liftM (either (Bad . show) Ok)
                   . tryIOError $ L.getLuxiClient luxiSocket)
                 (liftIO . L.closeClient)
                 $ mkResultT' . L.callMethod query
  answer <- L.extractArray raw >>= mapM (mapM L.fromJValWithStatus)
  let getXen [name, hv] | hv `elem` ["xen-pvm", "xen-hvm"] = [name]
      getXen _ = []
  return $ Set.fromList (answer >>= getXen)

-- | Look for an instance in a given report.
findInstanceLoad :: String -> AllReports -> Maybe Double
findInstanceLoad  name r | MonD.InstanceCpuReport m <- rIndividual r =
  Map.lookup name m
findInstanceLoad _ _ = Nothing

-- | Update the CPU load of one instance based on the reports.
-- Fail if instance CPU load is not (yet) available. However, do
-- accpet missing load data for instances on offline nodes, as well
-- as old load data for recently migrated instances.
updateCPUInstance :: Node.List
                  -> Container.Container AllReports
                  -> Set.Set String
                  -> [String]
                  -> Instance.Instance
                  -> Result Instance.Instance
updateCPUInstance nl reports xeninsts evacuated inst =
  let name = Instance.name inst
      nidx = Instance.pNode inst
  in if name `Set.member` xeninsts
    then let onNodeLoad = findInstanceLoad name (Container.find nidx reports)
             allLoads = mapMaybe (findInstanceLoad name)
                          $ Container.elems reports
         in case () of
           _ | Just load <- onNodeLoad ->
                 return $ inst { Instance.util = zeroUtil { cpuWeight = load } }
           _ | (load:_) <- allLoads ->
                 return $ inst { Instance.util = zeroUtil { cpuWeight = load } }
           _ | Node.offline $ Container.find nidx nl ->
                 return $ inst { Instance.util = zeroUtil }
           _ | Instance.name inst `elem` evacuated ->
                 return $ inst { Instance.util = zeroUtil }
           _ -> fail $ "Xen CPU data unavailable for " ++ name
    else let rep = rTotal $ Container.find nidx reports
         in case rep of MonD.CPUavgloadReport (CPUavgload _ _ ndload) ->
                          let w = ndload * fromIntegral (Instance.vcpus inst)
                                  / (fromIntegral . Node.uCpu
                                       $ Container.find nidx nl)
                          in return $ inst { Instance.util =
                                                zeroUtil { cpuWeight = w }}
                        _ -> fail $ "CPU data unavailable for node of " ++ name

-- | Update CPU usage data based on the collected reports. That is, get the
-- CPU usage of all instances from the reports and also update the nodes
-- accordingly.
updateCPULoad :: (Node.List, Instance.List)
              -> Container.Container AllReports
              -> Set.Set String
              -> [ String ]
              -> Result (Node.List, Instance.List)
updateCPULoad (nl, il) reports xeninsts evacuated = do
  il' <- Traversable.mapM (updateCPUInstance nl reports xeninsts evacuated) il
  let addNodeUtil n delta = n { Node.utilLoad = addUtil (Node.utilLoad n) delta
                              , Node.utilLoadForth =
                                  addUtil (Node.utilLoadForth n) delta
                              }
  let updateNodeUtil nnl inst_old inst_new =
        let delta = subUtil (Instance.util inst_new) $ Instance.util inst_old
            nidx = Instance.pNode inst_old
            n = Container.find nidx nnl
            n' = addNodeUtil n delta
        in Container.add nidx n' nnl
  let nl' = foldl (\nnl i -> updateNodeUtil nnl (Container.find i il)
                               $ Container.find i il') nl $ Container.keys il
  return (nl', il')

-- | For an instance, given by name, verify if an individual load report is
-- available again.
cleanUpEvacuation :: IORef MemoryState
                  -> Instance.List
                  -> Container.Container AllReports
                  -> String
                  -> IO ()
cleanUpEvacuation memstate il reports name = do
  let insts = filter ((==) name . Instance.name) $ Container.elems il
  case insts of
    [] -> do
            logDebug $ "Instnace " ++ name ++ "no longer on the cluster"
            rmEvacuated memstate name
    inst:_ -> do
                 let nidx = Instance.pNode inst
                 when (isJust . findInstanceLoad name
                         $ Container.find nidx reports) $ do
                   logDebug $ "Load data for " ++ name ++ " available again"
                   rmEvacuated memstate name

-- * Balancing

-- | Transform an instance move into a submittable job.
moveToJob :: Timestamp -> (Node.List, Instance.List) -> MoveJob -> [MetaOpCode]
moveToJob now (nl, il) (_, idx, move, _) =
  let opCodes = Cluster.iMoveToJob nl il idx move
  in map (annotateOpCode "auto-balancing the cluster" now) opCodes

-- | Iteratively improve a cluster by iterating over tryBalance.
iterateBalance :: AlgorithmOptions
               -> Cluster.Table -- ^ the starting table
               -> [MoveJob]     -- ^ current command list
               -> [MoveJob]     -- ^ resulting commands
iterateBalance opts ini_tbl cmds =
  let Cluster.Table ini_nl ini_il _ _ = ini_tbl
      m_next_tbl = Cluster.tryBalance opts ini_tbl
  in case m_next_tbl of
    Just next_tbl@(Cluster.Table _ _ _ plc@(curplc:_)) ->
      let (idx, _, _, move, _) = curplc
          plc_len = length plc
          (_, cs) = Cluster.printSolutionLine ini_nl ini_il 1 1 curplc plc_len
          afn = Cluster.involvedNodes ini_il curplc
          cmds' = (afn, idx, move, cs):cmds
      in iterateBalance opts next_tbl cmds'
    _ -> cmds

-- | List instances evacuated in a move job, if any.
evacuatedInsts :: (Node.List, Instance.List)
               -> MoveJob
               -> [String]
evacuatedInsts (nl, il) (_, idx, _, _) =
  let inst = Container.find idx il
      node = Container.find (Instance.pNode inst) nl
  in [Instance.name inst | Node.offline node]

-- | Balance a single group, restricted to the allowed nodes and
-- minimal gain.
balanceGroup :: IORef MemoryState
             -> Set.Set String
             -> L.Client
             -> Set.Set Int
             -> Double
             -> (Int,  (Node.List, Instance.List))
             -> ResultT String IO [JobId]
balanceGroup memstate xens client allowedNodes threshold (gidx, (nl, il)) = do
  logDebug $ printf "Balancing group %d, %d nodes, %d instances." gidx
               (Container.size nl) (Container.size il)
  let ini_cv = Metrics.compCV nl
      ini_tbl = Cluster.Table nl il ini_cv []
      opts = defaultOptions { algAllowedNodes = Just allowedNodes
                            , algMinGain = threshold
                            , algMinGainLimit = 10 * threshold
                            }
      cmds = iterateBalance opts ini_tbl []
      tasks = take 1 $ Cluster.splitJobs cmds
  logDebug $ "First task group: " ++ show tasks
  now <- liftIO currentTimestamp
  let jobs = tasks >>= map (moveToJob now (nl, il))
      evacs = filter (`Set.member` xens)
              (concat tasks >>= evacuatedInsts (nl, il))
  if null jobs
    then return []
    else do
      unless (null evacs) $ do
        logDebug $ "Evacuation of instances " ++ show evacs
        liftIO $ addEvacuated memstate evacs
      jids <- liftIO $ submitJobs jobs client
      case jids of
        Bad e -> mkResultT . logAndBad
                   $ "Failure submitting balancing jobs: " ++ e
        Ok jids' -> return jids'

-- * Interface function

-- | Carry out all the needed balancing, based on live CPU data, only touching
-- the available nodes. Only carry out balancing steps where the gain is above
-- the threshold.
balanceTask :: IORef MemoryState
            -> (Node.List, Instance.List) -- ^ current cluster configuration
            -> Set.Set Int -- ^ node indices on which actions may be taken
            -> Double -- ^ threshold for improvement
            -> ResultT String IO [JobId] -- ^ jobs submitted
balanceTask memstate (nl, il) okNodes threshold = do
  logDebug "Collecting dynamic load values"
  evacuated <- getEvacuated memstate
  logDebug $ "Not expecting load data from: " ++ show evacuated
  reports <- queryLoad nl
  xenInstances <- getXenInstances
  (nl', il') <- mkResultT . return
                  $ updateCPULoad (nl, il) reports xenInstances evacuated
  liftIO $ mapM_ (cleanUpEvacuation memstate il reports) evacuated
  let ngroups = ClusterUtils.splitCluster nl' il'
  luxiSocket <- liftIO Path.defaultQuerySocket
  bracket (liftIO $ L.getLuxiClient luxiSocket) (liftIO . L.closeClient) $ \c ->
    liftM concat $ mapM (balanceGroup memstate xenInstances c okNodes threshold)
                        ngroups


text:
package org.languagetool.rules.patterns;

import org.junit.Test;
import org.languagetool.AnalyzedToken;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.chunking.ChunkTag;
import org.languagetool.language.Demo;

import java.util.Collections;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class AbstractPatternRulePerformerTest {

  @Test
  public void testTestAllReadings() throws Exception {
    PatternToken patternToken1 = new PatternToken("foo", false, false, false);
    PatternRule simpleRule = new PatternRule("FAKE", new Demo(), Collections.singletonList(patternToken1), "descr", "message", "short");
    PatternTokenMatcher elemMatcher = new PatternTokenMatcher(patternToken1);

    AbstractPatternRulePerformer p = new MockAbstractPatternRulePerformer(simpleRule, new Unifier(null, null));

    assertTrue(p.testAllReadings(tokenReadings("foo", null), elemMatcher, null, 0, 0, 0));
    assertFalse(p.testAllReadings(tokenReadings("bar", null), elemMatcher, null, 0, 0, 0));
    assertTrue(p.testAllReadings(tokenReadings("foo", "myChunk"), elemMatcher, null, 0, 0, 0));
    assertTrue(p.testAllReadings(tokenReadings("foo", "otherChunk"), elemMatcher, null, 0, 0, 0));
  }

  @Test
  public void testTestAllReadingsWithChunks() throws Exception {
    PatternToken chunkPatternToken = new PatternToken(null, false, false, false);
    chunkPatternToken.setChunkTag(new ChunkTag("myChunk"));
    PatternRule simpleRule = new PatternRule("FAKE", new Demo(), Collections.singletonList(chunkPatternToken), "descr", "message", "short");
    PatternTokenMatcher elemMatcher = new PatternTokenMatcher(chunkPatternToken);

    AbstractPatternRulePerformer p = new MockAbstractPatternRulePerformer(simpleRule, new Unifier(null, null));

    assertFalse(p.testAllReadings(tokenReadings("bar", null), elemMatcher, null, 0, 0, 0));
    assertTrue(p.testAllReadings(tokenReadings("bar", "myChunk"), elemMatcher, null, 0, 0, 0));
    assertFalse(p.testAllReadings(tokenReadings("bar", "otherChunk"), elemMatcher, null, 0, 0, 0));
  }

  private AnalyzedTokenReadings[] tokenReadings(String token, String chunkTag) {
    AnalyzedTokenReadings tokenReadings1 = new AnalyzedTokenReadings(new AnalyzedToken(token, "pos", "lemma"), 0);
    if (chunkTag != null) {
      tokenReadings1.setChunkTags(Collections.singletonList(new ChunkTag(chunkTag)));
    }
    return new AnalyzedTokenReadings[] { tokenReadings1 };
  }

  static class MockAbstractPatternRulePerformer extends AbstractPatternRulePerformer {
    protected MockAbstractPatternRulePerformer(AbstractPatternRule rule, Unifier unifier) {
      super(rule, unifier);
    }
  }
}


text:
#include "tango-gl/video_overlay.h"
#include "tango-gl/shaders.h"

namespace tango_gl {

static const GLfloat kVertices[] =
  {-1.0,  1.0, 0.0,
   -1.0, -1.0, 0.0,
    1.0,  1.0, 0.0,
    1.0, -1.0, 0.0};

static const GLushort kIndices[] =
  {0, 1, 2, 2, 1, 3};

static const GLfloat kTextureCoords[] =
  {0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0};

VideoOverlay::VideoOverlay() {
  glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
  shader_program_ =
      util::CreateProgram(shaders::GetVideoOverlayVertexShader().c_str(),
                          shaders::GetVideoOverlayFragmentShader().c_str());
  if (!shader_program_) {
    LOGE("Could not create program.");
  }

  glGenTextures(1, &texture_id_);
  glBindTexture(GL_TEXTURE_EXTERNAL_OES, texture_id_);
  glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  uniform_texture_ = glGetUniformLocation(shader_program_, "texture");

  glGenBuffers(3, vertex_buffers_);
  // Allocate vertices buffer.
  glBindBuffer(GL_ARRAY_BUFFER, vertex_buffers_[0]);
  glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 3 * 4, kVertices,
               GL_STATIC_DRAW);
  glBindBuffer(GL_ARRAY_BUFFER, 0);

  // Allocate triangle indices buffer.
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertex_buffers_[1]);
  glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLushort) * 6, kIndices,
               GL_STATIC_DRAW);
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

  // Allocate texture coordinates buufer.
  glBindBuffer(GL_ARRAY_BUFFER, vertex_buffers_[2]);
  glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 2 * 4, kTextureCoords,
               GL_STATIC_DRAW);
  glBindBuffer(GL_ARRAY_BUFFER, 0);

  // Assign the vertices attribute data.
  attrib_vertices_ = glGetAttribLocation(shader_program_, "vertex");
  glBindBuffer(GL_ARRAY_BUFFER, vertex_buffers_[0]);
  glEnableVertexAttribArray(attrib_vertices_);
  glVertexAttribPointer(attrib_vertices_, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
  glBindBuffer(GL_ARRAY_BUFFER, 0);

  // Assign the texture coordinates attribute data.
  attrib_texture_coords_ = glGetAttribLocation(shader_program_, "textureCoords");
  glBindBuffer(GL_ARRAY_BUFFER, vertex_buffers_[2]);
  glEnableVertexAttribArray(attrib_texture_coords_);
  glVertexAttribPointer(attrib_texture_coords_, 2, GL_FLOAT, GL_FALSE, 0,
                        nullptr);
  glBindBuffer(GL_ARRAY_BUFFER, 0);

  uniform_mvp_mat_ = glGetUniformLocation(shader_program_, "mvp");
}

void VideoOverlay::Render(const glm::mat4& projection_mat,
                          const glm::mat4& view_mat) const {
  glUseProgram(shader_program_);

  glUniform1i(uniform_texture_, 0);
  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_EXTERNAL_OES, texture_id_);

  glm::mat4 model_mat = GetTransformationMatrix();
  glm::mat4 mvp_mat = projection_mat * view_mat * model_mat;
  glUniformMatrix4fv(uniform_mvp_mat_, 1, GL_FALSE, glm::value_ptr(mvp_mat));

  // Bind vertices buffer.
  glBindBuffer(GL_ARRAY_BUFFER, vertex_buffers_[0]);
  glEnableVertexAttribArray(attrib_vertices_);
  glVertexAttribPointer(attrib_vertices_, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
  glBindBuffer(GL_ARRAY_BUFFER, 0);

  // Bind texture coordinates buffer.
  glBindBuffer(GL_ARRAY_BUFFER, vertex_buffers_[2]);
  glEnableVertexAttribArray(attrib_texture_coords_);
  glVertexAttribPointer(attrib_texture_coords_, 2, GL_FLOAT, GL_FALSE, 0,
                        nullptr);
  glBindBuffer(GL_ARRAY_BUFFER, 0);

  // Bind element array buffer.
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertex_buffers_[1]);
  glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);
  util::CheckGlError("glDrawElements");
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

  glUseProgram(0);
  util::CheckGlError("glUseProgram()");
}

}  // namespace tango_gl