public void CalcualteStandardDeviationUsingValidData_ReturnsExpected()
        {
            var testData = new Double[6] { 1, 2, 3, 4, 5, 6 };
            var calculations = new Calculations();
            var standadDeviation = calculations.StandardDeviation(testData);

            var expected = 1.707825128;
            var actual =  Math.Round(standadDeviation,9);
            Assert.AreEqual(expected, actual);
        }
        public void CalculateMovingStandardDeviationUsingValidData_ReturnsExpected()
        {
            var testData = new Double[6] { 1, 2, 3, 4, 5, 6 };
            var calculations = new Calculations();
            var movingStandardDeviation = calculations.MovingStandardDeviation(testData,3);

            var expected = 4;
            var actual = new List<Double>(movingStandardDeviation).Count;
            Assert.AreEqual(expected, actual);
        }
        public void CalculateBollingerBandsUsingValidData_ReturnsExpected()
        {
            var testData = new Double[6] { 1, 2, 3, 4, 5, 6 };
            var calculations = new Calculations();
            var bollingerBands = calculations.BollingerBands(testData,3);

            var expected = 4;
            var actual = new List<Tuple<Double,Double>>(bollingerBands).Count;
            Assert.AreEqual(expected, actual);
        }
        public void CalculateVarianceUsingValidData_ReturnsExpected()
        {
            var testData = new Double[6] { 1, 2, 3, 4, 5, 6 };
            var calculations = new Calculations();
            var variance = calculations.Variance(testData);

            var expected = 2.916666667;
            var actual = Math.Round(variance, 9);
            Assert.AreEqual(expected, actual);
        }
Beispiel #5
0
        /// <summary>
        /// Init Guess set up
        /// Get user details or creat them
        /// Old guesses
        /// New image
        /// </summary>
        /// <param name="userGuid">Can be null if so new user is created</param>
        /// <returns></returns>
        public async Task <ActionResult> GuessNoFeedback(string userGuid, byte?phase = 0)
        {
            if (_session._isLoggedin)
            {
                //create if no guid
                var getUserRequest = new HttpRequestMessage(HttpMethod.Post, "/api/user");

                //Get if exists
                if (!string.IsNullOrEmpty(userGuid) && new Guid(userGuid) != Guid.Empty)
                {
                    getUserRequest = new HttpRequestMessage(HttpMethod.Get, string.Format("/api/user/hash/{0}", userGuid));
                }

                var getUserResponse = await _db.BuildApiResponse <UserModel>(getUserRequest, _session._accessToken);

                GuessViewModel model = new GuessViewModel();
                if (getUserResponse.Status == HttpStatusCode.OK)
                {
                    model.UserHash = getUserResponse.Content.HashUser.Value;
                    model.UserId   = getUserResponse.Content.UserId;

                    //returning details
                    model.ReturningUser  = (getUserResponse.Content.Guesses != null && getUserResponse.Content.Guesses.Any());
                    model.ReturningTimer = (getUserResponse.Content.TimePhase1.HasValue)
                        ? ((getUserResponse.Content.TimePhase1.Value.Hour * 3600) +
                           (getUserResponse.Content.TimePhase1.Value.Minute * 60) + (getUserResponse.Content.TimePhase1.Value.Second))
                        : 0;

                    //Login logging
                    var updateLoginTokenRequest  = new HttpRequestMessage(HttpMethod.Post, string.Format("/api/token/{0}/{1}", _session._accessId, model.UserHash.ToString()));
                    var updateLoginTokenResponse = await _db.BuildApiResponse <Token>(updateLoginTokenRequest, _session._accessToken);

                    //Past guesses
                    var usersGuessRequest = new HttpRequestMessage(HttpMethod.Get,
                                                                   string.Format("/api/usersGuess/{0}/{1}", getUserResponse.Content.UserId, phase));
                    var usersGuessResponse = await _db.BuildApiResponse <List <UserGuessModel> >(usersGuessRequest, _session._accessToken);


                    model.FinalPercentage = getUserResponse.Content.Guesses != null && getUserResponse.Content.Guesses.Any() && usersGuessResponse.Content.Count >= 10
                        ? (decimal)Calculations.FindAverageDifferenceOfList(usersGuessResponse.Content.OrderBy(x => x.UsersGuessId).Skip(usersGuessResponse.Content.Count - 10).ToList())
                        : (decimal)0.0;


                    model.ImagesUsed = usersGuessResponse.Content.Count;
                    model.Phase      = (byte)(phase.HasValue ? phase.Value : 0);

                    //Get random new image that hasn't been used
                    var binding = new RandomImageBinding
                    {
                        PreviousImageIds = getUserResponse.Content.Guesses != null && getUserResponse.Content.Guesses.Any()
                            ? getUserResponse.Content.Guesses.Select(x => x.ImageId).ToArray()
                            : new int[0],
                        ReturnRandom = true
                    };
                    var image = await GetRandomImage(binding);


                    if (image != null)
                    {
                        model.CurrentCloudinaryUrl = Common.BuildCloudinaryUrl(image.FileName);
                        model.CurrentImageId       = image.ImageId;

                        return(View(model));
                    }
                }

                return(RedirectToAction("Errorpage", "Home"));
            }

            return(RedirectToAction("Login", "Account"));
        }
Beispiel #6
0
        private void BuildControls()
        {
            if (CheckBoxes == null)
            {
                CheckBoxes = new Dictionary <Buff, CheckBox>();
            }
            else
            {
                CheckBoxes.Clear();
            }

            if (FindParent == null)
            {
                FindParent = new Dictionary <Buff, Buff>();
            }
            else
            {
                FindParent.Clear();
            }

            BuffStack.Children.Clear();
            Dictionary <string, Grid /*GroupBox*/> buffGroups = new Dictionary <string, Grid /*GroupBox*/>();

            if (CalculationsHunter.RelevantPetBuffs != null)
            {
                foreach (Buff b in CalculationsHunter.RelevantPetBuffs)
                {
                    Grid /*GroupBox*/ gb;
                    if (buffGroups.ContainsKey(b.Group))
                    {
                        gb = buffGroups[b.Group];
                    }
                    else
                    {
                        gb = new Grid/*GroupBox*/ ();
                        //gb.Header = b.Group;
                        StackPanel sp = new StackPanel();
                        gb.Children.Add(/*Content =*/ sp);
                        BuffStack.Children.Add(gb);
                        buffGroups[b.Group] = gb;
                    }
                    CheckBox buffCb = new CheckBox();
                    if (Rawr.Properties.GeneralSettings.Default.DisplayBuffSource && b.Source != null)
                    {
                        buffCb.Content = b.Name + " (" + b.Source + ")";
                    }
                    else
                    {
                        buffCb.Content = b.Name;
                    }
                    ToolTipService.SetToolTip(buffCb, Calculations.GetRelevantStats(b.Stats).ToString());
                    buffCb.Checked   += new RoutedEventHandler(buffCb_CheckedChange);
                    buffCb.Unchecked += new RoutedEventHandler(buffCb_CheckedChange);
                    buffCb.Tag        = b;
                    ((StackPanel)gb.Children[0] /*Content*/).Children.Add(buffCb);
                    CheckBoxes[b] = buffCb;

                    foreach (Buff i in b.Improvements)
                    {
                        buffCb = new CheckBox();
                        if (Rawr.Properties.GeneralSettings.Default.DisplayBuffSource && i.Source != null)
                        {
                            buffCb.Content = i.Name + " (" + i.Source + ")";
                        }
                        else
                        {
                            buffCb.Content = i.Name;
                        }
                        ToolTipService.SetToolTip(buffCb, Calculations.GetRelevantStats(i.Stats).ToString());
                        buffCb.Margin     = new Thickness(16, 0, 0, 0);
                        buffCb.Checked   += new RoutedEventHandler(buffCb_CheckedChange);
                        buffCb.Unchecked += new RoutedEventHandler(buffCb_CheckedChange);
                        buffCb.Tag        = i;
                        CheckBoxes[i]     = buffCb;
                        FindParent[i]     = b;
                        ((StackPanel)gb.Children[0] /*Content*/).Children.Add(buffCb);
                    }
                }
            }
        }
        public void Calculator_DivisionByZero_MustReturnException()
        {
            var exception = Assert.Throws <DivideByZeroException>(() => Calculations.Division(3, 1));

            Assert.Equal("Attempted to divide by zero.", exception.Message);
        }
        public int AdjustDrop(int nDrop, int nAtkLev, int nDefLev)
        {
            if (nAtkLev > 120)
            {
                nAtkLev = 120;
            }

            if (nAtkLev - nDefLev > 0)
            {
                int nDeltaLev = nAtkLev - nDefLev;
                if (1 < nAtkLev && nAtkLev <= 19)
                {
                    if (nDeltaLev < 3)
                    {
                        ;
                    }
                    else if (3 <= nDeltaLev && nDeltaLev < 6)
                    {
                        nDrop = nDrop / 5;
                    }
                    else
                    {
                        nDrop = nDrop / 10;
                    }
                }
                else if (19 < nAtkLev && nAtkLev <= 49)
                {
                    if (nDeltaLev < 5)
                    {
                        ;
                    }
                    else if (5 <= nDeltaLev && nDeltaLev < 10)
                    {
                        nDrop = nDrop / 5;
                    }
                    else
                    {
                        nDrop = nDrop / 10;
                    }
                }
                else if (49 < nAtkLev && nAtkLev <= 85)
                {
                    if (nDeltaLev < 4)
                    {
                        ;
                    }
                    else if (4 <= nDeltaLev && nDeltaLev < 8)
                    {
                        nDrop = nDrop / 5;
                    }
                    else
                    {
                        nDrop = nDrop / 10;
                    }
                }
                else if (85 < nAtkLev && nAtkLev <= 112)
                {
                    if (nDeltaLev < 3)
                    {
                        ;
                    }
                    else if (3 <= nDeltaLev && nDeltaLev < 6)
                    {
                        nDrop = nDrop / 5;
                    }
                    else
                    {
                        nDrop = nDrop / 10;
                    }
                }
                else if (112 < nAtkLev && nAtkLev <= 120)
                {
                    if (nDeltaLev < 2)
                    {
                        ;
                    }
                    else if (2 <= nDeltaLev && nDeltaLev < 4)
                    {
                        nDrop = nDrop / 5;
                    }
                    else
                    {
                        nDrop = nDrop / 10;
                    }
                }
                else if (120 < nAtkLev && nAtkLev <= 130)
                {
                    if (nDeltaLev < 2)
                    {
                        ;
                    }
                    else if (2 <= nDeltaLev && nDeltaLev < 4)
                    {
                        nDrop = nDrop / 5;
                    }
                    else
                    {
                        nDrop = nDrop / 10;
                    }
                }
                else if (130 < nAtkLev && nAtkLev <= 140)
                {
                    if (nDeltaLev < 2)
                    {
                        ;
                    }
                    else if (2 <= nDeltaLev && nDeltaLev < 4)
                    {
                        nDrop = nDrop / 5;
                    }
                    else
                    {
                        nDrop = nDrop / 10;
                    }
                }
            }

            return(Calculations.CutTrail(0, nDrop));
        }
        public int CalcMagicPower(IRole pAtker, IRole pTarget, int pAdjustAtk, ref InteractionEffect pSpecial) // /*=0*/, ref InteractionEffect special)
        {
            if (pTarget is Character)
            {
                Character pUser = pTarget as Character;
                if (pUser.QueryTransformation != null && pUser.QueryTransformation.Lookface == 223)
                {
                    return(1);
                }
            }

            if (m_pOwner.Map.IsLineSkillMap())
            {
                return(1);
            }

            if (pTarget.QueryStatus(FlagInt.VORTEX) != null)
            {
                return(1);
            }

            int nAtk = pAtker.MagicAttack;

            if (pAtker.Magics.QueryMagic() != null)
            {
                float tPower = pAtker.Magics.QueryMagic().QueryPower();
                if (tPower > 30000)
                {
                    tPower = (tPower - 30000) / 100f;
                    nAtk   = (int)(nAtk * tPower);
                }
                else
                {
                    nAtk += (short)tPower;
                }
            }

            int nDef = pTarget.MagicDefense; // * (1 + (pTarget.Magic / 100));

            if (pTarget is Character)
            {
                int nCounter = (int)(pTarget.Counteraction / 10f);
                int nPene    = (int)(pAtker.Penetration / 100f);
                if (nCounter < nPene)
                {
                    if (!Calculations.ChanceCalc((nPene - nCounter)))
                    {
                        Character pUser = pTarget as Character;
                        nDef = (int)(nDef * (1 + (pUser.MagicDefenseBonus / 100f)));
                    }
                    else
                    {
                        nAtk      = (int)(nAtk * 1.25f);
                        pSpecial |= InteractionEffect.BREAKTHROUGH;
                    }
                }
                else
                {
                    Character pUser = pTarget as Character;
                    nDef = (int)(nDef * (1 + (pUser.MagicDefenseBonus / 100f)));
                }
            }

            int nDamage = (int)((nAtk - nDef) * (1f - (pTarget.GetReduceDamage() / 100f)));

            nDamage = (int)(nDamage * (1f - (pTarget.GetTortoiseGemEffect() / 100f)));

            if (pAtker is Character && pTarget.IsMonster())
            {
                nDamage = CalcDamageUser2Monster(nDamage, nDef, pAtker.Level, pTarget.Level);
                nDamage = pTarget.AdjustMagicDamage(nDamage);
                nDamage = AdjustMinDamageUser2Monster(nDamage, pAtker, pTarget);
            }
            else if (pAtker.IsMonster() && pTarget is Character)
            {
                nDamage = CalcDamageMonster2User(nDamage, nDef, pAtker.Level, pTarget.Level);
                nDamage = pTarget.AdjustMagicDamage(nDamage);
                nDamage = AdjustMinDamageMonster2User(nDamage, pAtker, pTarget);
            }
            else
            {
                nDamage = pAtker.AdjustMagicDamage(nDamage);
            }

            if (pAtker.BattlePower < pTarget.BattlePower)
            {
                if (pTarget is Character)
                {
                    int   levelDiff = pTarget.BattlePower - pAtker.BattlePower;
                    float disccount = 0;
                    if (levelDiff > 50)
                    {
                        disccount = 50;
                    }
                    else
                    {
                        disccount = 100 - levelDiff;
                    }

                    nDamage = (int)(nDamage * (disccount / 100));
                }
            }

            if (pAtker.SkillCriticalStrike > pTarget.Immunity)
            {
                if (Calculations.ChanceCalc((float)(pAtker.SkillCriticalStrike - pTarget.Immunity) / 100))
                {
                    nDamage   = (int)(nDamage * 2f);
                    pSpecial |= InteractionEffect.CRITICAL_STRIKE;
                }
            }

            if (QueryMagic() != null && QueryMagic().GetElement() > ElementType.NONE)
            {
                switch (QueryMagic().GetElement())
                {
                case ElementType.WATER:
                    pSpecial |= InteractionEffect.WATER_RESIST;
                    break;

                case ElementType.FIRE:
                    pSpecial |= InteractionEffect.FIRE_RESIST;
                    break;

                case ElementType.WOOD:
                    pSpecial |= InteractionEffect.WOOD_RESIST;
                    break;

                case ElementType.METAL:
                    pSpecial |= InteractionEffect.METAL_RESIST;
                    break;

                case ElementType.EARTH:
                    pSpecial |= InteractionEffect.EARTH_RESIST;
                    break;
                }
            }

            if (pAtker is Monster && QueryMagic() != null && QueryMagic().GetElement() > ElementType.NONE)
            {
                nDamage += pAtker.Magics.GetElementPower(pTarget);
                //switch (QueryMagic().GetElement())
                //{
                //    case ElementType.WATER:
                //        {
                //            nDamage = (int)(nDamage * (1 - (pTarget.WaterResistance / 100f)));
                //            break;
                //        }
                //    case ElementType.FIRE:
                //        {
                //            nDamage = (int)(nDamage * (1 - (pTarget.FireResistance / 100f)));
                //            break;
                //        }
                //    case ElementType.EARTH:
                //        {
                //            nDamage = (int)(nDamage * (1 - (pTarget.EarthResistance / 100f)));
                //            break;
                //        }
                //    case ElementType.WOOD:
                //        {
                //            nDamage = (int)(nDamage * (1 - (pTarget.WoodResistance / 100f)));
                //            break;
                //        }
                //    case ElementType.METAL:
                //        {
                //            nDamage = (int)(nDamage * (1 - (pTarget.MetalResistance / 100f)));
                //            break;
                //        }
                //}
            }

            if (pAtker is Character)
            {
                nDamage += pAtker.AddFinalMagicAttack;
            }
            if (pTarget is Character)
            {
                nDamage -= pTarget.AddFinalMagicDefense;
            }

            // Adjust synflag damage
            if (pTarget is DynamicNpc)
            {
                //var npc = pTarget as DynamicNpc;
                //if (npc.IsSynFlag()
                //    && npc.IsSynMoneyEmpty())
                nDamage = nDamage * Character.SYNWAR_NOMONEY_DAMAGETIMES;
            }

            return(Calculations.CutTrail(1, nDamage));
        }
        private void GoButton_Click(object sender, RoutedEventArgs e)
        {
            FileSystemStockProvider provider = new FileSystemStockProvider(@"C:\Data\TEST.txt");
            var stockPrices = provider.GetData().Take(20);

            this.StockPriceDataGrid.ItemsSource = stockPrices;

            var adjustedClosePrices = from stockPrice in stockPrices
                                      select stockPrice.Item7;

            var dates = from stockPrice in stockPrices.Skip(2)
                        select new { stockPrice.Item1 };

            var calculations   = new Calculations();
            var movingAverage  = calculations.MovingAverage(adjustedClosePrices, 3);
            var movingAverages = dates.Zip(movingAverage, (d, p) => new { date = d.Item1, price = p });

            var bollingerBands = calculations.BollingerBands(adjustedClosePrices, 3);
            var upperBandBands = dates.Zip(bollingerBands, (d, bb) => new { date = d.Item1, upperBand = bb.Item1 + (bb.Item2 * 2) });
            var lowerBandBands = dates.Zip(bollingerBands, (d, bb) => new { date = d.Item1, lowerBand = bb.Item1 + (bb.Item2 * 2) * -1 });

            this.stockPriceLineGraph.DependentValuePath   = "price";
            this.stockPriceLineGraph.IndependentValuePath = "date";
            this.stockPriceLineGraph.ItemsSource          = movingAverages;

            this.stockPriceLineGraph2.DependentValuePath   = "upperBand";
            this.stockPriceLineGraph2.IndependentValuePath = "date";
            this.stockPriceLineGraph2.ItemsSource          = upperBandBands;

            this.stockPriceLineGraph3.DependentValuePath   = "lowerBand";
            this.stockPriceLineGraph3.IndependentValuePath = "date";
            this.stockPriceLineGraph3.ItemsSource          = lowerBandBands;

            var latestPrice   = stockPrices.Last();
            var adjustedClose = latestPrice.Item7;
            var closestDollar = Math.Round(adjustedClose, 0);

            var theGreeks = new List <GreekData>();

            for (int i = 0; i < 5; i++)
            {
                var greekData = new GreekData();
                greekData.StrikePrice = closestDollar - i;
                theGreeks.Add(greekData);
                greekData             = new GreekData();
                greekData.StrikePrice = closestDollar + i;
                theGreeks.Add(greekData);
            }
            theGreeks.Sort((greek1, greek2) => greek1.StrikePrice.CompareTo(greek2.StrikePrice));

            foreach (var greekData in theGreeks)
            {
                var inputData =
                    new BlackScholesInputData(adjustedClose, greekData.StrikePrice, .5, .01, .3);
                greekData.DeltaCall = calculations.BlackScholesDelta(inputData, PutCallFlag.Call);
                greekData.DeltaPut  = calculations.BlackScholesDelta(inputData, PutCallFlag.Put);
                greekData.Gamma     = calculations.BlackScholesGamma(inputData);
                greekData.RhoCall   = calculations.BlackScholesRho(inputData, PutCallFlag.Call);
                greekData.RhoPut    = calculations.BlackScholesRho(inputData, PutCallFlag.Put);
                greekData.ThetaCall = calculations.BlackScholesTheta(inputData, PutCallFlag.Call);
                greekData.ThetaPut  = calculations.BlackScholesTheta(inputData, PutCallFlag.Put);
                greekData.Vega      = calculations.BlackScholesVega(inputData);
            }

            this.TheGreeksDataGrid.ItemsSource = theGreeks;


            var blackScholes = new List <BlackScholesData>();

            for (int i = 0; i < 5; i++)
            {
                var blackScholesData = new BlackScholesData();
                blackScholesData.StrikePrice = closestDollar - i;
                blackScholes.Add(blackScholesData);
                blackScholesData             = new BlackScholesData();
                blackScholesData.StrikePrice = closestDollar + i;
                blackScholes.Add(blackScholesData);
            }
            blackScholes.Sort((bsmc1, bsmc2) => bsmc1.StrikePrice.CompareTo(bsmc2.StrikePrice));

            var           random     = new System.Random();
            List <Double> randomData = new List <double>();

            for (int i = 0; i < 1000; i++)
            {
                randomData.Add(random.NextDouble());
            }

            foreach (var blackScholesMonteCarlo in blackScholes)
            {
                var blackScholesInputData =
                    new BlackScholesInputData(adjustedClose, blackScholesMonteCarlo.StrikePrice, .5, .01, .3);
                var monteCarloInputData =
                    new MonteCarloInputData(adjustedClose, blackScholesMonteCarlo.StrikePrice, .5, .01, .3);

                blackScholesMonteCarlo.Call       = calculations.BlackScholes(blackScholesInputData, PutCallFlag.Call);
                blackScholesMonteCarlo.Put        = calculations.BlackScholes(blackScholesInputData, PutCallFlag.Put);
                blackScholesMonteCarlo.MonteCarlo = calculations.MonteCarlo(monteCarloInputData, randomData);
            }

            this.BlackScholesDataGrid.ItemsSource = blackScholes;
        }
