Example #1
0
        private void AddAnalyse_Click_1(object sender, EventArgs e)
        {
            AnalyseModel addmodel  = new AnalyseModel();
            DateModel    datemodel = new DateModel();

            datemodel.Day   = Program.Current_Date.Date;
            datemodel.Time += Program.Current_Date.TimeOfDay;

            addmodel.Date_Id = date.Add(datemodel);
            try
            {
                int selected = ListView.SelectedIndices[0];
                addmodel.Type_Id   = Analyse_Type.SelectedIndex + 1;
                addmodel.Client_Id = long.Parse(ListView.Items[selected].SubItems[0].Text);
                addmodel.Result    = long.Parse(ResultText.Text);
                addmodel.Coment    = Coment.Text;
                analyse.Add(addmodel);
                Coment.Clear();
                ResultText.Clear();
                MessageBox.Show("Данные внесены");
            }
            catch
            {
                MessageBox.Show("Некоторые поля не выбраны");
            }
        }
Example #2
0
        public void AddTimeSpan()
        {
            var date    = new Date(2019, 11, 04);
            var newDate = date.Add(new TimeSpan(0, 26, 3, 0, 0));

            newDate.Should().Be(new Date(2019, 11, 05));
        }
Example #3
0
        void GetRewardDelayed(BasePlayer player)
        {
            PrintWarning("0");
            if (!Cooldowns.ContainsKey(player.userID))
            {
                Cooldowns.Add(player.userID, DateTime.Now);
            }
            DateTime Date;

            PrintWarning("1");
            Cooldowns.TryGetValue(player.userID, out Date);
            PrintWarning("2");
            PrintWarning(Date + " " + DateTime.Now);
            PrintWarning("3");
            if (Date > DateTime.Now)
            {
                PrintWarning("4");
                PrintToChat(player, "You can only use this command in " + Date.Subtract(DateTime.Now).Minutes + " minutes");
                return;
            }

            GetRewardsForThisPlayer(player);

            TimeSpan time     = new TimeSpan(0, 0, 15, 0);
            DateTime combined = Date.Add(time);

            Cooldowns[player.userID] = combined; // we are setting the cooldown.
        }
Example #4
0
        private void GetNodes(XmlNodeList nodes)
        {
            foreach (XmlNode node in nodes)
            {
                // Title
                ValidExtensions.AddIfNotNull(Title, GetTitle(node));


                // Date
                if (node.Name == "date")
                {
                    DateTime res = new DateTime();
                    DateTime.TryParse(node.InnerText, out res);
                    if (res != new DateTime())
                    {
                        Date.Add(res);
                    }
                }



                if (node.HasChildNodes)
                {
                    GetNodes(node.ChildNodes);
                }
            }
        }
Example #5
0
        private void PopulateDateCollection()
        {
            //populate months

            for (int i = 1; i < 13; i++)
            {
                months.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i).Substring(0, 3), CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i));
                Month.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i).Substring(0, 3));
            }

            //populate year
            for (int i = 1990; i < 2050; i++)
            {
                Year.Add(i.ToString());
            }

            //populate Days
            for (int i = 1; i <= DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month); i++)
            {
                if (i < 10)
                {
                    Day.Add("0" + i);
                }
                else
                {
                    Day.Add(i.ToString());
                }
            }

            Date.Add(Month);
            Date.Add(Day);
            Date.Add(Year);
        }
        protected override async Task Submit()
        {
            await RepositoryService.AddWeight(Weight, Date.Add(Time));

            MessagingCenter.Send(this, Messages.WeightsUpdated);
            await NavigationService.GoBackAsync();
        }
Example #7
0
 public void Add(Used_data used_Data)
 {
     Date.Add(used_Data.Date);
     Electric_value.Add(used_Data.Electric_value);
     Cold_water_value.Add(used_Data.Cold_water_value);
     Hot_water_value.Add(used_Data.Hot_water_value);
 }
Example #8
0
        // Populates months, years and days which will be available in the picker

        private void PopulateDateCollection()

        {
            for (var i = 1; i <= 12; i++)
            {
                if (!Months.ContainsKey(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i).Substring(0, 3)))
                {
                    Months.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i).Substring(0, 3), CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i));
                }

                Month.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i).Substring(0, 3));
            }

            // Available years = 2000-2025
            for (var i = 2000; i < 2025; i++)
            {
                Year.Add(i.ToString());
            }

            for (var i = 1; i <= DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month); i++)
            {
                if (i < 10)
                {
                    Day.Add("0" + i);
                }
                else
                {
                    Day.Add(i.ToString());
                }
            }

            Date.Add(Month);
            Date.Add(Day);
            Date.Add(Year);
        }
        protected override async Task Submit()
        {
            var newModel = new WeightModel(model.Id, Weight, Date.Add(Time));
            await RepositoryService.UpdateWeight(newModel);

            MessagingCenter.Send(this, Messages.WeightsUpdated);
            await NavigationService.GoBackAsync();
        }
Example #10
0
 public DateTime Add(TimeSpan value)
 {
     if (IsEmpty)
     {
         return(Date);
     }
     return(Date.Add(value));
 }
Example #11
0
 /// <summary>
 /// Toes the temp appointment obj.
 /// </summary>
 /// <returns></returns>
 public AppointmentObj ToAppointmentObj()
 {
     return(new AppointmentObj
     {
         Days = String.Empty,
         Busy = true,
         End = Date.Add(End),
         Start = Date.Add(Start)
     });
 }
