Example #1
0
        private double[] Polyfit(double[] x, double[] y, int degree)
        {
            // Vandermonde matrix
            var v = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(x.Length, degree + 1);

            for (int i = 0; i < v.RowCount; i++)
            {
                for (int j = 0; j <= degree; j++)
                {
                    v[i, j] = Math.Pow(x[i], j);
                }
            }
            var         yv = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(y).ToColumnMatrix();
            QR <double> qr = v.QR(QRMethod.Full);
            // Math.Net doesn't have an "economy" QR, so:
            // cut R short to square upper triangle, then recompute Q
            var r = qr.R.SubMatrix(0, degree + 1, 0, degree + 1);
            var q = v.Multiply(r.Inverse());
            var p = r.Inverse().Multiply(q.TransposeThisAndMultiply(yv));

            return(p.Column(0).ToArray());
        }
Example #2
0
        public static void ReceiveMessage()
        {
            while (true)
            {
                try
                {
                    byte[]        data    = new byte[64];
                    StringBuilder builder = new StringBuilder();
                    int           bytes   = 0;
                    do
                    {
                        bytes = stream.Read(data, 0, data.Length);
                        builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
                    }while (stream.DataAvailable);

                    string        message = builder.ToString();
                    serverMessage sm      = JsonConvert.DeserializeObject <serverMessage>(message);
                    switch (sm.type)
                    {
                    case "messageerror":
                        Console.WriteLine("Ошибка, сообщение невозможно отправить: " + sm.data);
                        break;

                    case "usersonline":
                        string[] usersList = sm.data.Split('|');
                        Console.WriteLine("Список пользователей онлайн:");
                        for (int i = 1; i <= usersList.Length; i++)
                        {
                            Console.WriteLine(i.ToString() + ". " + usersList[i - 1]);
                        }
                        break;

                    case "rejectconnection":
                        Console.WriteLine("Невозможно установить соединение: " + sm.data);
                        break;

                    case "connections":
                        string[] onlineConnections = sm.data.Split('|');
                        if (onlineConnections[0] == "")
                        {
                            Console.WriteLine("Подключения отсутствуют");
                            break;
                        }
                        Console.WriteLine("Текущие подключения:");
                        for (int i = 0; i < onlineConnections.Length; i++)
                        {
                            Console.WriteLine(i + ". " + onlineConnections[i]);
                        }
                        break;

                    case "alreadydisconnected":
                        Console.WriteLine("Пользователь " + sm.data + " не подключен");
                        break;

                    case "removeconnection":
                        Console.WriteLine("Пользователь " + sm.data + " отключен");
                        break;

                    case "connectionremoved":
                        Console.WriteLine("Пользователь " + sm.data + " отключился");
                        break;

                    case "acceptconnection":
                        Console.WriteLine("Пользователь " + sm.data + " устанавливает соединение...");
                        clientMessage cm = new clientMessage()
                        {
                            type = "accept", data = sm.data
                        };
                        string json = JsonConvert.SerializeObject(cm);
                        Console.WriteLine("JSON :  " + json);
                        sendMessage(json);
                        break;

                    case "accept":
                        string[] keys               = sm.data.Split('|');
                        string   mySecretKey        = keys[1];
                        string   companionPublicKey = keys[2];
                        string[] mscdataString      = mySecretKey.Split(' ');
                        string[] cpkdataString      = companionPublicKey.Split(' ');
                        double[] mscdata            = new double[mscdataString.Length];
                        double[] cpkdata            = new double[cpkdataString.Length];
                        for (int i = 0; i < mscdataString.Length; i++)
                        {
                            mscdata[i] = Int32.Parse(mscdataString[i]);
                            cpkdata[i] = Int32.Parse(cpkdataString[i]);
                        }
                        Matrix <double> msc = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(mscdata.Length, 1, mscdata);
                        Matrix <double> cpk = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(cpkdata.Length, 1, cpkdata);
                        //Console.WriteLine("MY SEC: " + msc.ToString());
                        //Console.WriteLine("IT PUB: " + cpk.ToString());

                        msc = msc.Transpose();
                        Matrix <double> sKey = msc.Multiply(cpk);
                        sKey = sKey.Modulus(50);

                        commonSecretKey = (int)sKey[0, 0];
                        //Console.WriteLine("RES: " + Convert.ToString(commonSecretKey));


                        string     Digits  = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
                        byte[]     data123 = BitConverter.GetBytes(commonSecretKey);
                        BigInteger intData = 0;
                        for (int i = 0; i < data123.Length; i++)
                        {
                            intData = intData * 256 + data123[i];
                        }
                        string result = "";
                        while (intData > 0)
                        {
                            int remainder = (int)(intData % 58);
                            intData /= 58;
                            result   = Digits[remainder] + result;
                        }
                        for (int i = 0; i < data123.Length && data123[i] == 0; i++)
                        {
                            result = '1' + result;
                        }
                        csk = result;
                        Console.WriteLine("СГЕНЕРИРОВАН СЕКРЕТНЫЙ КЛЮЧ: " + csk);
                        Console.WriteLine("Установлена сессия с пользователем " + sm.name);
                        RC4Cipher newCipher  = new RC4Cipher(csk, 19);
                        session   newSession = new session()
                        {
                            name = sm.name, cipher = newCipher
                        };

                        addSession(newSession);

                        break;

                    default:
                        string  fp = sm.type.Split('|')[0];
                        string  sp = sm.type.Split('|')[1];
                        session rs = GetSession(sp);
                        if (fp == "message")
                        {
                            Console.WriteLine(sp + "(шифрованное): " + sm.data);
                            string decodemessage = rs.cipher.encode(sm.data);
                            Console.WriteLine(sp + "(дешифрованное): " + decodemessage);
                        }
                        break;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Подключение прервано! " + e);
                    Console.ReadLine();
                    Disconnect();
                }
            }
        }