Beispiel #11
0
        /// <summary>
        /// Creates a list of travel times from the matched track
        /// </summary>
        /// <param name="track"></param>
        /// <returns></returns>
        public static IEnumerable <TravelTime> FromMatchedTrack(OSMDB track)
        {
            List <TravelTime> result = new List <TravelTime>();
            var orderedWays          = track.Ways.OrderBy(way => int.Parse(way.Tags["order"].Value)).ToList();

            //Find start of the first segment
            int index = 0;

            while (index < orderedWays.Count && track.Nodes[orderedWays[index].Nodes[0]].Tags.ContainsTag("crossroad") == false)
            {
                index++;
            }

            while (index < orderedWays.Count)
            {
                int      startNodeId      = int.Parse(track.Nodes[orderedWays[index].Nodes[0]].Tags["node-id"].Value);
                DateTime segmentStartTime = DateTime.MinValue;
                if (track.Nodes[orderedWays[index].Nodes[0]].Tags.ContainsTag("time"))
                {
                    segmentStartTime = DateTime.Parse(track.Nodes[orderedWays[index].Nodes[0]].Tags["time"].Value);
                }
                else
                {
                    segmentStartTime = InterpolateStartTime(track, orderedWays, index);
                }

                List <GPXPoint> points = new List <GPXPoint>();
                points.Add(new GPXPoint(track.Nodes[orderedWays[index].Nodes[0]].Latitude, track.Nodes[orderedWays[index].Nodes[0]].Longitude, segmentStartTime));

                while (index < orderedWays.Count && track.Nodes[orderedWays[index].Nodes.Last()].Tags.ContainsTag("crossroad") == false)
                {
                    if (track.Nodes[orderedWays[index].Nodes.Last()].Tags.ContainsTag("time"))
                    {
                        points.Add(new GPXPoint(track.Nodes[orderedWays[index].Nodes.Last()].Latitude, track.Nodes[orderedWays[index].Nodes.Last()].Longitude,
                                                DateTime.Parse(track.Nodes[orderedWays[index].Nodes.Last()].Tags["time"].Value)));
                    }

                    index++;
                }

                if (index < orderedWays.Count)
                {
                    int endNodeId = int.Parse(track.Nodes[orderedWays[index].Nodes.Last()].Tags["node-id"].Value);

                    DateTime segmentEndTime = DateTime.MinValue;
                    if (track.Nodes[orderedWays[index].Nodes.Last()].Tags.ContainsTag("time"))
                    {
                        segmentEndTime = DateTime.Parse(track.Nodes[orderedWays[index].Nodes.Last()].Tags["time"].Value);
                    }
                    else
                    {
                        segmentEndTime = InterpolateEndTime(track, orderedWays, index);
                    }

                    points.Add(new GPXPoint(track.Nodes[orderedWays[index].Nodes.Last()].Latitude, track.Nodes[orderedWays[index].Nodes.Last()].Longitude, segmentEndTime));

                    int         wayId   = int.Parse(orderedWays[index].Tags["way-id"].Value);
                    SegmentInfo segment = new SegmentInfo()
                    {
                        NodeFromID = startNodeId, NodeToID = endNodeId, WayID = wayId
                    };
                    List <double> avgSpeeds = new List <double>();
                    for (int i = 0; i < points.Count - 1; i++)
                    {
                        avgSpeeds.Add(Calculations.GetDistance2D(points[i], points[i + 1]) / (points[i + 1].Time - points[i].Time).TotalSeconds);
                    }

                    TravelTime tt = new TravelTime(segment, segmentStartTime, segmentEndTime);
                    int        ii = 0;
                    while (ii < avgSpeeds.Count)
                    {
                        if (avgSpeeds[ii] < 1.0)
                        {
                            Stop stop = new Stop()
                            {
                                From = points[ii].Time
                            };
                            while (ii < avgSpeeds.Count && avgSpeeds[ii] < 1.0)
                            {
                                ii++;
                            }

                            stop.To = points[ii].Time;
                            tt.Stops.Add(stop);
                        }
                        ii++;
                    }

                    result.Add(tt);

                    index++;
                }
            }

            return(result);
        }
Beispiel #12
0
        public void TestMethodFormula(double a, double b, double c, double d, double e, double f, string expRes)
        {
            string actRes = new Calculations().ReturnResult(a, b, c, d, e, f);

            Assert.AreEqual(expRes, actRes);
        }