Example #12
0
        public string GetReservationFromTime(DateTime time)
        {
            DateTime             reservationDate = Date.Add(time.TimeOfDay);
            ReservationViewModel reservation     = ReservationList.Find(x => x.StartDate.CompareTo(reservationDate) <= 0 && x.EndDate.CompareTo(reservationDate) > 0);
            string result = string.Empty;

            if (reservation != null)
            {
                UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);
                result = String.Format("<a href=\"{0}\">{1} {2}</a>", url.Action("Details", new { id = reservation.Id }), reservation.Member.FirstName, reservation.Member.LastName);
            }

            return(result);
        }
Example #13
0
        private static void AddDaysAndShow(Date original, int days, bool enhanced = true)
        {
            Date date = original.Clone();

            if (enhanced)
            {
                date.AddEnhanced(days);
            }
            else
            {
                date.Add(days);
            }

            Console.WriteLine($"{date} (Added {days} days)");
        }
        private void PopulateDateCollection()
        {
            try
            {
                //populate months
                for (int i = 1; i < 13; i++)
                {
                    //if (!Months.ContainsKey(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i).Substring(0, 3)))
                    //    Months.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i).Substring(0, 3), CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i));
                    //Month.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i).Substring(0, 3));

                    if (i < 10)
                    {
                        Month.Add("0" + i);
                    }
                    else
                    {
                        Month.Add(i.ToString());
                    }
                }
                //populate year
                for (int i = 1900; i < 2050; i++)
                {
                    Year.Add(i.ToString());
                }

                //populate Days
                for (int i = 1; i <= DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month); i++)
                {
                    if (i < 10)
                    {
                        Day.Add("0" + i);
                    }
                    else
                    {
                        Day.Add(i.ToString());
                    }
                }
                Date.Add(Day);
                Date.Add(Month);
                Date.Add(Year);
            }
            catch (Exception ex)
            {
            }
        }
Example #15
0
        private void PopulateDateCollection()
        {
            //populate months
            for (int i = 1; i < 13; i++)
            {
                Month.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i).Substring(0, 3));
            }

            //populate year
            for (int i = 1990; i < 2100; i++)
            {
                Year.Add(i.ToString());
            }

            Date.Add(Month);
            Date.Add(Year);
        }
Example #16
0
        private static void Main(string[] args)
        {
            Date date = new Date(2020, 6, 7);

            Console.WriteLine(date);

            AddDaysAndShow(date, 45, false);
            AddDaysAndShow(date, 180, false);

            Date date2      = date.Clone();
            int  add2Months = 8;
            int  add2Days   = 25;

            date2.Add(add2Months, add2Days);
            Console.WriteLine($"{date2} (Added {add2Months} months and {add2Days} days)");

            Date date3      = date.Clone();
            int  add3Years  = 2;
            int  add3Months = 3;
            int  add3Days   = 7;
            Date add3       = new Date(add3Years, add3Months, add3Days);

            date3.Add(add3);
            Console.WriteLine(
                $"{date3} (Added {add3Years} years, {add3Months} months, and {add3Days} days)");

            Console.WriteLine();
            Console.WriteLine("--- Enhanced version ---");
            Console.WriteLine(date);

            AddDaysAndShow(date, 15);
            AddDaysAndShow(date, 45);
            AddDaysAndShow(date, 180);
            AddDaysAndShow(date, 365);

            Date married = new Date(2018, 11, 5);

            Console.WriteLine($"I married my spouse on {married}.");
            int passed = 580;

            Console.WriteLine($"{passed} days have passed since then.");
            married.AddEnhanced(passed);
            Console.WriteLine($"It becomes {married} if I add the number of days.");
        }
Example #17
0
        private void populateDateCollection()
        {
            int startYear = 1990;
            int endYear   = DateTime.Now.Date.Year + 20;

            //populate months
            for (int i = 1; i < 13; i++)
            {
                Month.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i));
            }

            //populate year
            for (int i = startYear; i < endYear; i++)
            {
                Year.Add(i.ToString());
            }

            Date.Add(Year);
            Date.Add(Month);
        }
Example #18
0
        public void AddShouldThrowException()
        {
            var date = new Date();

            date.Add(null);
        }
Example #19
0
        private void LoadEpubMetaDataFromOpfFile(string opfFilePath)
        {
            ZipEntry zipEntry = _EpubFile.GetEntry(opfFilePath);

            if (zipEntry == null)
            {
                throw new Exception("Invalid epub file.");
            }

            XElement contentOpf;

            using (Stream zipStream = _EpubFile.GetInputStream(zipEntry))
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    byte[] buffer = new byte[4096]; // 4K is optimum
                    StreamUtils.Copy(zipStream, memoryStream, buffer);
                    memoryStream.Position = 0;
                    contentOpf            = XElement.Load(memoryStream);
                }
            }

            XNamespace xNamespace = contentOpf.Attribute("xmlns") != null
                ? contentOpf.Attribute("xmlns").Value
                : XNamespace.None;

            string uniqueIdentifier = contentOpf.Attribute("unique-identifier").Value;

            UUID = contentOpf.Elements(xNamespace + "metadata").Elements()
                   .FirstOrDefault(e =>
                                   e.Name.LocalName == "identifier" &&
                                   e.HasAttributes &&
                                   e.Attribute("id") != null &&
                                   e.Attribute("id").Value == uniqueIdentifier
                                   ).Value;
            foreach (
                var metadataElement in
                contentOpf.Element(xNamespace + "metadata").Elements().Where(e => e.Value.Trim() != string.Empty))
            {
                switch (metadataElement.Name.LocalName)
                {
                case "title":
                    Title.Add(metadataElement.Value);
                    break;

                case "creator":
                    Creator.Add(metadataElement.Value);
                    break;

                case "date":
                    var attribute = metadataElement.Attributes().FirstOrDefault(a => a.Name.LocalName == "event");
                    if (attribute != null)
                    {
                        Date.Add(new DateData(attribute.Value, metadataElement.Value));
                    }
                    break;

                case "publisher":
                    Publisher.Add(metadataElement.Value);
                    break;

                case "subject":
                    Subject.Add(metadataElement.Value);
                    break;

                case "source":
                    Source.Add(metadataElement.Value);
                    break;

                case "rights":
                    Rights.Add(metadataElement.Value);
                    break;

                case "description":
                    Description.Add(metadataElement.Value);
                    break;

                case "contributor":
                    Contributer.Add(metadataElement.Value);
                    break;

                case "type":
                    Type.Add(metadataElement.Value);
                    break;

                case "format":
                    Format.Add(metadataElement.Value);
                    break;

                case "identifier":
                    ID.Add(metadataElement.Value);
                    break;

                case "language":
                    Language.Add(metadataElement.Value);
                    break;

                case "relation":
                    Relation.Add(metadataElement.Value);
                    break;

                case "coverage":
                    Coverage.Add(metadataElement.Value);
                    break;
                }
            }

            LoadManifestSectionFromOpfFile(contentOpf, xNamespace);
        }
