示例#1
0
        public static String GetSanitizedName(String fullName)
        {
            const Int32   maxLength        = 51;
            StringBuilder sanitizedBuilder = fullName.Aggregate(new StringBuilder(),
                                                                (SB, c) => isAllowedCharacter(c)
                                                                                                         ? SB.Append(c)
                                                                                                         : SB.Append('!').Append(((Int32)c).ToString("x4")));

            String sanitizedString = sanitizedBuilder.ToString();

            if (sanitizedString.Length <= maxLength)
            {
                return(sanitizedString);
            }

            String testForIncompleteSequence = sanitizedString.Substring(maxLength - 4, 4);
            Int32  i             = testForIncompleteSequence.IndexOf('!');
            Int32  splitPosition = i < 0
                                ? maxLength
                                : maxLength - 4 + i;
            String exceeded  = sanitizedString.Substring(splitPosition);
            String truncated = sanitizedString.Remove(splitPosition);

            return(truncated + "-" + getExceedHash(exceeded));
        }
示例#2
0
 /// <summary>
 ///   Converts a four-char value to an unsigned integer.
 /// </summary>
 /// <param name = "fourCharValue">The four char value.</param>
 /// <returns>An unsigned integer</returns>
 protected static uint FourCharToInt(String fourCharValue)
 {
     if (fourCharValue.Length != 4)
     {
         throw new ArgumentException();
     }
     return(fourCharValue.Aggregate(0u, (i, c) => (i * 256) + c));
 }
示例#3
0
        private void SaveButtonClick(Object sender, RoutedEventArgs e)
        {
            String ip, subnet, gateway, dns, dnsSub;

            String[] octetList = new String[4];

            octetList[0] = this.ipFirstOctet.Text;
            octetList[1] = this.ipSecondOctet.Text;
            octetList[2] = this.ipThirdOctet.Text;
            octetList[3] = this.ipFourthOctet.Text;
            ip           = octetList.Aggregate((cur, next) => cur + "." + next);

            octetList[0] = this.subnetFirstOctet.Text;
            octetList[1] = this.subnetSecondOctet.Text;
            octetList[2] = this.subnetThirdOctet.Text;
            octetList[3] = this.subnetFourthOctet.Text;
            subnet       = octetList.Aggregate((cur, next) => cur + "." + next);

            octetList[0] = this.gateFirstOctet.Text;
            octetList[1] = this.gateSecondOctet.Text;
            octetList[2] = this.gateThirdOctet.Text;
            octetList[3] = this.gateFourthOctet.Text;
            gateway      = octetList.Aggregate((cur, next) => cur + "." + next);

            octetList[0] = this.dnsFirstOctet.Text;
            octetList[1] = this.dnsSecondOctet.Text;
            octetList[2] = this.dnsThirdOctet.Text;
            octetList[3] = this.dnsFourthOctet.Text;
            dns          = octetList.Aggregate((cur, next) => cur + "." + next);

            octetList[0] = this.dnsSubFirstOctet.Text;
            octetList[1] = this.dnsSubSecondOctet.Text;
            octetList[2] = this.dnsSubThirdOctet.Text;
            octetList[3] = this.dnsSubFourthOctet.Text;
            dnsSub       = octetList.Aggregate((cur, next) => cur + "." + next);


            SaveConfig(ip, subnet, gateway, dns, dnsSub);
        }
示例#4
0
    void calc()
    {
        String     s = Console.ReadLine();
        BigInteger l = new BigInteger();

        l = s.Aggregate(l, (current, c) => current * 10 + (c - '0'));

        BigInteger r = (l + 1) * (l + 1) - 1;

        l = l * l;
        while ((l + 99) / 100 <= r / 100)
        {
            l  = (l + 99) / 100;
            r /= 100;
        }
        Console.WriteLine(l);
    }
示例#5
0
        public static string GenerateDeck(int seed)
        {
            var cards = string.Empty;

            String[] suit = { "C", "S", "H", "D" };
            String[] rank =
            {
                "2", "3", "4", "5", "6", "7", "8", "9", "10",
                "J", "Q", "K", "A"
            };

            // initialize cards in a deck
            var deck = new String[suit.Length * rank.Length];

            for (var i = 0; i < rank.Length; i++)
            {
                for (var j = 0; j < suit.Length; j++)
                {
                    deck[suit.Length * i + j] = rank[i] + suit[j];
                }
            }

            // shuffle deck
            var d    = deck.Length;
            var rand = new Random(seed);

            for (var i = 0; i < d; i++)
            {
                var r    = i + (int)(rand.NextDouble() * (d - i));
                var temp = deck[r];
                deck[r] = deck[i];
                deck[i] = temp;
            }

            var generateDeck = deck.Aggregate(cards, (current, s) => current + (s + " "));

            Console.WriteLine(generateDeck);

            return(generateDeck);
        }