Beispiel #13
0
        public static void WriteToODT(Calculations calculation, bool includeInputs, bool includeBody, bool includeOutputs, string filePath)
        {
            try
            {
                var libraryPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Libraries";
                File.Copy(libraryPath + @"\Calculation_Template.docx", filePath, true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Oops..." + Environment.NewLine + ex.Message);
                return;
            }

            using (WordprocessingDocument wordDocument =
                       WordprocessingDocument.Open(filePath, true))
            {
                var  mainPart = wordDocument.MainDocumentPart;
                Body body     = mainPart.Document.AppendChild(new Body());

                var headerPart = mainPart.HeaderParts.First();
                var line1      = new Paragraph(new Run(new Text("Design of column " + calculation.Column.Name)));
                line1.PrependChild <ParagraphProperties>(new ParagraphProperties()
                {
                    ParagraphStyleId = new ParagraphStyleId()
                    {
                        Val = "NoSpacing"
                    }
                });
                var line2 = new Paragraph(new Run(new Text("By: " + Environment.UserName + " on " + DateTime.Today.ToLongDateString())));
                line2.PrependChild <ParagraphProperties>(new ParagraphProperties()
                {
                    ParagraphStyleId = new ParagraphStyleId()
                    {
                        Val = "NoSpacing"
                    }
                });
                var line3 = new Paragraph(new Run(new Text("Checked by : ")));
                line3.PrependChild <ParagraphProperties>(new ParagraphProperties()
                {
                    ParagraphStyleId = new ParagraphStyleId()
                    {
                        Val = "NoSpacing"
                    }
                });
                var line4 = new Paragraph(new Run(new Text("")));
                line4.PrependChild <ParagraphProperties>(new ParagraphProperties()
                {
                    ParagraphStyleId = new ParagraphStyleId()
                    {
                        Val = "NoSpacing"
                    }
                });
                headerPart.RootElement.Append(line1, line2, line3, line4);

                // update the SCaFFOLD inputs / outputs
                calculation.UpdateInputOuput();

                if (includeInputs)
                {
                    Paragraph para      = new Paragraph(new Run(new Text("Inputs")));
                    var       paraProps = para.PrependChild <ParagraphProperties>(new ParagraphProperties());
                    paraProps.ParagraphStyleId = new ParagraphStyleId()
                    {
                        Val = "Heading1"
                    };
                    body.Append(para);
                    para      = new Paragraph(new Run(new Text("Input values for calculation.")));
                    paraProps = para.PrependChild <ParagraphProperties>(new ParagraphProperties());
                    paraProps.ParagraphStyleId = new ParagraphStyleId()
                    {
                        Val = "Normal"
                    };
                    body.Append(para);
                    var tableOfInputs = genTable(calculation.GetInputs());
                    body.Append(tableOfInputs);
                }

                if (includeBody)
                {
                    Paragraph para      = new Paragraph(new Run(new Text("Body")));
                    var       paraProps = para.PrependChild <ParagraphProperties>(new ParagraphProperties());
                    paraProps.ParagraphStyleId = new ParagraphStyleId()
                    {
                        Val = "Heading1"
                    };
                    body.Append(para);

                    para      = new Paragraph(new Run(new Text("Main calculation including diagrams, working, narrative and conclusions.")));
                    paraProps = para.PrependChild <ParagraphProperties>(new ParagraphProperties());
                    paraProps.ParagraphStyleId = new ParagraphStyleId()
                    {
                        Val = "Normal"
                    };
                    body.Append(para);


                    var FormulaeTable = genFormulaeTable(calculation.Expressions, mainPart);
                    body.AppendChild(FormulaeTable);
                }

                if (includeOutputs)
                {
                    var para      = new Paragraph(new Run(new Text("Calculated values")));
                    var paraProps = para.PrependChild <ParagraphProperties>(new ParagraphProperties());
                    paraProps.ParagraphStyleId = new ParagraphStyleId()
                    {
                        Val = "Heading1"
                    };
                    body.Append(para);

                    para      = new Paragraph(new Run(new Text("List of calculated values.")));
                    paraProps = para.PrependChild <ParagraphProperties>(new ParagraphProperties());
                    paraProps.ParagraphStyleId = new ParagraphStyleId()
                    {
                        Val = "Normal"
                    };
                    body.Append(para);

                    var tableOfOutputs = genTable(calculation.GetOutputs());
                    body.Append(tableOfOutputs);
                }
            }
        }
        private void AddRowToTable(DataTable ReportTable, Int64 DonorKey, Int64 RecipientKey, String MailingCodeString, Int32 Copies)
        {
            DataRow Row = ReportTable.NewRow();

            Row["DonorKey"]     = DonorKey;
            Row["RecipientKey"] = RecipientKey;
            string        PartnerShortName;
            TPartnerClass PartnerClass;

            TRemote.MPartner.Partner.ServerLookups.WebConnectors.GetPartnerShortName(
                DonorKey, out PartnerShortName, out PartnerClass);
            String[] PartnerNamePart = PartnerShortName.Split(new Char[] { ',' });
            Row["DonorShortName"] =
                PartnerNamePart.Length > 1 ?
                PartnerNamePart[0].Trim() + " " + PartnerNamePart[1].Trim() :
                PartnerNamePart[0].Trim();


            TRemote.MPartner.Partner.ServerLookups.WebConnectors.GetPartnerShortName(
                RecipientKey, out PartnerShortName, out PartnerClass);

            PartnerNamePart           = PartnerShortName.Split(new Char[] { ',' });
            Row["RecipientShortName"] =
                PartnerNamePart.Length > 1 ?
                PartnerNamePart[0].Trim() + " " + PartnerNamePart[1].Trim() :
                PartnerNamePart[0].Trim();

            PLocationTable LocationTbl;
            String         CountryName;

            TRemote.MPartner.Mailing.WebConnectors.GetBestAddress(DonorKey,
                                                                  out LocationTbl, out CountryName);

            if (LocationTbl.Rows.Count > 0)
            {
                Row["DonorAddress"] = Calculations.DetermineLocationString(LocationTbl[0],
                                                                           Calculations.TPartnerLocationFormatEnum.plfLineBreakSeparated,
                                                                           1,
                                                                           " "
                                                                           );
            }

            TRemote.MPartner.Mailing.WebConnectors.GetBestAddress(RecipientKey,
                                                                  out LocationTbl, out CountryName);

            if (LocationTbl.Rows.Count > 0)
            {
                Row["RecipientAddress"] = Calculations.DetermineLocationString(LocationTbl[0],
                                                                               Calculations.TPartnerLocationFormatEnum.plfLineBreakSeparated,
                                                                               1,
                                                                               " "
                                                                               );
            }

            String LongCode = DonorKey.ToString("D10") + RecipientKey.ToString("D10") + MailingCodeString;

            LongCode += Module10CheckDigit(LongCode);

            Row["CodeWithSpaces"] = String.Format("{0} {1} {2} {3} {4} {5}",
                                                  LongCode.Substring(0, 2),
                                                  LongCode.Substring(2, 5),
                                                  LongCode.Substring(7, 5),
                                                  LongCode.Substring(12, 5),
                                                  LongCode.Substring(17, 5),
                                                  LongCode.Substring(22)
                                                  );
            Row["CodeForOcr"] = "042>" + LongCode + "+ 010467502>";

            for (Int32 copy = 0; copy < Copies; copy++)
            {
                var newRow = ReportTable.NewRow();
                newRow.ItemArray = Row.ItemArray;
                ReportTable.Rows.Add(newRow);
            }
        }
Beispiel #15
0
        /// <summary>
        /// Retrieves data that will be shown on the 'Overview' UserControl and adds it to <paramref name="AIndividualDataDS" />.
        /// </summary>
        /// <param name="APartnerKey">PartnerKey of the Person to load data for.</param>
        /// <param name="AIndividualDataDS">Typed DataSet of Type <see cref="IndividualDataTDS" />. Needs to be instantiated already!</param>
        /// <param name="AReadTransaction">Open Database transaction.</param>
        /// <returns>void</returns>
        private static void BuildSummaryData(Int64 APartnerKey, ref IndividualDataTDS AIndividualDataDS, TDBTransaction AReadTransaction)
        {
            string StrNotAvailable = Catalog.GetString("Not Available");
            IndividualDataTDSSummaryDataTable     SummaryDT;
            IndividualDataTDSSummaryDataRow       SummaryDR;
            IndividualDataTDSMiscellaneousDataRow MiscellaneousDataDR = AIndividualDataDS.MiscellaneousData[0];
            PPersonTable           PPersonDT;
            PPersonRow             PersonDR = null;
            PmPassportDetailsTable PassportDetailsDT;
            PmStaffDataTable       PmStaffDataDT;
            PmStaffDataRow         PmStaffDataDR     = null;
            PmJobAssignmentTable   PmJobAssignmentDT = null;
            PUnitTable             PUnitDT           = null;
            PmJobAssignmentRow     PmJobAssignmentDR;
            IndividualDataTDSJobAssignmentStaffDataCombinedRow JobAssiStaffDataCombDR;
            int                       JobAssiStaffDataCombKey = 0;
            TCacheable                CommonCacheable         = new TCacheable();
            TPartnerCacheable         PartnerCacheable        = new TPartnerCacheable();
            string                    MaritalStatusDescr;
            StringCollection          PassportColumns;
            string                    Nationalities;
            PPartnerRelationshipTable PartnerRelationshipDT;
            PPartnerTable             PartnerDT;
            PPartnerRow               PartnerDR = null;
            PLocationRow              LocationDR;
            PPartnerLocationRow       PartnerLocationDR;
            string                    PhoneNumber;
            string                    PhoneExtension = String.Empty;
            Int64                     ChurchPartnerKey;

            SummaryDT = new IndividualDataTDSSummaryDataTable();
            SummaryDR = SummaryDT.NewRowTyped(false);

            SummaryDR.PartnerKey = APartnerKey;

            #region Person Info

            PPersonDT = PPersonAccess.LoadByPrimaryKey(APartnerKey, AReadTransaction);

            if (PPersonDT.Rows.Count == 1)
            {
                PersonDR = (PPersonRow)PPersonDT.Rows[0];
            }

            if (PersonDR != null)
            {
                SummaryDR.DateOfBirth = PersonDR.DateOfBirth;
                SummaryDR.Gender      = PersonDR.Gender;

                MaritalStatusDescr = PartnerCodeHelper.GetMaritalStatusDescription(
                    @PartnerCacheable.GetCacheableTable, PersonDR.MaritalStatus);

                if (MaritalStatusDescr != String.Empty)
                {
                    MaritalStatusDescr = " - " + MaritalStatusDescr;
                }

                SummaryDR.MaritalStatus = PersonDR.MaritalStatus + MaritalStatusDescr;
            }
            else
            {
                SummaryDR.SetDateOfBirthNull();
                SummaryDR.Gender        = StrNotAvailable;
                SummaryDR.MaritalStatus = StrNotAvailable;
            }

            #region Nationalities

            PassportColumns = StringHelper.StrSplit(
                PmPassportDetailsTable.GetDateOfIssueDBName() + "," +
                PmPassportDetailsTable.GetDateOfExpirationDBName() + "," +
                PmPassportDetailsTable.GetPassportNationalityCodeDBName() + "," +
                PmPassportDetailsTable.GetMainPassportDBName(), ",");

            PassportDetailsDT = PmPassportDetailsAccess.LoadViaPPerson(APartnerKey,
                                                                       PassportColumns, AReadTransaction, null, 0, 0);

            Nationalities = Ict.Petra.Shared.MPersonnel.Calculations.DeterminePersonsNationalities(
                @CommonCacheable.GetCacheableTable, PassportDetailsDT);

            if (Nationalities != String.Empty)
            {
                SummaryDR.Nationalities = Nationalities;
            }
            else
            {
                SummaryDR.Nationalities = StrNotAvailable;
            }

            #endregion

            #region Phone and Email (from 'Best Address')

            ServerCalculations.DetermineBestAddress(APartnerKey, out PartnerLocationDR, out LocationDR);

            if (LocationDR != null)
            {
                SummaryDR.EmailAddress = PartnerLocationDR.EmailAddress;

                if (PartnerLocationDR.TelephoneNumber != String.Empty)
                {
                    PhoneNumber = PartnerLocationDR.TelephoneNumber;

                    if (!PartnerLocationDR.IsExtensionNull())
                    {
                        PhoneExtension = PartnerLocationDR.Extension.ToString();
                    }

                    SummaryDR.TelephoneNumber = Calculations.FormatIntlPhoneNumber(PhoneNumber, PhoneExtension, LocationDR.CountryCode,
                                                                                   @CommonCacheable.GetCacheableTable);
                }
                else if (PartnerLocationDR.MobileNumber != String.Empty)
                {
                    SummaryDR.TelephoneNumber = Calculations.FormatIntlPhoneNumber(PartnerLocationDR.MobileNumber,
                                                                                   String.Empty, LocationDR.CountryCode, @CommonCacheable.GetCacheableTable) + " " +
                                                Catalog.GetString("(Mobile)");
                }
                else
                {
                    SummaryDR.TelephoneNumber = StrNotAvailable;
                }
            }
            else
            {
                SummaryDR.TelephoneNumber = StrNotAvailable;
                SummaryDR.EmailAddress    = StrNotAvailable;
            }

            #endregion

            #endregion

            #region Commitments/Jobs

            PmStaffDataDT = PmStaffDataAccess.LoadViaPPerson(APartnerKey, AReadTransaction);
            MiscellaneousDataDR.ItemsCountCommitmentPeriods = PmStaffDataDT.Rows.Count;

            // First check if the PERSON has got any Commitments
            if (PmStaffDataDT.Rows.Count > 0)
            {
                foreach (DataRow DR in PmStaffDataDT.Rows)
                {
                    JobAssiStaffDataCombDR            = AIndividualDataDS.JobAssignmentStaffDataCombined.NewRowTyped(false);
                    JobAssiStaffDataCombDR.Key        = JobAssiStaffDataCombKey++;
                    JobAssiStaffDataCombDR.PartnerKey = APartnerKey;

                    PmStaffDataDR = (PmStaffDataRow)DR;

                    if (!(PmStaffDataDR.IsReceivingFieldNull()) &&
                        (PmStaffDataDR.ReceivingField != 0))
                    {
                        PUnitDT = PUnitAccess.LoadByPrimaryKey(PmStaffDataDR.ReceivingField, AReadTransaction);

                        JobAssiStaffDataCombDR.FieldKey  = PmStaffDataDR.ReceivingField;
                        JobAssiStaffDataCombDR.FieldName = PUnitDT[0].UnitName;
                    }
                    else
                    {
                        JobAssiStaffDataCombDR.FieldKey  = 0;
                        JobAssiStaffDataCombDR.FieldName = "[None]";
                    }

                    JobAssiStaffDataCombDR.Position = PmStaffDataDR.JobTitle;
                    JobAssiStaffDataCombDR.FromDate = PmStaffDataDR.StartOfCommitment;
                    JobAssiStaffDataCombDR.ToDate   = PmStaffDataDR.EndOfCommitment;

                    AIndividualDataDS.JobAssignmentStaffDataCombined.Rows.Add(JobAssiStaffDataCombDR);
                }
            }
            else
            {
                // The PERSON hasn't got any Commitments, therefore check if the PERSON has any Job Assignments

                PmJobAssignmentDT = PmJobAssignmentAccess.LoadViaPPartner(APartnerKey, AReadTransaction);

                if (PmJobAssignmentDT.Rows.Count > 0)
                {
                    foreach (DataRow DR in PmJobAssignmentDT.Rows)
                    {
                        JobAssiStaffDataCombDR            = AIndividualDataDS.JobAssignmentStaffDataCombined.NewRowTyped(false);
                        JobAssiStaffDataCombDR.Key        = JobAssiStaffDataCombKey++;
                        JobAssiStaffDataCombDR.PartnerKey = APartnerKey;

                        PmJobAssignmentDR = (PmJobAssignmentRow)DR;

                        if (PmJobAssignmentDR.UnitKey != 0)
                        {
                            PUnitDT = PUnitAccess.LoadByPrimaryKey(PmJobAssignmentDR.UnitKey, AReadTransaction);

                            JobAssiStaffDataCombDR.FieldKey  = PmJobAssignmentDR.UnitKey;
                            JobAssiStaffDataCombDR.FieldName = PUnitDT[0].UnitName;
                        }
                        else
                        {
                            JobAssiStaffDataCombDR.FieldKey  = 0;
                            JobAssiStaffDataCombDR.FieldName = "[None]";
                        }

                        JobAssiStaffDataCombDR.Position = PmJobAssignmentDR.PositionName;
                        JobAssiStaffDataCombDR.FromDate = PmJobAssignmentDR.FromDate;
                        JobAssiStaffDataCombDR.ToDate   = PmJobAssignmentDR.ToDate;

                        AIndividualDataDS.JobAssignmentStaffDataCombined.Rows.Add(JobAssiStaffDataCombDR);
                    }
                }
            }

            #endregion

            #region Church Info

            SummaryDR.ChurchName         = StrNotAvailable;
            SummaryDR.ChurchAddress      = StrNotAvailable;
            SummaryDR.ChurchPhone        = StrNotAvailable;
            SummaryDR.ChurchPastor       = StrNotAvailable;
            SummaryDR.ChurchPastorsPhone = StrNotAvailable;
            SummaryDR.NumberOfShownSupportingChurchPastors = 0;

            // Find SUPPCHURCH Relationship
            PartnerRelationshipDT = PPartnerRelationshipAccess.LoadUsingTemplate(new TSearchCriteria[] {
                new TSearchCriteria(PPartnerRelationshipTable.GetRelationKeyDBName(), APartnerKey),
                new TSearchCriteria(PPartnerRelationshipTable.GetRelationNameDBName(), "SUPPCHURCH")
            },
                                                                                 AReadTransaction);

            SummaryDR.NumberOfShownSupportingChurches = PartnerRelationshipDT.Rows.Count;

            if (PartnerRelationshipDT.Rows.Count > 0)
            {
                ChurchPartnerKey = PartnerRelationshipDT[0].PartnerKey;

                // Load Church Partner
                PartnerDT = PPartnerAccess.LoadByPrimaryKey(ChurchPartnerKey, AReadTransaction);

                if (PartnerDT.Rows.Count > 0)
                {
                    PartnerDR = PartnerDT[0];

                    // Church Name
                    if (PartnerDR.PartnerShortName != String.Empty)
                    {
                        SummaryDR.ChurchName = PartnerDR.PartnerShortName;
                    }

                    #region Church Address and Phone

                    ServerCalculations.DetermineBestAddress(PartnerRelationshipDT[0].PartnerKey, out PartnerLocationDR, out LocationDR);

                    if (LocationDR != null)
                    {
                        SummaryDR.ChurchAddress = Calculations.DetermineLocationString(LocationDR,
                                                                                       Calculations.TPartnerLocationFormatEnum.plfCommaSeparated);

                        // Church Phone
                        if (PartnerLocationDR.TelephoneNumber != String.Empty)
                        {
                            PhoneNumber = PartnerLocationDR.TelephoneNumber;

                            if (!PartnerLocationDR.IsExtensionNull())
                            {
                                PhoneExtension = PartnerLocationDR.Extension.ToString();
                            }

                            SummaryDR.ChurchPhone = Calculations.FormatIntlPhoneNumber(PhoneNumber, PhoneExtension, LocationDR.CountryCode,
                                                                                       @CommonCacheable.GetCacheableTable);
                        }
                        else if (PartnerLocationDR.MobileNumber != String.Empty)
                        {
                            SummaryDR.ChurchPhone = Calculations.FormatIntlPhoneNumber(PartnerLocationDR.MobileNumber,
                                                                                       String.Empty, LocationDR.CountryCode, @CommonCacheable.GetCacheableTable) + " " +
                                                    Catalog.GetString("(Mobile)");
                        }
                    }

                    #endregion

                    #region Pastor

                    // Find PASTOR Relationship
                    PartnerRelationshipDT.Rows.Clear();
                    PartnerRelationshipDT = PPartnerRelationshipAccess.LoadUsingTemplate(new TSearchCriteria[] {
                        new TSearchCriteria(PPartnerRelationshipTable.GetPartnerKeyDBName(), ChurchPartnerKey),
                        new TSearchCriteria(PPartnerRelationshipTable.GetRelationNameDBName(), "PASTOR")
                    },
                                                                                         AReadTransaction);

                    SummaryDR.NumberOfShownSupportingChurchPastors = PartnerRelationshipDT.Rows.Count;

                    if (PartnerRelationshipDT.Rows.Count > 0)
                    {
                        // Load PASTOR Partner
                        PartnerDT = PPartnerAccess.LoadByPrimaryKey(PartnerRelationshipDT[0].RelationKey, AReadTransaction);

                        if (PartnerDT.Rows.Count > 0)
                        {
                            PartnerDR = PartnerDT[0];

                            // Pastor's Name
                            if (PartnerDR.PartnerShortName != String.Empty)
                            {
                                SummaryDR.ChurchPastor = PartnerDR.PartnerShortName;
                            }

                            #region Pastor's Phone

                            ServerCalculations.DetermineBestAddress(PartnerRelationshipDT[0].RelationKey,
                                                                    out PartnerLocationDR, out LocationDR);

                            if (LocationDR != null)
                            {
                                // Pastor's Phone
                                if (PartnerLocationDR.TelephoneNumber != String.Empty)
                                {
                                    PhoneNumber = PartnerLocationDR.TelephoneNumber;

                                    if (!PartnerLocationDR.IsExtensionNull())
                                    {
                                        PhoneExtension = PartnerLocationDR.Extension.ToString();
                                    }

                                    SummaryDR.ChurchPastorsPhone = Calculations.FormatIntlPhoneNumber(PhoneNumber,
                                                                                                      PhoneExtension, LocationDR.CountryCode, @CommonCacheable.GetCacheableTable);
                                }
                                else if (PartnerLocationDR.MobileNumber != String.Empty)
                                {
                                    SummaryDR.ChurchPastorsPhone = Calculations.FormatIntlPhoneNumber(PartnerLocationDR.MobileNumber,
                                                                                                      String.Empty, LocationDR.CountryCode, @CommonCacheable.GetCacheableTable) + " " +
                                                                   Catalog.GetString("(Mobile)");
                                }
                            }

                            #endregion
                        }
                    }

                    #endregion
                }
            }

            #endregion

            // Add Summary DataRow to Summary DataTable
            SummaryDT.Rows.Add(SummaryDR);

            // Add Row to 'SummaryData' DataTable in Typed DataSet 'IndividualDataTDS'
            AIndividualDataDS.Merge(SummaryDT);
        }
Beispiel #16
0
 public IdentityController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
 {
     SignInManager = signInManager;
     UserManager   = userManager;
     _calc         = new Calculations();
 }
Beispiel #17
0
 public IdentityController()
 {
     _calc = new Calculations();
 }
Beispiel #18
0
 public CpbAnalysis()
 {
     setup        = new CpbSetup();
     calculations = new Calculations();
     output       = new DataObject();
 }
Beispiel #19
0
        private static PartnerDetails GetDonor(Int64 APartnerKey)
        {
            if (DonorList.ContainsKey(APartnerKey))
            {
                return(DonorList[APartnerKey]);
            }

            PartnerDetails Ret        = new PartnerDetails();
            PPartnerTable  PartnerTbl = PPartnerAccess.LoadByPrimaryKey(APartnerKey, FTransaction);

            if (PartnerTbl.Rows.Count > 0)
            {
                PPartnerRow PartnerRow = PartnerTbl[0];

                Ret.LastName  = PartnerRow.PartnerShortName;
                Ret.Anonymous = PartnerRow.AnonymousDonor;

                if (PartnerRow.PartnerClass == "PERSON")
                {
                    PPersonTable PersonTbl = PPersonAccess.LoadByPrimaryKey(APartnerKey, FTransaction);

                    if (PersonTbl.Rows.Count > 0)
                    {
                        PPersonRow PersonRow = PersonTbl[0];
                        Ret.FirstName = PersonRow.FirstName;
                        Ret.LastName  = PersonRow.FamilyName;
                        Ret.Class     = "PERSON";
                    }
                }

                if (PartnerRow.PartnerClass == "FAMILY")
                {
                    PFamilyTable FamilyTbl = PFamilyAccess.LoadByPrimaryKey(APartnerKey, FTransaction);

                    if (FamilyTbl.Rows.Count > 0)
                    {
                        PFamilyRow FamilyRow = FamilyTbl[0];
                        Ret.FirstName = FamilyRow.FirstName;
                        Ret.LastName  = FamilyRow.FamilyName;
                        Ret.Class     = "FAMILY";
                    }
                }

                PPartnerLocationRow PartnerLocationRow;
                TLocationPK         LocationKey = ServerCalculations.DetermineBestAddress(APartnerKey, out PartnerLocationRow);

                if (LocationKey.LocationKey != -1)
                {
                    Ret.Email     = PartnerLocationRow.EmailAddress;
                    Ret.Telephone = PartnerLocationRow.TelephoneNumber;
                    PLocationTable LocationTbl = PLocationAccess.LoadByPrimaryKey(PartnerLocationRow.SiteKey,
                                                                                  PartnerLocationRow.LocationKey,
                                                                                  FTransaction);

                    if (LocationTbl.Rows.Count > 0)
                    {
                        PLocationRow LocationRow = LocationTbl[0];
                        Ret.Address = Calculations.DetermineLocationString(LocationRow, Calculations.TPartnerLocationFormatEnum.plfCommaSeparated);
                    }
                }
            }

            DonorList.Add(APartnerKey, Ret);
            return(Ret);
        }
        protected void btnAttSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                //using (ERPSSLHBEntities _context = new ERPSSLHBEntities())
                //{
                string at_status = "";
                bool   ot_status;

                HRM_ATTENDANCE objAttendance = new HRM_ATTENDANCE();
                objAttendance.EmpId                     = Convert.ToInt64(lblHiddenId.Text);
                objAttendance.EID                       = txtEid_AT.Text;
                objAttendance.ShiftCode                 = lblShiftCode.Text;
                objAttendance.Attendance_Date           = Convert.ToDateTime(txtAttDate.Text);
                objAttendance.Attendance_Day            = Convert.ToDateTime(txtAttDate.Text).DayOfWeek.ToString();
                objAttendance.Working_Day               = ddlWorkingDay.Text;
                objAttendance.OT_Compliance             = 0;
                objAttendance.Update_Status             = 0;
                objAttendance.Attendance_Process_Status = true;

                TimeSpan in_time = TimeSpan.Parse(string.Format("{0}:{1}:{2}", txtAttInTime.Hour, txtAttInTime.Minute, txtAttInTime.Second));
                objAttendance.In_Time = in_time;

                TimeSpan out_time = TimeSpan.Parse(string.Format("{0}:{1}:{2}", txtAttOutTime.Hour, txtAttOutTime.Minute, txtAttOutTime.Second));
                objAttendance.Out_Time = out_time;

                TimeSpan workedTime = Calculations.timeDiff(in_time, out_time);
                TimeSpan overTime   = TimeSpan.Parse("00:00:00");

                TimeSpan originalTime = TimeSpan.Parse("09:00:00");

                if (originalTime < in_time)
                {
                    TimeSpan late_time = Calculations.timeDiff(originalTime, in_time);
                    objAttendance.Late_Time = late_time;
                }
                else
                {
                    objAttendance.Late_Time = TimeSpan.Parse("00:00:00");
                }
                //if (workedTime > in_time)
                //{
                //    overTime = (workedTime - in_time);
                //    ot_status = true;
                //}
                //else
                //{
                //    ot_status = false;
                //}

                if (overTime == TimeSpan.Parse("00:00:00"))
                {
                    ot_status = false;
                }
                else
                {
                    ot_status = true;
                }

                objAttendance.Worked_Time     = workedTime;
                objAttendance.Shift_TotalHour = shifted_TotalHour;
                objAttendance.Over_Time       = overTime;
                objAttendance.OT_Hour         = 0;
                objAttendance.OT_Minute       = 0;
                objAttendance.OT_Total        = 0;
                objAttendance.OT_ExtraAdd     = 0;
                objAttendance.OT_Deduction    = 0;
                objAttendance.OT_Status       = ot_status;

                if (rdbPresent.Checked == true)
                {
                    at_status = "P";
                }
                if (rdbLate.Checked == true)
                {
                    at_status = "L";
                }
                //if (rdbOverLate.Checked == true)
                //{
                //    at_status = "OL";
                //}
                if (rdbAbsent.Checked == true)
                {
                    at_status = "A";
                }

                objAttendance.Status = at_status;
                //objAttendance.A = at_status;
                objAttendance.Remarks = txtRemarks_AT.Text;

                //obj.EDIT_USER = Guid.Parse("a376708d-757f-4777-bd05-bfc89b6971ce");
                objAttendance.Edit_User = ((SessionUser)Session["SessionUser"]).UserId;
                objAttendance.Edit_Date = DateTime.Now;

                string OCODE = ((SessionUser)Session["SessionUser"]).OCode;
                objAttendance.OCode = OCODE;

                //if (in_time > out_time)
                //{
                //    lblMessege.Text = "<font color='red'>Out Time can't be less than In Time</font>";
                //    return;
                //}

                int AttendanceCount = (from att in _context.HRM_ATTENDANCE
                                       where att.EID == objAttendance.EID && att.Attendance_Date == objAttendance.Attendance_Date
                                       select att.ATTE_ID).Count();

                //HRM_ATTENDANCE aHRM_ATTENDANCE = objAtt_BLL.GetAllAttendanceData(Convert.ToDateTime(txtAttDate.Text), txtEid_AT.Text);

                //if (aHRM_ATTENDANCE.In_Time == TimeSpan.Parse("00:00:00") || AttendanceCount==0)
                //{
                int result = objAtt_BLL.InsertAttendance(objAttendance);
                if (result == 1)
                {
                    //lblMessege.Text = "Attendance Recorded successfully!";
                    //lblMessege.ForeColor = System.Drawing.Color.Green;
                    ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "func('Attendance Recorded successfully!')", true);
                    reset();
                    BindGridEmployeeAttendance();
                }

                else
                {
                    ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "func('Attendance Recorded failure!')", true);
                    // lblMessege.Text = "Attendance Recorded failure!";
                    //lblMessege.ForeColor = System.Drawing.Color.Red;
                }
                //}
                //else
                //{
                ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "func('Attendance Already Recorded in this day for this Employee!')", true);
                //lblMessege.Text = "Attendance Already Recorded in this day for this Employee!";
                //lblMessege.ForeColor = System.Drawing.Color.Red;
                //reset();
                //}
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "func('" + ex.Message + "')", true);
            }
        }