Example #20
0
        private void PopulateDateCollection()
        {
            //populate Days
            for (int i = 1; i <= DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month); i++)
            {
                if (i < 10)
                {
                    Day.Add("0" + i);
                }
                else
                {
                    Day.Add(i.ToString());
                }
            }

            //populate year
            for (int i = 1990; i < 2050; i++)
            {
                Year.Add(i.ToString());
            }


            //populate months

            for (int i = 1; i < 13; i++)
            {
                if (!Months.ContainsKey(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i).Substring(0, 3)))
                {
                    Months.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i).Substring(0, 3), CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i));
                }
                Month.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i).Substring(0, 3));
            }
            Date.Add(Year);
            Date.Add(Month);
            Date.Add(Day);

            for (int i = 1; i <= 24; i++)
            {
                if (i < 10)
                {
                    Hour.Add("0" + i.ToString());
                }
                else
                {
                    Hour.Add(i.ToString());
                }
            }
            for (int j = 0; j < 60; j++)
            {
                if (j < 10)
                {
                    Minute.Add("0" + j);
                }
                else
                {
                    Minute.Add(j.ToString());
                }
            }



            Date.Add(Hour);
            Date.Add(Minute);
        }
Example #21
0
        public void ProcessTTCN()
        {
            string        verdictcheck = "NONE";
            string        inputdate;
            string        inputverdict;
            string        inputversion;
            int           modifycount = 0;
            List <string> filecontent = new List <string>();

            try
            {
                filecontent = File.ReadAllLines(TCR).ToList <string>();        //create list and put each line into it
            }
            catch
            {
                return;
            }
            for (int i = 0; i < filecontent.Count; i++)
            {
                if (filecontent[i].Contains("NOT VALID for UE certification"))              //search through list for all the given values
                {
                    modifycount = modifycount | 1;
                }
                if (filecontent[i].Contains("NTT docomo DST"))
                {
                    int      index   = filecontent[i].IndexOf("NTT docomo DST");
                    string   removed = filecontent[i].Remove(0, index);
                    string[] nospace = removed.Split(' ');
                    inputversion = nospace[3];
                    inputversion = inputversion.Remove(0, 1);
                    if (string.IsNullOrEmpty(detail.Version))
                    {
                        Version.Add(inputversion);
                    }
                    else if (detail.Version.Contains(inputversion))
                    {
                        Version.Add("");
                    }
                    else
                    {
                        Version.Add("NG");
                    }
                }
                if (filecontent[i].Contains("Final Verdict: PASS"))
                {
                    verdictcheck = "PASS";
                }
                else if (filecontent[i].Contains("Final Verdict: FAIL"))
                {
                    verdictcheck = "FAIL";
                }
                else if (filecontent[i].Contains("Final Verdict: INCONC"))
                {
                    verdictcheck = "INCONC";
                }
            }
            try
            {
                filecontent = File.ReadAllLines(Summary).ToList <string>();
            }
            catch
            {
                return;
            }
            for (int x = 0; x < filecontent.Count; x++)
            {
                if (filecontent[x].Contains("Test:"))
                {
                    string[] temp = filecontent[x].Split('.');
                    Name.Add(temp[temp.Length - 1]);
                    int listlength = Name.Count;
                }
                if (filecontent[x].Contains("Result:"))
                {
                    string[] temp = filecontent[x].Split(':');
                    inputverdict = temp[temp.Length - 1].Trim();
                    if (verdictcheck != "")
                    {
                        if (inputverdict.Contains("PASS") && !verdictcheck.Contains("PASS"))
                        {
                            Verdict.Add("NONE");
                        }
                        else
                        {
                            Verdict.Add(inputverdict);
                        }
                    }
                    else
                    {
                        Verdict.Add(inputverdict);
                    }
                }
                if (filecontent[x].Contains("Date:"))
                {
                    if (filecontent[x].Contains('/'))
                    {
                        string[] temp = filecontent[x].Split(':');
                        inputdate = temp[temp.Length - 1].Trim();
                        temp      = inputdate.Split('/');
                        inputdate = temp[2] + '-' + temp[0] + '-' + temp[1];
                        Date.Add(inputdate);
                    }
                }
                if (filecontent[x].Contains("Invalid for UE certification"))
                {
                    modifycount = modifycount | 1;
                }
                if (filecontent[x].Contains("ENGINEERING"))
                {
                    modifycount = modifycount | 2;
                }
            }

            if (modifycount == 1 || modifycount == 3)
            {
                Modify.Add("MODIFIED");
            }
            else
            {
                Modify.Add(" ");
            }

            if (!string.IsNullOrEmpty(Sig))
            {
                SignatureVerifier versig = new SignatureVerifier(Sig);
                bool valid = versig.cmdverify();

                if (valid)
                {
                    Signature.Add("VALID");
                }
                else
                {
                    Signature.Add("INVALID");
                }
            }
        }