示例#6
0
 public static String DoubleString(String s)
 {
     // return a string that is the original string with each character in the string repeated twice
     // e.g. for input "ABCDE", return "AABBCCDDEE"
     return(s.Aggregate(string.Empty, (current, c) => current + (Convert.ToString(c) + Convert.ToString(c))));
 }
        public IDictionary<String, ScrapeInfo> Scrape(String url, String[] hashes)
        {
            Dictionary<String, ScrapeInfo> returnVal = new Dictionary<string, ScrapeInfo>();

            ValidateInput(url, hashes, ScraperType.UDP);

            Int32 trasactionId = Random.Next(0, 65535);

            UdpClient udpClient = new UdpClient(Tracker, Port)
                {
                    Client =
                        {
                            SendTimeout = Timeout*1000, 
                            ReceiveTimeout = Timeout*1000
                        }
                };

            byte[] sendBuf = _currentConnectionId.Concat(Pack.Int32(0)).Concat(Pack.Int32(trasactionId)).ToArray();
            udpClient.Send(sendBuf, sendBuf.Length);

            IPEndPoint endPoint = null;
            byte[] recBuf = udpClient.Receive(ref endPoint);

            if(recBuf == null) throw new NoNullAllowedException("udpClient failed to receive");
            if(recBuf.Length < 0) throw new InvalidOperationException("udpClient received no response");
            if(recBuf.Length < 16) throw new InvalidOperationException("udpClient did not receive entire response");

            UInt32 recAction = Unpack.UInt32(recBuf, 0, Unpack.Endianness.Big);
            UInt32 recTrasactionId = Unpack.UInt32(recBuf, 4, Unpack.Endianness.Big);

            if (recAction != 0 || recTrasactionId != trasactionId)
            {
                throw new Exception("Invalid response from tracker");
            }

            _currentConnectionId = CopyBytes(recBuf, 8, 8);

            byte[] hashBytes = new byte[0];
            hashBytes = hashes.Aggregate(hashBytes, (current, hash) => current.Concat(Pack.Hex(hash)).ToArray());

            int expectedLength = 8 + (12 * hashes.Length);

            sendBuf = _currentConnectionId.Concat(Pack.Int32(2)).Concat(Pack.Int32(trasactionId)).Concat(hashBytes).ToArray();
            udpClient.Send(sendBuf, sendBuf.Length);

            recBuf = udpClient.Receive(ref endPoint);

            if (recBuf == null) throw new NoNullAllowedException("udpClient failed to receive");
            if (recBuf.Length < 0) throw new InvalidOperationException("udpClient received no response");
            if (recBuf.Length < expectedLength) throw new InvalidOperationException("udpClient did not receive entire response");

            recAction = Unpack.UInt32(recBuf, 0, Unpack.Endianness.Big);
            recTrasactionId = Unpack.UInt32(recBuf, 4, Unpack.Endianness.Big);

            _currentConnectionId = CopyBytes(recBuf, 8, 8);

            if (recAction != 2 || recTrasactionId != trasactionId)
            {
                throw new Exception("Invalid response from tracker");
            }

            Int32 startIndex = 8;
            foreach (String hash in hashes)
            {
                UInt32 seeders = Unpack.UInt32(recBuf, startIndex, Unpack.Endianness.Big);
                UInt32 completed = Unpack.UInt32(recBuf, startIndex + 4, Unpack.Endianness.Big);
                UInt32 leachers = Unpack.UInt32(recBuf, startIndex + 8, Unpack.Endianness.Big);

                returnVal.Add(hash, new ScrapeInfo(seeders, completed, leachers, ScraperType.UDP));

                startIndex += 12;
            }

            udpClient.Close();

            return returnVal;
        }