Beispiel #21
0
        private static Boolean ExportField()
        {
            Int64 MySiteKey = DomainManagerBase.GSiteKey;

            /*
             *  From 4GL:
             *
             *  FIND FIRST pbfPartnerLocation WHERE p_partner_key_n = pdPartnerKey
             *      AND p_location_type_c = pcLocationType
             *      AND p_send_mail_l = plMailing
             *      AND (p_date_effective_d = ? OR p_date_effective_d <= TODAY)
             *      AND (p_date_good_until_d = ? OR p_date_good_until_d >= TODAY)
             *      NO-LOCK NO-ERROR.
             *  FIND pbfLocation OF pbfPartnerLocation NO-LOCK NO-ERROR.
             */
            String SqlQuery =
                "Select " +
                "PUB_p_location.p_building_1_c AS Building1, " +
                "PUB_p_location.p_building_2_c AS Building2, " +
                "PUB_p_location.p_street_name_c AS StreetName, " +
                "PUB_p_location.p_locality_c AS Locality, " +
                "PUB_p_location.p_suburb_c AS Suburb, " +
                "PUB_p_location.p_city_c AS City, " +
                "PUB_p_location.p_county_c AS County, " +
                "PUB_p_location.p_postal_code_c AS PostalCode, " +
                "PUB_p_location.p_country_code_c AS CountryCode, " +
                "PUB_p_location.p_address_3_c AS Address3, " +
                "PUB_p_partner_location.p_email_address_c AS Email, " +
                "PUB_p_partner_location.p_fax_number_c As Fax, " +
                "PUB_p_partner_location.p_url_c AS Website, " +
                "PUB_p_partner_location.p_telephone_number_c AS Telephone, " +
                "PUB_p_partner_location.p_send_mail_l AS SendMail, " +
                "PUB_p_country.p_time_zone_minimum_n AS TimeZoneMin, " +
                "PUB_p_country.p_time_zone_maximum_n AS TimeZoneMax, " +
                "PUB_p_country.p_internat_telephone_code_i AS InternationalPhone " +
                "FROM PUB_p_partner_location LEFT JOIN PUB_p_location ON PUB_p_partner_location.p_site_key_n = PUB_p_location.p_site_key_n " +
                "LEFT JOIN PUB_p_country ON PUB_p_location.p_country_code_c = PUB_p_country.p_country_code_c " +
                "WHERE PUB_p_partner_location.p_partner_key_n = " + MySiteKey.ToString("D10") +
                " AND (PUB_p_partner_location.p_location_type_c = 'BUSINESS') " +
                " AND (PUB_p_partner_location.p_date_effective_d IS NULL OR PUB_p_partner_location.p_date_effective_d < NOW()) " +
                " AND (PUB_p_partner_location.p_date_good_until_d IS NULL OR PUB_p_partner_location.p_date_good_until_d > NOW()) "
            ;

            DataSet FieldLocationDS = DBAccess.GDBAccessObj.Select(SqlQuery, "FieldLocationTbl", FTransaction);
            DataRow Row;

            if (FieldLocationDS.Tables["FieldLocationTbl"].Rows.Count == 0)
            {
                return(false);
            }

            Row = FieldLocationDS.Tables["FieldLocationTbl"].Rows[0];
            String PostalAddress = Calculations.DetermineLocationString(
                Row["Building1"].ToString(), Row["Building2"].ToString(), Row["Locality"].ToString(), Row["StreetName"].ToString(),
                Row["Address3"].ToString(), Row["Suburb"].ToString(), Row["City"].ToString(), Row["County"].ToString(),
                Row["PostalCode"].ToString(), Row["CountryCode"].ToString(), Calculations.TPartnerLocationFormatEnum.plfCommaSeparated);

            //
            // If there's a "non-mailing" address, this is the "real" one, with email, fax, url etc.
            FieldLocationDS.Tables["FieldLocationTbl"].DefaultView.RowFilter = "SendMail=false";

            String StreetAddress;

            if (FieldLocationDS.Tables["FieldLocationTbl"].DefaultView.Count > 0)
            {
                Row           = FieldLocationDS.Tables["FieldLocationTbl"].DefaultView[0].Row;
                StreetAddress = Calculations.DetermineLocationString(
                    Row["Building1"].ToString(), Row["Building2"].ToString(), Row["Locality"].ToString(), Row["StreetName"].ToString(),
                    Row["Address3"].ToString(), Row["Suburb"].ToString(), Row["City"].ToString(), Row["County"].ToString(),
                    Row["PostalCode"].ToString(), Row["CountryCode"].ToString(), Calculations.TPartnerLocationFormatEnum.plfCommaSeparated);
            }
            else
            {
                StreetAddress = PostalAddress;
            }

            String TimeZone = Row["TimeZoneMin"].ToString();

            if (Row["TimeZoneMin"] != Row["TimeZoneMax"])
            {
                TimeZone += (" " + Row["TimeZoneMax"].ToString());
            }

            String IntlPrefix = ("+" + Row["InternationalPhone"] + " ");

            using (StreamWriter sw = new StreamWriter(FExportFilePath + "field.csv"))
            {
                sw.WriteLine("key,value");
                sw.WriteLine("time_zone," + TimeZone);
                sw.WriteLine("postal_address,\"" + PostalAddress + "\"");
                sw.WriteLine("street_address,\"" + StreetAddress + "\"");
                sw.WriteLine("email," + Row["Email"]);
                sw.WriteLine("fax," + IntlPrefix + Row["Fax"]);
                sw.WriteLine("website," + Row["Website"]);
                sw.WriteLine("telephone," + IntlPrefix + Row["Telephone"]);
            }
            return(true);
        }
        public void EuclideanGCD(int expected, params int[] numbers)
        {
            int actual = Calculations.EuclideanGCD(numbers);

            Assert.AreEqual(expected, actual);
        }