Example #22
0
        public void ProcessMLAPI()
        {
            string        inputname;
            string        inputdate;
            string        inputverdict;
            string        inputversion;
            int           modifycount = 0;
            List <string> filecontent = new List <string>();

            if (TCR.EndsWith(".sig"))
            {
                //do nothing
            }
            else
            {
                try
                {
                    filecontent = File.ReadAllLines(TCR).ToList <string>();       //create list to put each line into it
                }
                catch
                {
                    return;
                }
                for (int x = 0; x < filecontent.Count; x++)
                {
                    if (filecontent[x].Contains("TCR_TestCaseReport name"))                     //go through list to find values and put them in
                    {
                        string[] temp = filecontent[x].Split('=');
                        inputname = temp[1];
                        inputname = inputname.Substring(1, inputname.Length - 3);
                        string firstletter = inputname.Substring(0, 1);
                        if (firstletter != "I")
                        {
                            {
                                if (inputname.Length > 22)
                                {
                                    Name.Add(inputname.Substring(0, 22));
                                }
                                else
                                {
                                    Name.Add(inputname);
                                }
                            }
                        }
                    }
                    if (filecontent[x].Contains("TCR_ExecutionDate value"))
                    {
                        string[] temp = filecontent[x].Split('=');
                        inputdate = temp[1];
                        inputdate = inputdate.Substring(1, inputdate.Length - 4);
                        if (inputdate.Length > 10)
                        {
                            Date.Add(inputdate.Substring(0, inputdate.Length - 1));
                        }
                        else
                        {
                            Date.Add(inputdate);
                        }
                    }
                    if (filecontent[x].Contains("TCR_Verdict value"))
                    {
                        string[] temp = filecontent[x].Split('=');
                        inputverdict = temp[1];
                        inputverdict = inputverdict.Substring(1, inputverdict.Length - 4);
                        if (inputverdict.Length > 4)
                        {
                            Verdict.Add(inputverdict.Substring(0, inputverdict.Length - 1));
                        }
                        else
                        {
                            Verdict.Add(inputverdict);
                        }
                    }
                    if (filecontent[x].Contains("NOT VALID for UE certification"))
                    {
                        modifycount = modifycount | 1;
                    }
                    if (filecontent[x].Contains("ENGINEERING BuildID"))
                    {
                        modifycount = modifycount | 2;
                    }
                    if (modifycount == 1 || modifycount == 3)
                    {
                        Modify.Add("MODIFIED");
                    }
                    else
                    {
                        Modify.Add(" ");
                    }
                    if (filecontent[x].Contains("NTT DOCOMO DST"))
                    {
                        int      index   = filecontent[x].IndexOf("NTT DOCOMO DST");
                        string   removed = filecontent[x].Remove(0, index);
                        string[] nospace = removed.Split(' ');
                        inputversion = nospace[3];
                        inputversion = inputversion.Remove(0, 1);
                        if (string.IsNullOrEmpty(detail.Version))
                        {
                            Version.Add(inputversion);
                        }
                        else if (detail.Version == inputversion)
                        {
                            Version.Add("");
                        }
                        else
                        {
                            Version.Add("NG");
                        }
                    }
                }
            }
            if (!string.IsNullOrEmpty(Sig))
            {
                SignatureVerifier versig = new SignatureVerifier(Sig);
                bool valid = versig.cmdverify();

                if (valid)
                {
                    Signature.Add("VALID");
                }
                else
                {
                    Signature.Add("INVALID");
                }
            }
        }