示例#8
0
        /// <summary>
        /// Loads the input script file and parses it. Parses out everything outside of predeal/condition/produce/generate/action sections.
        /// </summary>
        /// <param name="file">Filename of the script.</param>
        public void loadFile(String file)
        {
            String[] contents = File.ReadAllLines(file);
            Dictionary <String, int> keyLines = new Dictionary <String, int>();

            String[] keywords = { "predeal", "condition", "generate", "produce", "action" };
            for (int i = 0; i < contents.Length; i++)
            {
                String line   = contents[i];
                int    lineNo = Array.IndexOf(keywords, line.Trim());
                if (lineNo >= 0)
                {
                    keyLines.Add(keywords[lineNo], i);
                }
            }
            keyLines = keyLines.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
            for (int i = 0; i < keyLines.Count; i++)
            {
                KeyValuePair <String, int> keyline = keyLines.ElementAt(i);
                String[] section = new String[contents.Length - keyline.Value];
                if (i + 1 < keyLines.Count)
                {
                    Array.Copy(contents, keyline.Value, section, 0, keyLines.ElementAt(i + 1).Value - keyline.Value);
                }
                else
                {
                    Array.Copy(contents, keyline.Value, section, 0, contents.Length - keyline.Value);
                }
                section[0] = Regex.Replace(section[0], "^" + keyline.Key, "").Trim();
                section    = section.Where(str => str != null && str.Trim().Length > 0).ToArray();
                switch (keyline.Key)
                {
                case "predeal":
                    String[] players = { "north", "east", "south", "west" };
                    char[]   suits   = { 'S', 'H', 'D', 'C' };
                    foreach (String l in section)
                    {
                        String line   = l.Trim();
                        int    player = Array.IndexOf(players, line.Substring(0, line.IndexOf(' ')));
                        if (player >= 0)
                        {
                            String[] chunks = Regex.Replace(line, "^" + players[player], "").Split(',');
                            String[] hand   = new String[4];
                            foreach (String chunk in chunks)
                            {
                                int suit = Array.IndexOf(suits, chunk.Trim().ToUpper()[0]);
                                if (suit >= 0)
                                {
                                    hand[suit] = chunk.Trim().Substring(1);
                                }
                            }
                            this.predeal.Add(players[player], hand);
                        }
                    }
                    break;

                case "condition":
                    this.condition = section.Aggregate((a, b) => a + "\n" + b);
                    break;

                case "generate":
                    if (section.Length > 1)
                    {
                        throw new Exception(Form1.GetResourceManager().GetString("DealerParser_errorTooManyGenerate", Form1.GetCulture()));
                    }
                    if (section.Length == 1)
                    {
                        try
                        {
                            this.generate = Convert.ToInt64(section[0]);
                        }
                        catch (OverflowException)
                        {
                            throw new Exception(Form1.GetResourceManager().GetString("DealerParser_errorGenerateOverflow", Form1.GetCulture()));
                        }
                    }
                    break;

                case "produce":
                    if (section.Length > 1)
                    {
                        throw new Exception(Form1.GetResourceManager().GetString("DealerParser_errorTooManyProduce", Form1.GetCulture()));
                    }
                    if (section.Length == 1)
                    {
                        try
                        {
                            this.produce = Convert.ToInt64(section[0]);
                        }
                        catch (OverflowException)
                        {
                            throw new Exception(Form1.GetResourceManager().GetString("DealerParser_errorProduceOverflow", Form1.GetCulture()));
                        }
                    }
                    break;

                case "action":
                    Regex           pattern = new Regex(@"(?<comma>,)|(?<open>\()|(?<close>\))|(?<token>[^,\(\)]*)");
                    MatchCollection matches = pattern.Matches(section.Aggregate((a, b) => a + b));
                    List <String>   tokens  = new List <String>();
                    foreach (Match match in matches)
                    {
                        int groupNo = 0;
                        foreach (Group group in match.Groups)
                        {
                            if (group.Success && groupNo > 0)
                            {
                                tokens.Add(group.Value);
                            }
                            groupNo++;
                        }
                    }
                    int           open          = 0;
                    List <String> actions       = new List <String>();
                    String        currentAction = "";
                    foreach (String token in tokens)
                    {
                        switch (token)
                        {
                        case "(":
                            open++;
                            currentAction += token;
                            break;

                        case ")":
                            open--;
                            currentAction += token;
                            break;

                        case ",":
                            if (open == 0)
                            {
                                actions.Add(currentAction.Trim());
                                currentAction = "";
                            }
                            else
                            {
                                currentAction += token;
                            }
                            break;

                        default:
                            currentAction += token;
                            break;
                        }
                    }
                    actions.Add(currentAction.Trim());
                    this.actions = actions.Where(s => s.StartsWith("average")).ToList();
                    break;
                }
            }
        }
示例#9
0
 public String wezTablicePustychBIN(String tablicaPustych)
 {
     return(String.Concat(tablicaPustych.Aggregate(new StringBuilder(), (builder, c) =>
                                                   builder.Append(Convert.ToString(Convert.ToInt32(c.ToString(), 16), 2).PadLeft(4, '0'))).ToString().Reverse()));
 }