Beispiel #23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="APaymentNum"></param>
        /// <param name="ALedgerNumber"></param>
        public void PrintRemittanceAdvice(Int32 APaymentNum, Int32 ALedgerNumber)
        {
            txtPaymentNum.NumberValueInt = APaymentNum;
            AccountsPayableTDS PaymentDetails = TRemote.MFinance.AP.WebConnectors.LoadAPPayment(ALedgerNumber, APaymentNum);

            if (PaymentDetails.AApPayment.Rows.Count == 0) // unable to load this payment..
            {
                lblLoadStatus.Text = String.Format(Catalog.GetString("Error - can't load Payment number {0}."), APaymentNum);
                return;
            }

            SortedList <string, List <string> > FormValues = new SortedList <string, List <string> >();

            //
            // load my own country code, so I don't print it on letters to my own country.
            //
            string LocalCountryCode = TRemote.MPartner.Partner.ServerLookups.WebConnectors.GetCountryCodeFromSiteLedger();

            //
            // These are the fields that I will pull out of the TDS...
            //
            FormValues.Add("SupplierName", new List <string>());
            FormValues.Add("SupplierAddress", new List <string>());
            FormValues.Add("PaymentDate", new List <string>());
            FormValues.Add("OurReference", new List <string>());
            FormValues.Add("InvoiceDate", new List <string>());
            FormValues.Add("InvoiceNumber", new List <string>());
            FormValues.Add("InvoiceAmount", new List <string>());
            FormValues.Add("TotalPayment", new List <string>());

            FormValues["SupplierName"].Add(PaymentDetails.PPartner[0].PartnerShortName);

            if (PaymentDetails.PLocation[0].CountryCode == LocalCountryCode)
            {
                PaymentDetails.PLocation[0].CountryCode = ""; // Don't print country code it it's the same as my own.
            }

            FormValues["SupplierAddress"].Add(Calculations.DetermineLocationString(PaymentDetails.PLocation[0],
                                                                                   Calculations.TPartnerLocationFormatEnum.plfHtmlLineBreak));

            String DatePattern = Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern;

            DatePattern = "dd MMMM yyyy"; // The long pattern above is no good in UK, although it might be OK in other cultures...

            FormValues["PaymentDate"].Add(PaymentDetails.AApPayment[0].PaymentDate.Value.ToString(DatePattern));
            FormValues["OurReference"].Add(PaymentDetails.AApSupplier[0].OurReference);

            foreach (AApDocumentRow Row in PaymentDetails.AApDocument.Rows)
            {
                FormValues["InvoiceDate"].Add(Row.DateIssued.ToString(DatePattern));
                FormValues["InvoiceNumber"].Add(Row.DocumentCode);
                FormValues["InvoiceAmount"].Add(Row.TotalAmount.ToString("n2") + " " + PaymentDetails.AApSupplier[0].CurrencyCode);
            }

            FormValues["TotalPayment"].Add(PaymentDetails.AApPayment[0].Amount.ToString("n2") + " " + PaymentDetails.AApSupplier[0].CurrencyCode);

            String TemplateFilename = TAppSettingsManager.GetValue("Formletters.Path") + "\\ApRemittanceAdvice.html";

            if (!File.Exists(TemplateFilename))
            {
                lblLoadStatus.Text = String.Format(Catalog.GetString("Error - unable to load HTML template from {0}"), TemplateFilename);
                return;
            }

            FHtmlDoc = TFormLettersTools.PrintSimpleHTMLLetter(TemplateFilename, FormValues);

            System.Drawing.Printing.PrintDocument printDocument = new System.Drawing.Printing.PrintDocument();
            bool printerInstalled = printDocument.PrinterSettings.IsValid;

            if (!printerInstalled)
            {
                lblLoadStatus.Text = Catalog.GetString("There is no printer, so printing is not possible");
                return;
            }

            FGfxPrinter = new TGfxPrinter(printDocument, TGfxPrinter.ePrinterBehaviour.eFormLetter);
            try
            {
                TPrinterHtml htmlPrinter = new TPrinterHtml(FHtmlDoc,
                                                            TAppSettingsManager.GetValue("Formletters.Path"),
                                                            FGfxPrinter);
                FGfxPrinter.Init(eOrientation.ePortrait, htmlPrinter, eMarginType.ePrintableArea);
                this.ppvLetters.InvalidatePreview();
                this.ppvLetters.Document = FGfxPrinter.Document;
                this.ppvLetters.Zoom     = 1;
                // GfxPrinter.Document.EndPrint += new PrintEventHandler(this.EndPrint);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            btnPDF.Visible  = true;
            btnCopy.Visible = true;

            lblLoadStatus.Text = "";
        }
        public void BinaryGCD(int expected, params int[] numbers)
        {
            int actual = Calculations.BinaryGCD(numbers);

            Assert.AreEqual(expected, actual);
        }
        public bool ProcAttack_Hand2Hand()
        {
            try
            {
                if (m_pOwner == null || m_dwTargetId == 0 || !IsBattleMaintain())
                {
                    ResetBattle();
                    return(false);
                }
            }
            catch (Exception ex)
            {
                ServerKernel.Log.SaveLog("ProcAttack_Hand2Hand.IsBattleMaint", false, LogType.WARNING);
                ServerKernel.Log.SaveLog(ex.ToString(), false, LogType.EXCEPTION);
                return(false);
            }

            var pTarget = FindRole(m_dwTargetId);

            if (pTarget == null)
            {
                ResetBattle();
                return(false);
            }

            if (m_pOwner.IsImmunity(pTarget))
            {
                ResetBattle();
                return(false);
            }

            Character pOwner = null;

            if (m_pOwner is Character)
            {
                pOwner = m_pOwner as Character;
            }

            if (IsTargetDodged(m_pOwner, pTarget))
            {
                m_pOwner.SendDamageMsg(pTarget.Identity, 0, InteractionEffect.NONE);

                return(true);
            }

            // if archer
            //if (m_pOwner.IsBowman())
            //{
            //    if (pOwner != null)
            //    {
            //        if (!pOwner.Equipment.Items.ContainsKey(5) || !pOwner.Equipment.Items[5].IsArrowSort()
            //            || pOwner.Equipment.Items[5].Durability <= 0)
            //        {
            //            if (!pOwner.ReloadArrows())
            //            {
            //                ResetBattle();
            //                return false; // no arrows
            //            }
            //        }
            //        else
            //        {
            //            pOwner.Equipment.Items[5].Durability -= 1;
            //        }
            //        pOwner.Send(pOwner.Equipment.Items[5].InformationPacket(true));
            //    }
            //}

            if (QueryMagic() != null)
            {
                QueryMagic().AbortMagic(true);
            }

            if (pTarget is Character)
            {
                Character pTargetUser = pTarget as Character;
                if (pTargetUser.CheckScapegoat(m_pOwner))
                {
                    return(true);
                }
            }

            if (m_pOwner is Character && m_pOwner.AutoSkillAttack(pTarget))
            {
                return(true);
            }

            InteractionEffect special = InteractionEffect.NONE;
            int nDamage         = m_pOwner.Attack(pTarget, ref special);
            int nTargetLifeLost = Math.Max(1, nDamage);
            int nExp            = (int)Math.Min(pTarget.MaxLife, nTargetLifeLost);

            if (m_pOwner.QueryStatus(FlagInt.FATAL_STRIKE) != null &&
                pTarget is Monster)
            {
                Monster pMob = pTarget as Monster;
                if (!pMob.IsGuard() &&
                    !pMob.IsPlayer() &&
                    !pMob.IsDynaNpc() &&
                    !pMob.IsDynaMonster())
                {
                    m_pOwner.MapX = pTarget.MapX;
                    m_pOwner.MapY = pTarget.MapY;
                    var msg = new MsgAction(m_pOwner.Identity, pTarget.Identity, m_pOwner.MapX, m_pOwner.MapY,
                                            GeneralActionType.NINJA_STEP);
                    m_pOwner.Send(msg);
                    m_pOwner.Screen.SendMovement(msg);
                }
            }

            m_pOwner.SendDamageMsg(pTarget.Identity, (uint)nTargetLifeLost, special);
            if (nDamage == 0)
            {
                return(false);
            }

            // pTarget.AddAttribute(ClientUpdateType.HITPOINTS, -1*nTargetLifeLost, true);
            pTarget.BeAttack(0, m_pOwner, nDamage, true);

            // Syn rank
            DynamicNpc pNpc       = null;
            Character  pOwnerUser = null;

            if (pTarget is DynamicNpc)
            {
                pNpc = pTarget as DynamicNpc;
            }

            if (m_pOwner is Character)
            {
                pOwnerUser = m_pOwner as Character;
            }

            if (pNpc != null && pOwnerUser != null && pNpc.IsAwardScore())
            {
                if (pNpc.IsCtfFlag())
                {
                    pOwnerUser.AwardCtfScore(pNpc, nTargetLifeLost);
                }
                else
                {
                    pOwnerUser.AwardSynWarScore(pNpc, nTargetLifeLost);
                }
            }

            if (m_pOwner is Character && pNpc != null && pNpc.IsGoal() || pTarget.IsMonster()) // check is monster
            {
                nExp = m_pOwner.AdjustExperience(pTarget, nExp, false);
                int nAdditionExp = 0;
                if (!pTarget.IsAlive)
                {
                    nAdditionExp = (int)(pTarget.MaxLife * 5 / 100);
                    nExp        += nAdditionExp;

                    if (pOwnerUser != null)
                    {
                        if (pOwnerUser.Team != null)
                        {
                            pOwnerUser.Team.AwardMemberExp(pOwnerUser.Identity, pTarget, nAdditionExp);
                        }
                    }
                }

                m_pOwner.AwardBattleExp(nExp, true);

                if (!pTarget.IsAlive && nAdditionExp > 0)
                {
                    if (!pTarget.IsAlive && !m_pOwner.Map.IsTrainingMap() && pOwnerUser != null)
                    {
                        pOwnerUser.Send(string.Format(ServerString.STR_KILLING_EXPERIENCE, nAdditionExp),
                                        ChatTone.TOP_LEFT);
                    }
                }

                if (pOwnerUser != null)
                {
                    Item item;
                    if (pOwnerUser.Equipment.Items.TryGetValue(ItemPosition.RIGHT_HAND, out item))
                    {
                        pOwnerUser.WeaponSkill.AwardExperience((ushort)item.GetItemSubtype(), nExp);
                    }
                    if (pOwnerUser.Equipment.Items.TryGetValue(ItemPosition.LEFT_HAND, out item))
                    {
                        pOwnerUser.WeaponSkill.AwardExperience((ushort)item.GetItemSubtype(), nExp);
                    }
                }
            }

            m_pOwner.AdditionMagic(nTargetLifeLost, nDamage);

            if (Calculations.ChanceCalc(5f) && m_pOwner is Character)
            {
                (m_pOwner as Character).SendWeaponMagic2(pTarget);
            }

            if (!pTarget.IsAlive)
            {
                int dwDieWay = m_pOwner.IsSimpleMagicAtk() ? 3 : 1;
                if (nDamage > pTarget.MaxLife / 3)
                {
                    dwDieWay = 2;
                }

                m_pOwner.Kill(pTarget, m_pOwner.IsBowman() ? 5 : (uint)dwDieWay);
            }

            if (pOwnerUser != null && pOwnerUser.QueryStatus(FlagInt.FATAL_STRIKE) != null)
            {
                DestroyAutoAttack();
            }

            return(true);
        }
        private void GoButton_Click(object sender, RoutedEventArgs e)
        {
            FileSystemStockProvider provider = new FileSystemStockProvider(@"C:\Data\TEST.txt");
            var stockPrices = provider.GetData().Take(20);
            this.StockPriceDataGrid.ItemsSource = stockPrices;

            var adjustedClosePrices = from stockPrice in stockPrices
                    select stockPrice.Item7;

            var dates = from stockPrice in stockPrices.Skip(2)
                                     select new { stockPrice.Item1 };

            var calculations = new Calculations();
            var movingAverage = calculations.MovingAverage(adjustedClosePrices, 3);
            var movingAverages = dates.Zip(movingAverage, (d, p) => new { date=d.Item1, price=p});

            var bollingerBands = calculations.BollingerBands(adjustedClosePrices, 3);
            var upperBandBands = dates.Zip(bollingerBands, (d, bb) => new { date = d.Item1, upperBand = bb.Item1 + (bb.Item2 * 2) });
            var lowerBandBands = dates.Zip(bollingerBands, (d, bb) => new { date = d.Item1, lowerBand = bb.Item1 + (bb.Item2 * 2) * -1 });

            this.stockPriceLineGraph.DependentValuePath = "price";
            this.stockPriceLineGraph.IndependentValuePath = "date";
            this.stockPriceLineGraph.ItemsSource = movingAverages;

            this.stockPriceLineGraph2.DependentValuePath = "upperBand";
            this.stockPriceLineGraph2.IndependentValuePath = "date";
            this.stockPriceLineGraph2.ItemsSource = upperBandBands;

            this.stockPriceLineGraph3.DependentValuePath = "lowerBand";
            this.stockPriceLineGraph3.IndependentValuePath = "date";
            this.stockPriceLineGraph3.ItemsSource = lowerBandBands;

            var latestPrice = stockPrices.Last();
            var adjustedClose = latestPrice.Item7;
            var closestDollar = Math.Round(adjustedClose, 0);

            var theGreeks = new List<GreekData>();
            for (int i = 0; i < 5; i++)
            {
                var greekData = new GreekData();
                greekData.StrikePrice = closestDollar - i;
                theGreeks.Add(greekData);
                greekData = new GreekData();
                greekData.StrikePrice = closestDollar + i;
                theGreeks.Add(greekData);
            }
            theGreeks.Sort((greek1,greek2)=>greek1.StrikePrice.CompareTo(greek2.StrikePrice));

            foreach (var greekData in theGreeks)
            {
                var inputData =
                    new BlackScholesInputData(adjustedClose, greekData.StrikePrice, .5, .01, .3);
                greekData.DeltaCall = calculations.BlackScholesDelta(inputData, PutCallFlag.Call);
                greekData.DeltaPut = calculations.BlackScholesDelta(inputData, PutCallFlag.Put);
                greekData.Gamma = calculations.BlackScholesGamma(inputData);
                greekData.RhoCall = calculations.BlackScholesRho(inputData, PutCallFlag.Call);
                greekData.RhoPut = calculations.BlackScholesRho(inputData, PutCallFlag.Put);
                greekData.ThetaCall = calculations.BlackScholesTheta(inputData, PutCallFlag.Call);
                greekData.ThetaPut = calculations.BlackScholesTheta(inputData, PutCallFlag.Put);
                greekData.Vega = calculations.BlackScholesVega(inputData);

            }

            this.TheGreeksDataGrid.ItemsSource = theGreeks;

            var blackScholes = new List<BlackScholesData>();
            for (int i = 0; i < 5; i++)
            {
                var blackScholesData = new BlackScholesData();
                blackScholesData.StrikePrice = closestDollar - i;
                blackScholes.Add(blackScholesData);
                blackScholesData = new BlackScholesData();
                blackScholesData.StrikePrice = closestDollar + i;
                blackScholes.Add(blackScholesData);
            }
            blackScholes.Sort((bsmc1, bsmc2) => bsmc1.StrikePrice.CompareTo(bsmc2.StrikePrice));

            var random = new System.Random();
            List<Double> randomData = new List<double>();
            for (int i = 0; i < 1000; i++)
            {
                randomData.Add(random.NextDouble());
            }

            foreach (var blackScholesMonteCarlo in blackScholes)
            {
                var blackScholesInputData =
                    new BlackScholesInputData(adjustedClose, blackScholesMonteCarlo.StrikePrice, .5, .01, .3);
                var monteCarloInputData =
                    new MonteCarloInputData(adjustedClose, blackScholesMonteCarlo.StrikePrice, .5, .01, .3);

                blackScholesMonteCarlo.Call = calculations.BlackScholes(blackScholesInputData, PutCallFlag.Call);
                blackScholesMonteCarlo.Put = calculations.BlackScholes(blackScholesInputData, PutCallFlag.Put);
                blackScholesMonteCarlo.MonteCarlo = calculations.MonteCarlo(monteCarloInputData, randomData);
            }

            this.BlackScholesDataGrid.ItemsSource = blackScholes;
        }
        public int CalcAttackPower(IRole attacker, IRole attacked, ref InteractionEffect pSpecial)
        {
            if (attacked is Character)
            {
                Character pUser = attacked as Character;
                if (pUser.QueryTransformation != null && pUser.QueryTransformation.Lookface == 223)
                {
                    return(1);
                }
            }

            if (m_pOwner.Map.IsLineSkillMap())
            {
                return(1);
            }

            if (attacked.QueryStatus(FlagInt.VORTEX) != null)
            {
                return(1);
            }

            int nAttack = 0;

            if (Calculations.ChanceCalc(50))
            {
                nAttack = attacker.MaxAttack - ThreadSafeRandom.RandGet(1, Math.Max(1, attacker.MaxAttack - attacker.MinAttack) / 2 + 1);
            }
            else
            {
                nAttack = attacker.MinAttack + ThreadSafeRandom.RandGet(1, Math.Max(1, attacker.MaxAttack - attacker.MinAttack) / 2 + 1);
            }

            if (attacker is Character && attacked is Character && (attacker as Character).IsBowman())
            {
                nAttack = (int)(nAttack / 1.5f);
            }

            // handle physical status
            if (attacker.QueryStatus(FlagInt.STIG) != null)
            {
                float tPower = attacker.QueryStatus(FlagInt.STIG).Power;
                if (tPower > 30000)
                {
                    tPower  = (tPower - 30000) / 100f;
                    nAttack = (int)(nAttack * tPower);
                }
                else
                {
                    nAttack += (short)tPower;
                }
            }

            int nRawDefense = attacked.Defense;
            int nDef        = attacked.AdjustDefense(nRawDefense);

            if (attacker.QueryStatus(FlagInt.OBLIVION) != null &&
                !(attacked is Character) &&
                ((attacked is Monster) && !(attacked as Monster).IsBoss))
            {
                nAttack *= 2;
            }

            if (attacker.QueryStatus(FlagInt.FATAL_STRIKE) != null &&
                ((!attacked.IsDynaNpc() && !(attacked is Character))))
            {
                float tPower = attacker.QueryStatus(FlagInt.FATAL_STRIKE).Power;
                if (tPower > 30000)
                {
                    tPower  = (tPower - 30000) / 100f;
                    nAttack = (int)(nAttack * tPower);
                }
                else
                {
                    nAttack += (short)tPower;
                }

                if (attacked is Monster)
                {
                    Monster pMob = attacked as Monster;
                    if (pMob.IsGuard())
                    {
                        nAttack /= 10;
                    }
                }
            }

            if (attacker.QueryStatus(FlagInt.VORTEX) != null && !attacked.IsDynaNpc() && !(attacked is Character))
            {
                float tPower = attacker.QueryStatus(FlagInt.VORTEX).Power;
                if (tPower > 30000)
                {
                    tPower  = (tPower - 30000) / 100f;
                    nAttack = (int)(nAttack * tPower);
                }
                else
                {
                    nAttack += (short)tPower;
                }
            }

            if (attacker.QueryStatus(FlagInt.SUPERMAN) != null &&
                (!attacked.IsDynaNpc() && !(attacked is Character)))
            {
                float tPower = attacker.QueryStatus(FlagInt.SUPERMAN).Power;
                if (tPower > 30000)
                {
                    tPower  = (tPower - 30000) / 100f;
                    nAttack = (int)(nAttack * tPower);
                }
                else
                {
                    nAttack += (short)tPower;
                }
            }

            if (attacked.QueryStatus(FlagInt.SHIELD) != null)
            {
                float tPower = attacked.QueryStatus(FlagInt.SHIELD).Power;
                if (tPower > 30000)
                {
                    tPower = (tPower - 30000) / 100f;
                    nDef   = (int)(nDef * tPower);
                }
                else
                {
                    nDef += (short)tPower;
                }
            }

            if (attacker.Magics.QueryMagic() != null)
            {
                float tPower = attacker.Magics.QueryMagic().QueryPower();
                if (tPower > 30000)
                {
                    tPower  = (tPower - 30000) / 100f;
                    nAttack = (int)(nAttack * tPower);
                }
                else
                {
                    nAttack += (short)tPower;
                }
            }

            //float reduction = attacked.GetReduceDamage();
            int   nDamage = (int)((nAttack - nDef) * (1f - (attacked.GetReduceDamage() / 100f)));
            float tort    = (attacked.GetTortoiseGemEffect() / 100f);

            nDamage = (int)(nDamage * (1f - tort));

            if (nDamage <= 0)
            {
                nDamage = 7;
            }

            if (attacker is Character && attacked.IsMonster())
            {
                nDamage = CalcDamageUser2Monster(nAttack, nDef, attacker.Level, attacked.Level);
                nDamage = attacked.AdjustWeaponDamage(nDamage);
                nDamage = AdjustMinDamageUser2Monster(nDamage, attacker, attacked);
            }
            else if (attacker.IsMonster() && attacked is Character)
            {
                nDamage = CalcDamageMonster2User(nAttack, nDef, attacker.Level, attacked.Level);
                nDamage = attacked.AdjustWeaponDamage(nDamage);
                nDamage = AdjustMinDamageMonster2User(nDamage, attacker, attacked);
            }
            else
            {
                nDamage = attacked.AdjustWeaponDamage(nDamage);
            }

            //if (attacker is Character && attacked is Character && attacker.BattlePower < attacked.BattlePower)
            //{
            //    nDamage /= 2;
            //}

            #region Block, Critical, Break
            if (attacker.BattlePower < attacked.BattlePower)
            {
                if (attacked is Character)
                {
                    // Break (Pene is on the magic code)
                    // Break through the battle power cap...
                    // If the break fails, the damage is reduced by half.
                    if (attacked.Counteraction < attacker.Breakthrough)
                    {
                        if (!Calculations.ChanceCalc((float)(attacker.Breakthrough - attacked.Counteraction) / 10))
                        {
                            nDamage /= 2;
                        }
                        else
                        {
                            pSpecial |= InteractionEffect.BREAKTHROUGH;
                        }
                        //Owner.SendMessage(string.Format("Break: {0} Counter: {1} Difference: {2}%", GetBreakthrough(), pTarget.GetCounteraction(), (float)(GetBreakthrough() - pTarget.GetCounteraction()) / 10));
                    }
                    else
                    {
                        nDamage /= 2;
                    }
                }
            }

            // Critical is enabled on every monster. :)
            // Multiply the damage by 1.5
            if (attacker.CriticalStrike > attacked.Immunity)
            {
                if (Calculations.ChanceCalc((float)(attacker.CriticalStrike - attacked.Immunity) / 100))
                {
                    nDamage   = (int)(nDamage * 1.5f);
                    pSpecial |= InteractionEffect.CRITICAL_STRIKE;
                }
            }

            if (attacked.Block > 0 && Calculations.ChanceCalc((float)attacked.Block / 100))
            {
                nDamage  /= 10;
                pSpecial |= InteractionEffect.BLOCK;
            }

            if (QueryMagic() != null && QueryMagic().GetElement() > ElementType.NONE)
            {
                switch (QueryMagic().GetElement())
                {
                case ElementType.WATER:
                    pSpecial |= InteractionEffect.WATER_RESIST;
                    break;

                case ElementType.FIRE:
                    pSpecial |= InteractionEffect.FIRE_RESIST;
                    break;

                case ElementType.WOOD:
                    pSpecial |= InteractionEffect.WOOD_RESIST;
                    break;

                case ElementType.METAL:
                    pSpecial |= InteractionEffect.METAL_RESIST;
                    break;

                case ElementType.EARTH:
                    pSpecial |= InteractionEffect.EARTH_RESIST;
                    break;
                }
            }
            #endregion

            if (attacker is Monster && QueryMagic() != null && QueryMagic().GetElement() > ElementType.NONE)
            {
                switch (QueryMagic().GetElement())
                {
                case ElementType.WATER:
                {
                    nDamage = (int)(nDamage * (1 - (attacked.WaterResistance / 100f)));
                    break;
                }

                case ElementType.FIRE:
                {
                    nDamage = (int)(nDamage * (1 - (attacked.FireResistance / 100f)));
                    break;
                }

                case ElementType.EARTH:
                {
                    nDamage = (int)(nDamage * (1 - (attacked.EarthResistance / 100f)));
                    break;
                }

                case ElementType.WOOD:
                {
                    nDamage = (int)(nDamage * (1 - (attacked.WoodResistance / 100f)));
                    break;
                }

                case ElementType.METAL:
                {
                    nDamage = (int)(nDamage * (1 - (attacked.MetalResistance / 100f)));
                    break;
                }
                }
            }

            if (attacker is Character)
            {
                nDamage += attacker.AddFinalAttack;
            }

            if (attacked is Character)
            {
                nDamage -= attacked.AddFinalDefense;
            }

            if (attacked is Monster)
            {
                nDamage = (int)Math.Min(nDamage, attacked.MaxLife * 700);
            }

            if (nDamage <= 0)
            {
                nDamage = 1;
            }

            return(nDamage);
        }
        /// <summary>
        /// Print a receipt for each gift (one page for each donor) in the batch
        /// </summary>
        /// <param name="AGiftTDS"></param>
        public void PrintGiftBatchReceipts(GiftBatchTDS AGiftTDS)
        {
            AGiftBatchRow GiftBatchRow = AGiftTDS.AGiftBatch[0];

            DataView GiftView = new DataView(AGiftTDS.AGift);

            //AGiftTDS.AGift.DefaultView.RowFilter
            GiftView.RowFilter = String.Format("{0}={1} and {2}={3}",
                                               AGiftTable.GetLedgerNumberDBName(), GiftBatchRow.LedgerNumber,
                                               AGiftTable.GetBatchNumberDBName(), GiftBatchRow.BatchNumber);
            String       ReceiptedDonorsList             = "";
            List <Int32> ReceiptedGiftTransactions       = new List <Int32>();
            SortedList <Int64, AGiftTable> GiftsPerDonor = new SortedList <Int64, AGiftTable>();

            foreach (DataRowView rv in GiftView)
            {
                AGiftRow GiftRow = (AGiftRow)rv.Row;

                // this will be true for gift reversals for which we do not need a receipt
                if (GiftRow.ReceiptPrinted)
                {
                    continue;
                }

                bool   ReceiptEachGift;
                String ReceiptLetterFrequency;
                bool   EmailGiftStatement;
                bool   AnonymousDonor;

                TRemote.MPartner.Partner.ServerLookups.WebConnectors.GetPartnerReceiptingInfo(
                    GiftRow.DonorKey,
                    out ReceiptEachGift,
                    out ReceiptLetterFrequency,
                    out EmailGiftStatement,
                    out AnonymousDonor);

                if (ReceiptEachGift)
                {
                    // I want to print a receipt for this gift,
                    // but if there's already one queued for this donor,
                    // I'll add this gift onto the existing receipt.

                    if (!GiftsPerDonor.ContainsKey(GiftRow.DonorKey))
                    {
                        GiftsPerDonor.Add(GiftRow.DonorKey, new AGiftTable());
                    }

                    AGiftRow NewRow = GiftsPerDonor[GiftRow.DonorKey].NewRowTyped();
                    DataUtilities.CopyAllColumnValues(GiftRow, NewRow);
                    GiftsPerDonor[GiftRow.DonorKey].Rows.Add(NewRow);
                } // if receipt required
            }     // foreach gift

            if (GiftsPerDonor.Count == 0) // no receipts needed
            {
                return;
            }

            String HtmlDoc = "";

            OpenFileDialog DialogOpen = new OpenFileDialog();

            if (Directory.Exists(TAppSettingsManager.GetValue("Formletters.Path")))
            {
                DialogOpen.InitialDirectory = TAppSettingsManager.GetValue("Formletters.Path");
            }

            DialogOpen.Filter           = Catalog.GetString("HTML file (*.html)|*.html;*.htm");
            DialogOpen.RestoreDirectory = true;
            DialogOpen.Title            = Catalog.GetString("Select the template for the gift receipt");

            if (DialogOpen.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            string HTMLTemplateFilename = DialogOpen.FileName;
            int    NumberOfDonors       = 0;

            foreach (Int64 DonorKey in GiftsPerDonor.Keys)
            {
                String        DonorShortName;
                TPartnerClass DonorClass;
                TRemote.MPartner.Partner.ServerLookups.WebConnectors.GetPartnerShortName(DonorKey, out DonorShortName, out DonorClass);
                DonorShortName = Calculations.FormatShortName(DonorShortName, eShortNameFormat.eReverseShortname);

                string HtmlPage = TRemote.MFinance.Gift.WebConnectors.PrintGiftReceipt(
                    GiftBatchRow.CurrencyCode,
                    DonorShortName,
                    DonorKey,
                    DonorClass,
                    GiftsPerDonor[DonorKey],
                    HTMLTemplateFilename
                    );

                TFormLettersTools.AttachNextPage(ref HtmlDoc, HtmlPage);
                NumberOfDonors++;
                ReceiptedDonorsList += String.Format("{0}: {1}{2}", NumberOfDonors, DonorShortName, Environment.NewLine);

                foreach (AGiftRow GiftRow in GiftsPerDonor[DonorKey].Rows)
                {
                    ReceiptedGiftTransactions.Add(GiftRow.GiftTransactionNumber);
                }
            }

            TFormLettersTools.CloseDocument(ref HtmlDoc);

            if (ReceiptedGiftTransactions.Count > 0)
            {
                TFrmReceiptControl.PreviewOrPrint(HtmlDoc);

                string Message = Catalog.GetPluralString("Was a receipt to the following donor printed correctly?",
                                                         "Were receipts to the following donors printed correctly?", NumberOfDonors);

                if (MessageBox.Show(
                        Message + "\n\n" +
                        ReceiptedDonorsList,
                        Catalog.GetString("Receipt Printing"),
                        MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    foreach (Int32 Trans in ReceiptedGiftTransactions)
                    {
                        TRemote.MFinance.Gift.WebConnectors.MarkReceiptsPrinted(
                            GiftBatchRow.LedgerNumber,
                            GiftBatchRow.BatchNumber,
                            Trans);
                    }
                }
            }
        }
Beispiel #29
0
        public static Column Optimise(BackgroundWorker worker, Column column, bool[] shapes, bool[] activ, string[] mins, string[] maxs, string[] incrs, List <Concrete> concreteGrades, List <int> barDiameters,
                                      List <int> linkDiameters, int Nmax, double Tinit, double[] Ws, double[] Fs, double alpha, bool square, double variance = 1, bool allLoads = false, bool[] fireMethods = null)

        {
            Calculations calc      = new Calculations(column);
            double       costRef   = calc.GetCost()[3];
            double       carbonRef = calc.GetEmbodiedCarbon()[2];

            fireMethods = fireMethods ?? new bool[] { true, false, false, false };

            double Wcarb = Ws[1];
            double Wcost = Ws[0];
            double Fcarb = Fs[1];
            double Fcost = Fs[0];

            var    chekcs = Objective(column, carbonRef, costRef, Wcost, Fcost, Wcarb, Fcarb, allLoads, fireMethods);
            double f      = chekcs.Item1;

            column.CapacityCheck    = chekcs.Item2;
            column.FireCheck        = chekcs.Item3;
            column.SpacingCheck     = chekcs.Item4;
            column.MinMaxSteelCheck = chekcs.Item5;
            column.MinRebarCheck    = chekcs.Item6;

            double T = Tinit;
            int    t = 0;

            Column BestCol = column.Clone();

            BestCol.Cost = f;
            double fBest = f;

            List <int> shapesInd = new List <int>();

            for (int i = 0; i < shapes.Length; i++)
            {
                if (shapes[i])
                {
                    shapesInd.Add(i);
                }
            }
            int shapeIdx = 0;

            column.Shape = (shapesInd[shapeIdx] == 0) ? GeoShape.Rectangular : ((shapesInd[shapeIdx] == 1) ? GeoShape.Circular : GeoShape.Polygonal);

            if (activ[6])
            {
                BestCol.ConcreteGrade = concreteGrades[1];
            }

            Column[] report = new Column[4];

            while (t < Nmax)
            {
                int NN = activ.Count();

                // update of X
                Column     ColTemp = column.Clone();
                List <int> eps     = NormalRand(NN + 1, variance);

                if (activ[0])
                {
                    ColTemp.LX = Math.Max(Convert.ToDouble(mins[0]), Math.Min(column.LX + eps[0] * Convert.ToDouble(incrs[0]), Convert.ToDouble(maxs[0])));
                }
                if (activ[1])
                {
                    ColTemp.LY = square ? ColTemp.LX : Math.Max(Convert.ToDouble(mins[1]), Math.Min(column.LY + eps[1] * Convert.ToDouble(incrs[1]), Convert.ToDouble(maxs[1])));
                }
                if (activ[2])
                {
                    ColTemp.NRebarX = Math.Max(Convert.ToInt32(mins[2]), Math.Min(column.NRebarX + eps[2], Convert.ToInt32(maxs[2])));
                }
                if (activ[3])
                {
                    ColTemp.NRebarX = Math.Max(Convert.ToInt32(mins[3]), Math.Min(column.NRebarX + eps[3], Convert.ToInt32(maxs[3])));
                }
                if (activ[4])
                {
                    ColTemp.Diameter = Math.Max(Convert.ToDouble(mins[4]), Math.Min(column.Diameter + eps[4] * Convert.ToDouble(incrs[2]), Convert.ToDouble(maxs[4])));
                }
                if (activ[5])
                {
                    ColTemp.NRebarCirc = Math.Max(Convert.ToInt32(mins[5]), Math.Min(column.NRebarX + eps[5], Convert.ToInt32(maxs[5])));
                }
                if (activ[6])
                {
                    ColTemp.Radius = Math.Max(Convert.ToDouble(mins[6]), Math.Min(column.Radius + eps[6] * Convert.ToDouble(incrs[3]), Convert.ToDouble(maxs[6])));
                }
                if (activ[7])
                {
                    ColTemp.Edges = Math.Max(Convert.ToInt32(mins[7]), Math.Min(column.Edges + eps[7], Convert.ToInt32(maxs[7])));
                }

                if (activ[8])
                {
                    int minidx = barDiameters.IndexOf(Convert.ToInt32(mins[8]));
                    int maxidx = barDiameters.IndexOf(Convert.ToInt32(maxs[8]));
                    int idx    = barDiameters.IndexOf(column.BarDiameter);
                    ColTemp.BarDiameter = barDiameters[Math.Max(minidx, Math.Min(idx + eps[8], maxidx))];
                }
                if (activ[9])
                {
                    int minidx = linkDiameters.IndexOf(Convert.ToInt32(mins[9]));
                    int maxidx = linkDiameters.IndexOf(Convert.ToInt32(maxs[9]));
                    int idx    = linkDiameters.IndexOf(column.BarDiameter);
                    ColTemp.LinkDiameter = linkDiameters[Math.Max(minidx, Math.Min(idx + eps[9], maxidx))];
                }
                if (activ[10])
                {
                    List <string> grades = concreteGrades.Select(x => x.Name).ToList();
                    int           minidx = grades.IndexOf(mins[10]);
                    int           maxidx = grades.IndexOf(maxs[10]);
                    int           idx    = grades.IndexOf(column.ConcreteGrade.Name);
                    ColTemp.ConcreteGrade = concreteGrades[Math.Max(minidx, Math.Min(idx + eps[10], maxidx))];
                }

                if (shapesInd.Count > 1)
                {
                    int n  = shapesInd.Count;
                    int xx = shapeIdx + eps[10];
                    shapeIdx = ((xx >= 0) ? xx % n : Math.Min(0, n - Math.Abs(xx) % n));

                    ColTemp.Shape = (shapesInd[shapeIdx] == 0) ? GeoShape.Rectangular : ((shapesInd[shapeIdx] == 1) ? GeoShape.Circular : GeoShape.Polygonal);
                }

                // delta f
                var res = Objective(ColTemp, carbonRef, costRef, Wcost, Fcost, Wcarb, Fcarb, allLoads, fireMethods);
                ColTemp.CapacityCheck    = res.Item2;
                ColTemp.FireCheck        = res.Item3;
                ColTemp.SpacingCheck     = res.Item4;
                ColTemp.MinMaxSteelCheck = res.Item5;
                ColTemp.MinRebarCheck    = res.Item6;
                double fp = res.Item1;
                double Df = fp - f;
                if (Df < 0)
                {
                    column      = ColTemp;
                    f          += Df;
                    column.Cost = f;
                }
                else
                {
                    Random rand = new Random();
                    double r    = rand.NextDouble();
                    double p    = Math.Exp(-Df / T);
                    if (p > r)
                    {
                        column      = ColTemp;
                        f          += Df;
                        column.Cost = f;
                    }
                }
                if (fp < fBest)
                {
                    BestCol      = ColTemp.Clone();
                    fBest        = fp;
                    BestCol.Cost = fBest;
                }
                T = alpha * T;
                t++;
                //Console.WriteLine(f);
                // transmission of results to main thread
                report[0] = column;
                //report[1] = f;
                report[2] = BestCol;
                //report[3] = fBest;

                worker.ReportProgress(0, report);
            }
            return(column);
        }
Beispiel #30
0
        /// <summary>
        /// match imported transactions from bank statement to an existing gift batch
        /// </summary>
        /// <returns>true while new matches are found</returns>
        private static bool MatchTransactionsToGiftBatch(BankImportTDS AMainDS)
        {
            bool newMatchFound = false;

            DataView GiftDetailWithoutAmountView = new DataView(AMainDS.AGiftDetail,
                                                                string.Empty,
                                                                BankImportTDSAGiftDetailTable.GetDonorKeyDBName() + "," +
                                                                BankImportTDSAGiftDetailTable.GetAlreadyMatchedDBName(),
                                                                DataViewRowState.CurrentRows);

            DataView GiftDetailByBatchNumberMatchStatus = new DataView(AMainDS.AGiftDetail,
                                                                       string.Empty,
                                                                       BankImportTDSAGiftDetailTable.GetAlreadyMatchedDBName(),
                                                                       DataViewRowState.CurrentRows);

            DataView TransactionsByBankAccountView = new DataView(AMainDS.AEpTransaction,
                                                                  string.Empty,
                                                                  BankImportTDSAEpTransactionTable.GetBankAccountNumberDBName() + "," +
                                                                  BankImportTDSAEpTransactionTable.GetBranchCodeDBName() + "," +
                                                                  BankImportTDSAEpTransactionTable.GetMatchActionDBName(),
                                                                  DataViewRowState.CurrentRows);

            foreach (BankImportTDSAEpTransactionRow transaction in AMainDS.AEpTransaction.Rows)
            {
                if (transaction.MatchAction == Ict.Petra.Shared.MFinance.MFinanceConstants.BANK_STMT_STATUS_UNMATCHED)
                {
                    DataRowView[] filteredRows = GiftDetailByBatchNumberMatchStatus.FindRows(new object[] { false });

                    BankImportTDSAGiftDetailRow BestMatch = null;
                    int BestMatchNumber = 0;

                    foreach (DataRowView rv in filteredRows)
                    {
                        BankImportTDSAGiftDetailRow detailrow = (BankImportTDSAGiftDetailRow)rv.Row;

                        int matchNumberDonorSurname =
                            MatchingWords(Calculations.FormatShortName(detailrow.DonorShortName,
                                                                       eShortNameFormat.eOnlySurname), transaction.AccountName);

                        if (matchNumberDonorSurname == 0)
                        {
                            // if surname does not match: ignore, just to be sure
                            // problem: will ignore umlaut etc. can be fixed for the next time by entering the bank account into OpenPetra
                            continue;
                        }

                        int matchNumberDonor = MatchingWords(detailrow.DonorShortName, transaction.AccountName) +
                                               matchNumberDonorSurname * 3;
                        int matchNumberRecipient = MatchingWords(detailrow.RecipientDescription, transaction.Description);

                        if ((matchNumberDonor > 0) && (matchNumberRecipient > 0) &&
                            ((matchNumberDonor > 1) || (matchNumberRecipient > 1)) &&
                            (matchNumberRecipient + matchNumberDonor > BestMatchNumber))
                        {
                            BestMatchNumber = matchNumberRecipient + matchNumberDonor;
                            BestMatch       = detailrow;
                        }
                    }

                    if (BestMatch != null)
                    {
                        // get all gifts of this donor, and all bank statement transactions
                        DataRowView[] GiftDetailWithoutAmount = GiftDetailWithoutAmountView.FindRows(
                            new object[] { BestMatch.DonorKey, false });

                        DataRowView[] TransactionsByBankAccount = TransactionsByBankAccountView.FindRows(
                            new object[] { transaction.BankAccountNumber, transaction.BranchCode, MFinanceConstants.BANK_STMT_STATUS_UNMATCHED });

                        while (MatchOneDonor(AMainDS, GiftDetailWithoutAmount, TransactionsByBankAccount))
                        {
                            GiftDetailWithoutAmount = GiftDetailWithoutAmountView.FindRows(
                                new object[] { BestMatch.DonorKey, false });

                            TransactionsByBankAccount = TransactionsByBankAccountView.FindRows(
                                new object[] { transaction.BankAccountNumber, transaction.BranchCode, MFinanceConstants.BANK_STMT_STATUS_UNMATCHED });

                            newMatchFound = true;
                        }
                    }
                }
            }

            return(newMatchFound);
        }
Beispiel #31
0
        public decimal GetPreTaxServicesTotal()
        {
            var plainSum = GetPlainSum();

            return(CalculateServices(Calculations.Where(x => !x.IncludeTax), plainSum));
        }
 public virtual double GetAngle(Body body)
 {
     return(Calculations.GetAngle(
                body.Joints[activeJoint.KinectJoint.Type], body.Joints[activeJoint.KinectJoint.Parent.Type], body.Joints[activeJoint.KinectJoint.Children.First().Value.Type]
                ));
 }
Beispiel #33
0
 public decimal GetCalculationTotal(string s)
 {
     return(Calculations.Where(x => string.IsNullOrEmpty(s) || x.Name == s).Sum(x => x.CalculationAmount));
 }
Beispiel #34
0
        public async Task <JsonResult> GuessCheck(int imageId, decimal guessPercent, int userId,
                                                  int currentTime, int phase)
        {
            var getImageRequest  = new HttpRequestMessage(HttpMethod.Get, $"/api/image/{imageId}");
            var getImageResponse = await _db.BuildApiResponse <ImageModel>(getImageRequest, _session._accessToken);

            if (getImageResponse.Status == HttpStatusCode.OK)
            {
                var  correctPercent = (double)getImageResponse.Content.DecayRate;
                bool result         = false;

                //convert to percentage
                double userGuesdecimal = guessPercent == 0
                    ? 0.0
                    : ((double)guessPercent / 100);

                //if range sits between 10 then answer is correct
                if (userGuesdecimal >= (correctPercent - 0.05) && userGuesdecimal <= (correctPercent + 0.05))
                {
                    result = true;
                }
                else
                {
                    result = false;
                }

                var userGuessBinding = new
                {
                    GuessPercentage = (guessPercent / 100),
                    UserId          = userId,
                    ImageId         = imageId,
                    Phase           = phase
                };

                var postGuessRequest = new HttpRequestMessage(HttpMethod.Post, "/api/usersGuess")
                {
                    Content = new StringContent(JsonSerializer.Serialize(userGuessBinding), Encoding.UTF8, "application/json")
                };
                var postGuessResponse = await _db.BuildApiResponse <UserGuessModel>(postGuessRequest, _session._accessToken);

                if (postGuessResponse.Status == HttpStatusCode.OK)
                {
                    //get users guesses list so there isn't any cheating via JS browser methods
                    var getUserGuessRequest  = new HttpRequestMessage(HttpMethod.Get, $"/api/usersGuess/{userId}/{phase}");
                    var getUserGuessResponse = await _db.BuildApiResponse <List <UserGuessModel> >(getUserGuessRequest, _session._accessToken);

                    var dif = 0.0;
                    if (getUserGuessResponse.Status == HttpStatusCode.OK)
                    {
                        //find difference
                        if (getUserGuessResponse.Content.Count >= 10 && phase == (int)Phase.TWO)
                        {
                            var list = getUserGuessResponse.Content.OrderBy(x => x.UsersGuessId).Skip(getUserGuessResponse.Content.Count - 10)
                                       .ToList();
                            dif = Calculations.FindAverageDifferenceOfList(list);
                        }
                        else if (phase == (int)Phase.ONE || phase == (int)Phase.THREE)
                        {
                            var list = getUserGuessResponse.Content.OrderBy(x =>
                                                                            x.UsersGuessId)
                                       .ToList();
                            dif = Calculations.FindAverageDifferenceOfList(list);
                        }


                        //save data so if user exits/refreshes can come back to this point
                        var time            = new TimeSpan(0, 0, currentTime);
                        var editUserBinding = new UpdateUserBinding()
                        {
                            FinishingPercent = ((decimal)dif),
                            PictureCycled    = getUserGuessResponse.Content.Count,
                            Time             = DateTime.UtcNow.Date.Add(time),
                            Phase            = (byte)phase
                        };

                        var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(editUserBinding));

                        var updateUserRequest = new HttpRequestMessage(HttpMethod.Post, $"/api/user/{userId}")
                        {
                            Content = new StringContent(stringPayload, Encoding.UTF8, "application/json")
                        };
                        var updateUserResponse = await _db.BuildApiResponse <UserModel>(updateUserRequest, _session._accessToken);


                        var returnValues = new
                        {
                            Answer         = result,
                            Count          = getUserGuessResponse.Content.Count,
                            CorrectPercent = Math.Round((correctPercent * 100)),
                            Total          = Math.Round(dif, 2),
                            Error          = "",
                            Success        = true
                        };
                        return(Json(returnValues));
                    }
                    else
                    {
                        return(Json(new
                        {
                            Error = getUserGuessResponse.Status + ": " + getUserGuessResponse.Error,
                            Success = false
                        }));
                    }
                }
                else
                {
                    return(Json(new
                    {
                        Error = postGuessResponse.Status + ": " + postGuessResponse.Error,
                        Success = false
                    }));
                }
            }

            return(Json(new
            {
                Error = getImageResponse.Status + ": " + getImageResponse.Error,
                Success = false
            }));
        }
        /// <summary>
        /// Set the text of the specified results label (thread safe)
        /// </summary>
        /// <param name="labelID"></param>
        /// <param name="data"></param>
        private void SetLabelValue(Calculations labelID, object data)
        {
            if (this.InvokeRequired)
            {
                UpdateLabelCallback callback = new UpdateLabelCallback(SetLabelValue);
                object[] args = new object[2];
                args[0] = labelID;
                args[1] = data;
                this.Invoke(callback, args);
            }
            else
            {
                Label label = _calcValueLabels[(int)labelID];

                string labelText = "";
                try
                {
                    decimal value = (decimal)data;
                    if (labelID == Calculations.SelectedValues)
                    {
                        labelText = value.ToString();
                    }
                    else
                    {
                        labelText = new IskAmount(value).ToString();
                    }
                }
                catch
                {
                    labelText = data.ToString();
                }
                label.Text = labelText;
            }
        }
 public void Calculator_Division_MustReturnCorrectResult()
 {
     Assert.Equal(1, Calculations.Division(5, 5));
 }