Example #23
0
        static void Main(string[] args)
        {
            DateTime startTime = DateTime.Now;

            Option.Type optionType      = Option.Type.Put;
            double      underlyingPrice = 36;
            double      strikePrice     = 40;
            double      dividendYield   = 0.0;
            double      riskFreeRate    = 0.06;
            double      volatility      = 0.2;

            Date todaysDate = new Date(15, Month.May, 1998);

            Settings.instance().setEvaluationDate(todaysDate);

            Date settlementDate = new Date(17, Month.May, 1998);
            Date maturityDate   = new Date(17, Month.May, 1999);

            Calendar calendar = new TARGET();

            DateVector exerciseDates = new DateVector(4);

            for (int i = 1; i <= 4; i++)
            {
                Period forwardPeriod = new Period(3 * i, TimeUnit.Months);
                Date   forwardDate   = settlementDate.Add(forwardPeriod);
                exerciseDates.Add(forwardDate);
            }

            EuropeanExercise europeanExercise =
                new EuropeanExercise(maturityDate);
            BermudanExercise bermudanExercise =
                new BermudanExercise(exerciseDates);
            AmericanExercise americanExercise =
                new AmericanExercise(settlementDate, maturityDate);

            // bootstrap the yield/dividend/vol curves and create a
            // BlackScholesMerton stochastic process
            DayCounter dayCounter = new Actual365Fixed();
            YieldTermStructureHandle flatRateTSH =
                new YieldTermStructureHandle(
                    new FlatForward(settlementDate, riskFreeRate,
                                    dayCounter));
            YieldTermStructureHandle flatDividendTSH =
                new YieldTermStructureHandle(
                    new FlatForward(settlementDate, dividendYield,
                                    dayCounter));
            BlackVolTermStructureHandle flatVolTSH =
                new BlackVolTermStructureHandle(
                    new BlackConstantVol(settlementDate, calendar,
                                         volatility, dayCounter));

            QuoteHandle underlyingQuoteH =
                new QuoteHandle(new SimpleQuote(underlyingPrice));
            BlackScholesMertonProcess stochasticProcess =
                new BlackScholesMertonProcess(underlyingQuoteH,
                                              flatDividendTSH,
                                              flatRateTSH,
                                              flatVolTSH);

            PlainVanillaPayoff payoff =
                new PlainVanillaPayoff(optionType, strikePrice);

            // options
            VanillaOption europeanOption =
                new VanillaOption(payoff, europeanExercise);
            VanillaOption bermudanOption =
                new VanillaOption(payoff, bermudanExercise);
            VanillaOption americanOption =
                new VanillaOption(payoff, americanExercise);

            // report the parameters we are using
            ReportParameters(optionType, underlyingPrice, strikePrice,
                             dividendYield, riskFreeRate,
                             volatility, maturityDate);

            // write out the column headings
            ReportHeadings();

            #region Analytic Formulas

            // Black-Scholes for European
            try {
                europeanOption.setPricingEngine(
                    new AnalyticEuropeanEngine(stochasticProcess));
                ReportResults("Black-Scholes",
                              europeanOption.NPV(), null, null);
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Barone-Adesi and Whaley approximation for American
            try {
                americanOption.setPricingEngine(
                    new BaroneAdesiWhaleyEngine(stochasticProcess));
                ReportResults("Barone-Adesi/Whaley",
                              null, null, americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Bjerksund and Stensland approximation for American
            try {
                americanOption.setPricingEngine(
                    new BjerksundStenslandEngine(stochasticProcess));
                ReportResults("Bjerksund/Stensland",
                              null, null, americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Integral
            try {
                europeanOption.setPricingEngine(
                    new IntegralEngine(stochasticProcess));
                ReportResults("Integral",
                              europeanOption.NPV(), null, null);
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            uint timeSteps = 801;

            // Finite differences
            try {
                europeanOption.setPricingEngine(
                    new FDEuropeanEngine(stochasticProcess,
                                         timeSteps, timeSteps - 1));
                bermudanOption.setPricingEngine(
                    new FDBermudanEngine(stochasticProcess,
                                         timeSteps, timeSteps - 1));
                americanOption.setPricingEngine(
                    new FDAmericanEngine(stochasticProcess,
                                         timeSteps, timeSteps - 1));
                ReportResults("Finite differences",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            //Variance Gamma
            try
            {
                VarianceGammaProcess vgProcess = new VarianceGammaProcess(underlyingQuoteH,
                                                                          flatDividendTSH,
                                                                          flatRateTSH,
                                                                          volatility, 0.01, 0.0
                                                                          );
                europeanOption.setPricingEngine(
                    new VarianceGammaEngine(vgProcess));
                ReportResults("Variance-Gamma",
                              europeanOption.NPV(), null, null);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            #endregion Analytic Formulas

            #region Binomial Methods

            // Binomial Jarrow-Rudd
            try {
                europeanOption.setPricingEngine(
                    new BinomialJRVanillaEngine(stochasticProcess, timeSteps));
                bermudanOption.setPricingEngine(
                    new BinomialJRVanillaEngine(stochasticProcess, timeSteps));
                americanOption.setPricingEngine(
                    new BinomialJRVanillaEngine(stochasticProcess, timeSteps));
                ReportResults("Binomial Jarrow-Rudd",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Binomial Cox-Ross-Rubinstein
            try {
                europeanOption.setPricingEngine(
                    new BinomialCRRVanillaEngine(stochasticProcess, timeSteps));
                bermudanOption.setPricingEngine(
                    new BinomialCRRVanillaEngine(stochasticProcess, timeSteps));
                americanOption.setPricingEngine(
                    new BinomialCRRVanillaEngine(stochasticProcess, timeSteps));
                ReportResults("Binomial Cox-Ross-Rubinstein",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Additive Equiprobabilities
            try {
                europeanOption.setPricingEngine(
                    new BinomialEQPVanillaEngine(stochasticProcess, timeSteps));
                bermudanOption.setPricingEngine(
                    new BinomialEQPVanillaEngine(stochasticProcess, timeSteps));
                americanOption.setPricingEngine(
                    new BinomialEQPVanillaEngine(stochasticProcess, timeSteps));
                ReportResults("Additive Equiprobabilities",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Binomial Trigeorgis
            try {
                europeanOption.setPricingEngine(
                    new BinomialTrigeorgisVanillaEngine(stochasticProcess, timeSteps));
                bermudanOption.setPricingEngine(
                    new BinomialTrigeorgisVanillaEngine(stochasticProcess, timeSteps));
                americanOption.setPricingEngine(
                    new BinomialTrigeorgisVanillaEngine(stochasticProcess, timeSteps));
                ReportResults("Binomial Trigeorgis",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Binomial Tian
            try {
                europeanOption.setPricingEngine(
                    new BinomialTianVanillaEngine(stochasticProcess, timeSteps));
                bermudanOption.setPricingEngine(
                    new BinomialTianVanillaEngine(stochasticProcess, timeSteps));
                americanOption.setPricingEngine(
                    new BinomialTianVanillaEngine(stochasticProcess, timeSteps));
                ReportResults("Binomial Tian",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Binomial Leisen-Reimer
            try {
                europeanOption.setPricingEngine(
                    new BinomialLRVanillaEngine(stochasticProcess, timeSteps));
                bermudanOption.setPricingEngine(
                    new BinomialLRVanillaEngine(stochasticProcess, timeSteps));
                americanOption.setPricingEngine(
                    new BinomialLRVanillaEngine(stochasticProcess, timeSteps));
                ReportResults("Binomial Leisen-Reimer",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Binomial Joshi
            try {
                europeanOption.setPricingEngine(
                    new BinomialJ4VanillaEngine(stochasticProcess, timeSteps));
                bermudanOption.setPricingEngine(
                    new BinomialJ4VanillaEngine(stochasticProcess, timeSteps));
                americanOption.setPricingEngine(
                    new BinomialJ4VanillaEngine(stochasticProcess, timeSteps));
                ReportResults("Binomial Joshi",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            #endregion Binomial Methods

            #region Monte Carlo Methods

            // quantlib appears to use max numeric (int and real) values to test for 'null' (or rather 'default') values

            // MC (crude)
            try {
                int    mcTimeSteps       = 1;
                int    timeStepsPerYear  = int.MaxValue;
                bool   brownianBridge    = false;
                bool   antitheticVariate = false;
                int    requiredSamples   = int.MaxValue;
                double requiredTolerance = 0.02;
                int    maxSamples        = int.MaxValue;
                int    seed = 42;
                europeanOption.setPricingEngine(
                    new MCPREuropeanEngine(stochasticProcess,
                                           mcTimeSteps,
                                           timeStepsPerYear,
                                           brownianBridge,
                                           antitheticVariate,
                                           requiredSamples,
                                           requiredTolerance,
                                           maxSamples, seed));
                ReportResults("MC (crude)", europeanOption.NPV(), null, null);
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // MC (Sobol)
            try {
                int    mcTimeSteps       = 1;
                int    timeStepsPerYear  = int.MaxValue;
                bool   brownianBridge    = false;
                bool   antitheticVariate = false;
                int    requiredSamples   = 32768; // 2^15
                double requiredTolerance = double.MaxValue;
                int    maxSamples        = int.MaxValue;
                int    seed = 0;
                europeanOption.setPricingEngine(
                    new MCLDEuropeanEngine(stochasticProcess,
                                           mcTimeSteps,
                                           timeStepsPerYear,
                                           brownianBridge,
                                           antitheticVariate,
                                           requiredSamples,
                                           requiredTolerance,
                                           maxSamples, seed));
                ReportResults("MC (Sobol)", europeanOption.NPV(), null, null);
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            #endregion Monte Carlo Methods

            DateTime endTime = DateTime.Now;
            TimeSpan delta   = endTime - startTime;
            Console.WriteLine();
            Console.WriteLine("Run completed in {0} s", delta.TotalSeconds);
            Console.WriteLine();
        }
Example #24
0
        public IActionResult OnPost()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            ResolutionsSystem rs = new ResolutionsSystem();

            Classes.Client client = new Client();
            if (MiddleName == null || MiddleName == "")
            {
                client = rs.GetClient(FirstName, LastName);
            }
            else
            {
                client = rs.GetClient(FirstName, MiddleName, LastName);
            }

            int counsellorID;

            SqlCode code;

            if (client.ClientID == null)
            {
                //client doesn't exist
                System.Diagnostics.Debug.WriteLine("Client doesn't exist");
                //client doesn't exist, so insert a new client into the database
                code = rs.CreateClient(GetClient());
                if (code == SqlCode.Failure)
                {
                    System.Diagnostics.Debug.WriteLine("Failed to create client");

                    Message = "Failed to create client";
                    return(Page());
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Client exists");
            }


            //client now exists

            if (MiddleName == null || MiddleName == "")
            {
                client = rs.GetClient(FirstName, LastName);
            }
            else
            {
                client = rs.GetClient(FirstName, MiddleName, LastName);
            }

            counsellorID = SelectedID;

            System.Diagnostics.Debug.WriteLine($"TimeSelected: {TimeSelected}");
            //TimeSpan appointmentTime = TimeSpan.Parse(TimeSelected);
            //DateTime appointmentDateTime = Date.Add(appointmentTime);
            DateTime appointmentDateTime = Date.Add(Time);

            Classes.Appointment newAppointment = new Classes.Appointment()
            {
                AppointmentDate = appointmentDateTime,
                ClientID        = (int)client.ClientID,
                CounsellorID    = counsellorID
            };

            code = rs.BookAppointment(newAppointment);

            if (code == SqlCode.Failure)
            {
                Message = "Failed to create appointment";
                return(Page());
            }

            return(new RedirectToPageResult("Index"));
        }
Example #25
0
        private void LoadEpubMetaDataFromOpfFile(string opfFilePath)
        {
            ZipEntry zipEntry = _EpubFile.Entries.FirstOrDefault(e => e.FileName.Equals(opfFilePath, StringComparison.InvariantCultureIgnoreCase));

            if (zipEntry == null)
            {
                throw new Exception("Invalid epub file.");
            }

            XElement contentOpf;

            using (MemoryStream memoryStream = new MemoryStream())
            {
                zipEntry.Extract(memoryStream);
                // Fix buggy "<?xml verison="1.1"?>
                // See http://stackoverflow.com/questions/912440/xdocument-cant-load-xml-with-version-1-1-in-c-sharp-linq
                byte[] b = memoryStream.ToArray();
                for (int i = 0; i < 50; i++)
                {
                    // Check for version="1.1" and replace if found
                    if (b[i] == 0x76 && b[i + 1] == 0x65 && b[i + 2] == 0x72 && b[i + 3] == 0x73 && b[i + 4] == 0x69 && b[i + 5] == 0x6F && b[i + 6] == 0x6E &&
                        b[i + 7] == 0x3D && b[i + 8] == 0x22 && b[i + 9] == 0x31 && b[i + 10] == 0x2E && b[i + 11] == 0x31)
                    {
                        b[i + 11] = 0x30;
                    }
                }
                using (MemoryStream fixedStream = new MemoryStream(b))
                {
                    contentOpf = XElement.Load(fixedStream);
                }
                b = null;
            }

            XNamespace xNamespace = contentOpf.Attribute("xmlns") != null?contentOpf.Attribute("xmlns").Value : XNamespace.None;

            string uniqueIdentifier = contentOpf.Attribute("unique-identifier").Value;

            try { UUID = contentOpf.Elements(xNamespace + "metadata").Elements().FirstOrDefault(e => e.Name.LocalName == "identifier" && e.Attributes("id").FirstOrDefault() != null && e.Attribute("id").Value == uniqueIdentifier).Value; }
            catch { }
            foreach (var metadataElement in contentOpf.Elements(xNamespace + "metadata").Elements().Where(e => e.Value.Trim() != string.Empty))
            {
                switch (metadataElement.Name.LocalName)
                {
                case "title": Title.Add(metadataElement.Value); break;

                case "creator": Creator.Add(metadataElement.Value); break;

                case "date":
                    var attribute = metadataElement.Attributes().FirstOrDefault(a => a.Name.LocalName == "event");
                    if (attribute != null)
                    {
                        Date.Add(new DateData(attribute.Value, metadataElement.Value));
                    }
                    break;

                case "publisher": Publisher.Add(metadataElement.Value); break;

                case "subject": Subject.Add(metadataElement.Value); break;

                case "source": Source.Add(metadataElement.Value); break;

                case "rights": Rights.Add(metadataElement.Value); break;

                case "description": Description.Add(metadataElement.Value); break;

                case "contributor": Contributer.Add(metadataElement.Value); break;

                case "type": Type.Add(metadataElement.Value); break;

                case "format": Format.Add(metadataElement.Value); break;

                case "identifier": ID.Add(metadataElement.Value); break;

                case "language": Language.Add(metadataElement.Value); break;

                case "relation": Relation.Add(metadataElement.Value); break;

                case "coverage": Coverage.Add(metadataElement.Value); break;
                }
            }

            LoadManifestSectionFromOpfFile(contentOpf, xNamespace);
        }
Example #26
0
 public DateTime Value(TimeSpan time)
 {
     return(Date.Add(time));
 }
Example #27
0
        protected override void OnBarUpdate()
        {
            DateTime dtBegin = DateTime.MaxValue;

            switch (IntervalType)
            {
            case IntervalType.Sec:
                dtBegin = MinBar.Time.Date.AddHours(MinBar.Time.Hour).AddMinutes(MinBar.Time.Minute).AddSeconds(MinBar.Time.Second / Interval * Interval);
                break;

            case IntervalType.Min:
                dtBegin = MinBar.Time.Date.AddHours(MinBar.Time.Hour).AddMinutes(MinBar.Time.Minute / Interval * Interval);
                break;

            case IntervalType.Hour:
                dtBegin = MinBar.Time.Date.AddHours(MinBar.Time.Hour / Interval * Interval);
                break;

            case IntervalType.Day:
                dtBegin = DateTime.ParseExact(MinBar.TradingDay.ToString(), "yyyyMMdd", null);
                break;

            case IntervalType.Week:
                dtBegin = DateTime.ParseExact(MinBar.TradingDay.ToString(), "yyyyMMdd", null);
                dtBegin = dtBegin.Date.AddDays(1 - (byte)dtBegin.DayOfWeek);
                break;

            case IntervalType.Month:
                dtBegin = DateTime.ParseExact(MinBar.TradingDay.ToString(), "yyyyMMdd", null);
                dtBegin = new DateTime(dtBegin.Year, dtBegin.Month, 1);
                break;

            case IntervalType.Year:
                dtBegin = DateTime.ParseExact(MinBar.TradingDay.ToString(), "yyyyMMdd", null);
                dtBegin = new DateTime(dtBegin.Year, 1, 1);
                break;

            default:
                throw new Exception("参数错误");
            }
            if (bar == null)             //首次调用
            {
                bar = new Bar
                {
                    Time   = dtBegin,
                    Volume = MinBar.Volume,                     // kOld.preVol == 0 ? 0 : _tick.Volume - kOld.preVol;
                };
                bar.High  = MinBar.High;
                bar.Low   = MinBar.Low;
                bar.Open  = MinBar.Open;
                bar.Close = MinBar.Close;
                newbar    = true;
            }
            else
            {
                if (bar.Time == dtBegin)                 //在当前K线范围内
                {
                    newbar     = false;
                    bar.High   = Math.Max(bar.High, MinBar.High);
                    bar.Low    = Math.Min(bar.Low, MinBar.Low);
                    bar.Close  = MinBar.Close;
                    bar.Volume = bar.Volume + MinBar.Volume;
                }
                else if (dtBegin > bar.Time)
                {
                    newbar     = true;
                    bar.Time   = dtBegin;
                    bar.Volume = MinBar.Volume;
                    bar.Open   = MinBar.Open;
                    bar.High   = MinBar.High;
                    bar.Low    = MinBar.Low;
                    bar.Close  = MinBar.Close;
                }
            }

            if (newbar)
            {
                Date.Add(double.Parse(bar.Time.ToString("yyyyMMdd")));
                Time.Add(double.Parse(bar.Time.ToString("0.HHmmss")));
                Open.Add(bar.Open);
                High.Add(bar.High);
                Low.Add(bar.Low);
                Close.Add(bar.Close);
                Volume.Add(bar.Volume);
            }
            else
            {
                High[0]   = bar.High;
                Low[0]    = bar.Low;
                Close[0]  = bar.Close;
                Volume[0] = bar.Volume;
            }
        }
Example #28
0
 public string GetLocationString()
 {
     return(string.Format("{0}, {1}-{2}, {3}", Globals.CurrentCulture.DateTimeFormat.GetDayName(Date.DayOfWeek),
                          DateTimeHelper.Round(Date).ToString("HH:mm"),
                          DateTimeHelper.Round((Date.Add(Duration))).ToString("HH:mm"), LocationString));
 }
Example #29
0
        protected override void OnBarUpdate()
        {
            DateTime dtBegin = DateTime.MaxValue;

            switch (IntervalType)
            {
            case EnumIntervalType.Sec:
                dtBegin = MinBar.D.Date.AddHours(MinBar.D.Hour).AddMinutes(MinBar.D.Minute).AddSeconds(MinBar.D.Second / Interval * Interval);
                break;

            case EnumIntervalType.Min:
                dtBegin = MinBar.D.Date.AddHours(MinBar.D.Hour).AddMinutes(MinBar.D.Minute / Interval * Interval);
                break;

            case EnumIntervalType.Hour:
                dtBegin = MinBar.D.Date.AddHours(MinBar.D.Hour / Interval * Interval);
                break;

            case EnumIntervalType.Day:
                dtBegin = DateTime.ParseExact(MinBar.TradingDay.ToString(), "yyyyMMdd", null);
                break;

            case EnumIntervalType.Week:
                dtBegin = DateTime.ParseExact(MinBar.TradingDay.ToString(), "yyyyMMdd", null);
                dtBegin = dtBegin.Date.AddDays(1 - (byte)dtBegin.DayOfWeek);
                break;

            case EnumIntervalType.Month:
                dtBegin = DateTime.ParseExact(MinBar.TradingDay.ToString(), "yyyyMMdd", null);
                dtBegin = new DateTime(dtBegin.Year, dtBegin.Month, 1);
                break;

            case EnumIntervalType.Year:
                dtBegin = DateTime.ParseExact(MinBar.TradingDay.ToString(), "yyyyMMdd", null);
                dtBegin = new DateTime(dtBegin.Year, 1, 1);
                break;

            default:
                throw new Exception("参数错误");
            }
            if (bar == null)             //首次调用
            {
                bar = new Bar
                {
                    D = dtBegin,
                    I = MinBar.I,
                    V = MinBar.V,                     // kOld.preVol == 0 ? 0 : _tick.Volume - kOld.preVol;
                };
                bar.H  = MinBar.H;
                bar.L  = MinBar.L;
                bar.O  = MinBar.O;
                bar.C  = MinBar.C;
                newbar = true;
            }
            else
            {
                if (bar.D == dtBegin)                 //在当前K线范围内
                {
                    newbar = false;
                    bar.H  = Math.Max(bar.H, MinBar.H);
                    bar.L  = Math.Min(bar.L, MinBar.L);
                    bar.C  = MinBar.C;
                    bar.V  = bar.V + MinBar.V;
                    bar.I  = MinBar.I;
                }
                else if (dtBegin > bar.D)
                {
                    newbar = true;
                    bar.D  = dtBegin;
                    bar.V  = MinBar.V;
                    bar.I  = MinBar.I;
                    bar.O  = MinBar.O;
                    bar.H  = MinBar.H;
                    bar.L  = MinBar.L;
                    bar.C  = MinBar.C;
                }
            }

            if (newbar)
            {
                Date.Add(double.Parse(bar.D.ToString("yyyyMMdd")));
                Time.Add(double.Parse(bar.D.ToString("0.HHmmss")));
                Open.Add(bar.O);
                High.Add(bar.H);
                Low.Add(bar.L);
                Close.Add(bar.C);
                Volume.Add(bar.V);
                OpenInterest.Add(bar.I);
            }
            else
            {
                High[0]         = bar.H;
                Low[0]          = bar.L;
                Close[0]        = bar.C;
                Volume[0]       = bar.V;
                OpenInterest[0] = bar.I;
            }
        }
Example #30
0
        private void LoadEpubMetaDataFromOpfFile(string opfFilePath)
        {
            ZipEntry zipEntry = _EpubFile.Entries.FirstOrDefault(e => e.FileName.Equals(opfFilePath, StringComparison.InvariantCultureIgnoreCase));

            if (zipEntry == null)
            {
                throw new Exception("Invalid epub file.");
            }

            XElement contentOpf;

            using (MemoryStream memoryStream = new MemoryStream()) {
                zipEntry.Extract(memoryStream);
                memoryStream.Position = 0;
                contentOpf            = XElement.Load(memoryStream);
            }

            XNamespace xNamespace = contentOpf.Attribute("xmlns") != null?contentOpf.Attribute("xmlns").Value : XNamespace.None;

            string uniqueIdentifier = contentOpf.Attribute("unique-identifier").Value;

            try
            {
                UUID = contentOpf.Elements(xNamespace + "metadata").Elements().FirstOrDefault(e => e.Name.LocalName == "identifier" && e.Attribute("id").Value == uniqueIdentifier).Value;
            }
            catch { }
            foreach (var metadataElement in contentOpf.Elements(xNamespace + "metadata").Elements().Where(e => e.Value.Trim() != string.Empty))
            {
                switch (metadataElement.Name.LocalName)
                {
                case "title": Title.Add(metadataElement.Value); break;

                case "creator": Creator.Add(metadataElement.Value); break;

                case "date":
                    var attribute = metadataElement.Attributes().FirstOrDefault(a => a.Name.LocalName == "event");
                    if (attribute != null)
                    {
                        Date.Add(new DateData(attribute.Value, metadataElement.Value));
                    }
                    break;

                case "publisher": Publisher.Add(metadataElement.Value); break;

                case "subject": Subject.Add(metadataElement.Value); break;

                case "source": Source.Add(metadataElement.Value); break;

                case "rights": Rights.Add(metadataElement.Value); break;

                case "description": Description.Add(metadataElement.Value); break;

                case "contributor": Contributer.Add(metadataElement.Value); break;

                case "type": Type.Add(metadataElement.Value); break;

                case "format": Format.Add(metadataElement.Value); break;

                case "identifier": ID.Add(metadataElement.Value); break;

                case "language": Language.Add(metadataElement.Value); break;

                case "relation": Relation.Add(metadataElement.Value); break;

                case "coverage": Coverage.Add(metadataElement.Value); break;
                }
            }

            LoadManifestSectionFromOpfFile(contentOpf, xNamespace);
        }