Example #1
0
        private ShippingRate CreateShippingRate(
            Guid methodId,
            ShippingMethodDto shippingMethod,
            EstimateResult <ShipmentEstimate> result)
        {
            var estimate                    = result.Estimates.First();
            var priceExclTax                = shippingMethod.GetShippingMethodParameterValue(ParameterNames.PriceExclTax) == "True";
            var usesAdditionalServices      = !string.IsNullOrEmpty(shippingMethod.GetShippingMethodParameterValue(ParameterNames.AdditionalServices));
            var priceWithAdditionalServices = !priceExclTax
                ? (decimal)estimate.PackagePrice.PackagePriceWithAdditionalServices.AmountWithVAT
                : (decimal)estimate.PackagePrice.PackagePriceWithAdditionalServices.AmountWithoutVAT;
            var priceWithoutAdditionalServices = !priceExclTax
                ? (decimal)estimate.PackagePrice.PackagePriceWithoutAdditionalServices.AmountWithVAT
                : (decimal)estimate.PackagePrice.PackagePriceWithoutAdditionalServices.AmountWithoutVAT;

            var amount = AdjustPrice(shippingMethod, usesAdditionalServices ? priceWithAdditionalServices :
                                     priceWithoutAdditionalServices);

            var moneyAmount = new Money(
                amount,
                new Currency(estimate.PackagePrice.CurrencyIdentificationCode));

            return(new BringShippingRate(
                       methodId,
                       estimate.GuiInformation.DisplayName,
                       estimate.GuiInformation.MainDisplayCategory,
                       estimate.GuiInformation.SubDisplayCategory,
                       estimate.GuiInformation.DescriptionText,
                       estimate.GuiInformation.HelpText,
                       estimate.GuiInformation.Tip,
                       estimate.ExpectedDelivery.ExpectedDeliveryDate,
                       moneyAmount));
        }
Example #2
0
        public async Task <EstimateResult <IEstimate> > FindEstimatesAsync(EstimateQuery query)
        {
            string jsonResponse;
            var    requestUri = CreateRequestUri(query);

            using (var client = CreateClient())
            {
                try
                {
                    jsonResponse = await client.GetStringAsync(requestUri).ConfigureAwait(false);
                }
                catch (HttpRequestException rEx)
                {
                    // TODO: parse errors from here and create strongly typed error messages
                    // Could be object with Code, Description and HTML (full message received from Bring)
                    // Some errors are validation errors like - invalid postal code, invalid city etc., but some are exceptions.
                    // Wrap and return only validation errors, others throw further.
                    // Wrap configuration errors and throw them with details, but other errors throw as is.
                    // http://developer.bring.com/additionalresources/errorhandling.html?from=shipping
                    return(EstimateResult <IEstimate> .CreateFailure(rEx.Message));
                }
            }
            var response  = JsonConvert.DeserializeObject <ShippingResponse>(jsonResponse);
            var estimates = response.Product.Select(MapProduct).Cast <IEstimate>();

            return(EstimateResult <IEstimate> .CreateSuccess(estimates));
        }
Example #3
0
        public EstimateResult EstimateScore(TasteValue model, List <VegetableDosing> VegModel)
        {
            EstimateResult Result          = new EstimateResult();
            List <string>  DescriptionList = new List <string>();
            List <string>  VegCatagories   = new List <string>();

            foreach (var item in VegModel)
            {
                VegCatagories.Add(item.VegValue.Name);
            }
            var response = new SQL().GetVegetableFlavour(VegCatagories);
            int number   = response.Where(x => x.FlavourName != null || x.FlavourName != "").Count();

            int saltyScore, sweetScore, sourScore, spicyScore, bitterScore, oilScore, FlavourScore;

            DescriptionList.Add(FlavourEstimate(number, out FlavourScore));
            DescriptionList.Add(SaltyEstimate(model.Salty, out saltyScore));
            DescriptionList.Add(SweetEstimate(model.Sweet, out sweetScore));
            DescriptionList.Add(SourEstimate(model.Sour, out sourScore));
            DescriptionList.Add(SpicyEstimate(model.Spicy, out spicyScore));
            DescriptionList.Add(BitterEstimate(model.Bitter, out bitterScore));
            DescriptionList.Add(OilEstimate(model.Oil, out oilScore));
            Result.Description = string.Join(", ", DescriptionList.ToArray());
            Result.Score       = 95 - saltyScore - sweetScore - sourScore - spicyScore - bitterScore - oilScore;
            return(Result);
        }
Example #4
0
        public async Task <EstimateResult <IEstimate> > FindEstimatesAsync(EstimateQuery query)
        {
            HttpResponseMessage responseMessage = null;
            string jsonResponse = null;

            var requestUri = CreateRequestUri(query);
            var cacheKey   = CreateCacheKey(requestUri);

            if (HttpRuntime.Cache.Get(cacheKey) is EstimateResult <IEstimate> cached)
            {
                return(await Task.FromResult(cached));
            }

            using (var client = CreateClient())
            {
                try
                {
                    responseMessage = await client.GetAsync(requestUri).ConfigureAwait(false);

                    jsonResponse = await responseMessage.Content.ReadAsStringAsync();

                    responseMessage.EnsureSuccessStatusCode();
                }
                catch (HttpRequestException)
                {
                    if (string.IsNullOrEmpty(jsonResponse))
                    {
                        var responseError = new ResponseError(responseMessage?.StatusCode ?? HttpStatusCode.InternalServerError);
                        return(EstimateResult <IEstimate> .CreateFailure(responseError));
                    }
                }
            }

            var response = JsonConvert.DeserializeObject <ShippingResponse>(jsonResponse, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });

            var errors = response.GetAllErrors().ToArray();

            if (errors.Any())
            {
                return(EstimateResult <IEstimate> .CreateFailure(errors));
            }

            var products  = response.GetAllProducts();
            var estimates = products.Select(MapProduct).Cast <IEstimate>().ToList();
            var result    = EstimateResult <IEstimate> .CreateSuccess(estimates);

            HttpRuntime.Cache.Insert(cacheKey, result, null, DateTime.UtcNow.AddMinutes(2), Cache.NoSlidingExpiration);

            return(result);
        }
Example #5
0
        public EstimateResult EvaluteRecipe(RecipeViewModel Recipemodel)
        {
            Recipe          model   = new Recipe();
            GetMaterialData GetData = new GetMaterialData();

            model = GetData.TransData(Recipemodel);

            TasteCalculator   calculator = new TasteCalculator();
            List <TasteValue> TasteList  = new List <TasteValue>();
            TasteEstimate     TasteEst   = new TasteEstimate();

            TasteList.Add(calculator.VegtableCalculate(model.VegDosing));
            TasteList.Add(calculator.MeatCalculate(model.MeatDosings));
            TasteList.Add(calculator.SeasonCalculate(model.SeasonDosings));
            TasteList.Add(calculator.EggCalculate(model.EggDosings));
            EstimateResult result = TasteEst.EstimateScore(calculator.AvgCalculator(TasteList), model.VegDosing);

            return(result);
        }
Example #6
0
        /// <summary>
        /// Finds Bring Shipping estimates based on estimate query.
        /// </summary>
        /// <typeparam name="T">Type of estimates <see cref="IEstimate"/>.</typeparam>
        /// <param name="query">Query parameters of type <see cref="EstimateQuery"/>.</param>
        /// <returns>Estimate find result of type <see cref="EstimateResult{T}"/>.</returns>
        public async Task <EstimateResult <T> > FindAsync <T>(EstimateQuery query)
            where T : IEstimate
        {
            foreach (var handler in Settings.QueryHandlers)
            {
                if (handler.CanHandle(typeof(T)))
                {
                    var estimate = await handler.FindEstimatesAsync(query).ConfigureAwait(false);

                    if (estimate.Success)
                    {
                        return(EstimateResult <T> .CreateSuccess(estimate.Estimates.Cast <T>()));
                    }
                    return(EstimateResult <T> .CreateFailure(estimate.ErrorMessages));
                }
            }

            throw new Exception(string.Format("No matching query handler found for estimate type {0}", typeof(T).Name));
        }
        private ShippingRate CreateShippingRate(
            Guid methodId,
            ShippingMethodDto shippingMethod,
            EstimateResult <ShipmentEstimate> result)
        {
            var estimate = result.Estimates.First();
            var amount   = AdjustPrice(shippingMethod, (decimal)estimate.PackagePrice.PackagePriceWithAdditionalServices.AmountWithVAT);

            var moneyAmount = new Money(
                amount,
                new Currency(estimate.PackagePrice.CurrencyIdentificationCode));

            return(new BringShippingRate(
                       methodId,
                       estimate.GuiInformation.DisplayName,
                       estimate.GuiInformation.MainDisplayCategory,
                       estimate.GuiInformation.SubDisplayCategory,
                       estimate.GuiInformation.DescriptionText,
                       estimate.GuiInformation.HelpText,
                       estimate.GuiInformation.Tip,
                       estimate.ExpectedDelivery.ExpectedDeliveryDate,
                       moneyAmount));
        }
Example #8
0
        private ShippingRate CreateShippingRate(
            Guid methodId,
            ShippingMethodDto shippingMethod,
            EstimateResult <ShipmentEstimate> result)
        {
            var settings = _estimateSettingsFactory.CreateFrom(shippingMethod);
            var estimate = result.Estimates.First();

            var usesAdditionalServices = settings.AdditionalServices.Any();
            var packagePrice           = estimate.Price.NetPrice ?? estimate.Price.ListPrice;

            var priceWithAdditionalServices = !settings.PriceExclTax
                ? (decimal)packagePrice.PriceWithAdditionalServices.AmountWithVAT
                : (decimal)packagePrice.PriceWithAdditionalServices.AmountWithoutVAT;

            var priceWithoutAdditionalServices = !settings.PriceExclTax
                ? (decimal)packagePrice.PriceWithoutAdditionalServices.AmountWithVAT
                : (decimal)packagePrice.PriceWithoutAdditionalServices.AmountWithoutVAT;

            var amount = AdjustPrice(shippingMethod, settings, usesAdditionalServices ? priceWithAdditionalServices :
                                     priceWithoutAdditionalServices);

            var moneyAmount = new Money(
                amount,
                new Currency(packagePrice.CurrencyCode));

            return(new BringShippingRate(
                       methodId,
                       estimate.GuiInformation.DisplayName,
                       estimate.GuiInformation.MainDisplayCategory,
                       estimate.GuiInformation.SubDisplayCategory,
                       estimate.GuiInformation.DescriptionText,
                       estimate.GuiInformation.HelpText,
                       estimate.GuiInformation.Tip,
                       estimate.ExpectedDelivery.ExpectedDeliveryDate,
                       moneyAmount));
        }
Example #9
0
        private byte[] CompressPframe(Bitmap bitmap)
        {
            YCbCr[,] yCbCrs = ColorChannel.ReadYCbCrs(bitmap);
            YCbCrSubSample yCbCrSubSamples = JPEG.SubSample(yCbCrs);

            // motion vecotr estimate
            var            mv          = new MotionVector(15);
            EstimateResult vecotrDiffs = mv.Estimate(frameMemory, yCbCrSubSamples);

            // dct subquantized differences
            var tasks = new Task[3];

            sbyte[,] yQuantized = null, cbQuantized = null, crQuantized = null;

            tasks[0] = Task.Factory.StartNew(() =>
            {
                yQuantized = DCTSubQuantized(vecotrDiffs.YDiffs, LuminanceQuantizationTable);
            });
            tasks[1] = Task.Factory.StartNew(() =>
            {
                cbQuantized = DCTSubQuantized(vecotrDiffs.CbDiffs, ChrominanceQuantizationTable);
            });
            tasks[2] = Task.Factory.StartNew(() =>
            {
                crQuantized = DCTSubQuantized(vecotrDiffs.CrDiffs, ChrominanceQuantizationTable);
            });
            Task.WaitAll(tasks);

            //upquantized IDCT, add to frame memory
            int yHeight = yCbCrSubSamples.Y.GetLength(0), yWidth = yCbCrSubSamples.Y.GetLength(1), cHeight = yCbCrSubSamples.Cb.GetLength(0), cWidth = yCbCrSubSamples.Cb.GetLength(1);

            tasks[0] = Task.Factory.StartNew(() =>
            {
                yCbCrSubSamples.Y = UpQuantizedIDCT(yHeight, yWidth, yQuantized, LuminanceQuantizationTable);
            });
            tasks[1] = Task.Factory.StartNew(() =>
            {
                yCbCrSubSamples.Cb = UpQuantizedIDCT(cHeight, cWidth, cbQuantized, ChrominanceQuantizationTable);
            });
            tasks[2] = Task.Factory.StartNew(() =>
            {
                yCbCrSubSamples.Cr = UpQuantizedIDCT(cHeight, cWidth, crQuantized, ChrominanceQuantizationTable);
            });

            // zigzag RLE differences
            sbyte[] yStream  = ZigZagTransform(yQuantized);
            sbyte[] cbStream = ZigZagTransform(cbQuantized);
            sbyte[] crStream = ZigZagTransform(crQuantized);

            // concatennate byte stream
            var data = new sbyte[vecotrDiffs.Vectors.Length * 2 + yStream.Length + cbStream.Length + crStream.Length];

            for (int i = 0, j = 0; i < vecotrDiffs.Vectors.Length; ++i)
            {
                data[j++] = (sbyte)(vecotrDiffs.Vectors[i].x);
                data[j++] = (sbyte)(vecotrDiffs.Vectors[i].y);
            }

            yStream.CopyTo(data, vecotrDiffs.Vectors.Length * 2);
            cbStream.CopyTo(data, yStream.Length + vecotrDiffs.Vectors.Length * 2);
            crStream.CopyTo(data, yStream.Length + cbStream.Length + vecotrDiffs.Vectors.Length * 2);

            Task.WaitAll(tasks);
            AddDifferencesToMemoryFrame(yCbCrSubSamples, vecotrDiffs.Vectors); // update frame memory
            return(RunLengthEncode(data));
        }
Example #10
0
        // estimate best match using 2d logorithmic search
        public EstimateResult Estimate(YCbCrSubSample reference, YCbCrSubSample target)
        {
            // image dimension
            int height = reference.Y.GetLength(0);
            int width  = reference.Y.GetLength(1);

            // number of 8*8 blocks to fill the y channel
            int h = (int)Math.Ceiling((double)height / N);
            int w = (int)Math.Ceiling((double)width / N);

            var result      = new EstimateResult {
            };
            int vectorIndex = 0;

            result.Vectors = new Vector[h * w];

            // y channel with paddings if origin image is not multiples of 8
            h           <<= 3;
            w           <<= 3;
            result.YDiffs = new double[h, w];

            // cb  cr
            h = (int)Math.Ceiling((double)reference.Cb.GetLength(0) / N) << 3;
            w = (int)Math.Ceiling((double)reference.Cb.GetLength(1) / N) << 3;
            result.CbDiffs = new double[h, w];
            result.CrDiffs = new double[h, w];

            // dec to prevent -1 calculation inside the loop
            --width; --height;
            // cb cr height and width
            int cHeight = height >> 1, cWidth = width >> 1;

            for (int row = 0; row <= height; row += N)
            {
                for (int col = 0; col <= width; col += N)
                {
                    // calculate the difference at the same pos first
                    var r8 = new double[N, N];
                    var t8 = new double[N, N];
                    // 8*8 block filling
                    for (int i = 0, Y = row; i < N; ++i)
                    {
                        for (int j = 0, X = col; j < N; ++j)
                        {
                            // use y channel to get vector
                            r8[i, j] = reference.Y[Y, X];
                            t8[i, j] = target.Y[Y, X];
                            if (X < width) // padding number use the boundary number
                            {
                                ++X;
                            }
                        }
                        if (Y < height)
                        {
                            ++Y;
                        }
                    }

                    Differences min = CalDifferences(r8, t8);
                    Vector      mv  = new Vector {
                        x = 0, y = 0
                    };

                    // 2d logorithmic search for new reference block (p92)
                    int  centerY = row, centerX = col;
                    int  offset = (int)Math.Ceiling(P / 2.0);
                    bool last   = false;

                    while (!last)
                    {
                        // find one of the nine specified macroblocks that yields minimum MAD, then update centerX, centerY, min Difference. vecotr.
                        for (int offY = centerY - offset; offY <= centerY + offset; offY += offset)
                        {
                            for (int offX = centerX - offset; offX <= centerX + offset; offX += offset)
                            {
                                if ((offX == centerX && offY == centerY) || offX < 0 || offY < 0 || offX > width || offY > height)
                                {
                                    continue;
                                }

                                // 8*8 block filling references block
                                for (int i = 0, Y = offY; i < N; ++i)
                                {
                                    for (int j = 0, X = offX; j < N; ++j)
                                    {
                                        r8[i, j] = reference.Y[Y, X];
                                        if (X < width) // padding number use the boundary number
                                        {
                                            ++X;
                                        }
                                    }
                                    if (Y < height)
                                    {
                                        ++Y;
                                    }
                                }
                                Differences d = CalDifferences(r8, t8);

                                // compare with min
                                if (d.AbsoluteDifference < min.AbsoluteDifference)
                                {
                                    min     = d;
                                    mv.x    = col - offX;
                                    mv.y    = row - offY;
                                    centerX = offX;
                                    centerY = offY;
                                }
                            }
                        }


                        if (offset == 1)
                        {
                            last = true;
                        }
                        offset = (int)Math.Ceiling(offset / 2.0);
                    }

                    // cb cr
                    for (int Y = row >> 1, YB = Y + (N >> 1); Y < YB && Y < cHeight; ++Y)
                    {
                        for (int X = col >> 1, XB = X + (N >> 1); X < XB && X < cWidth; ++X)
                        {
                            int ry = Math.Max(0, Math.Min(Y - mv.y, cHeight));
                            int rx = Math.Max(0, Math.Min(X - mv.x, cWidth));
                            result.CbDiffs[Y, X] = target.Cb[Y, X] - reference.Cb[ry, rx];
                            result.CrDiffs[Y, X] = target.Cr[Y, X] - reference.Cr[ry, rx];
                        }
                    }

                    // y
                    for (int _y = 0, Y = row; _y < N; ++_y, ++Y)
                    {
                        for (int _x = 0, X = col; _x < N; ++_x, ++X)
                        {
                            result.YDiffs[Y, X] = min.DifferenceBlock[_y, _x];
                        }
                    }
                    result.Vectors[vectorIndex++] = mv;
                }
            }

            return(result);
        }
        public PositionEstimate GetPosition(string clientMac)
        {
            /**
             * [WebGet] = SnifferReceiver operation (cf: http://msdn.microsoft.com/en-us/library/cc668788.aspx )
             * usage example: http://localhost:38244/SnifferService.svc/GetPosition?mac='Big Mac'
             */

            if (clientMac == null)
            {
                return(null);
            }

            SnifferWifiMeasurement curMeas;

            if (!(currentOnlineMeasurements.TryGetValue(clientMac, out curMeas)))
            {
                return(null); //we do not have a measurement yet to base an estimate on
            }

            //Check whether the client is associated with a building
            //If not, positioning has (JUST) been requested, but the correct building not established yet.
            WifiPosEngine posEngine;

            if (!(currentWifiPosEngines.TryGetValue(clientMac, out posEngine)))
            {
                return(null); //we do not have a wifi pos engine. Reason: User has probably not called StartWifiPositioning.
            }

            if (posEngine.getCurrentBuilding() == null) //It is the very first estimate
            {
                posEngine.setCurrentBuilding(getCorrectBuilding(curMeas));
            }

            EstimateResult currentEstimate = posEngine.getEstimate(curMeas);

            //We have a result
            if (currentEstimate != null && currentEstimate.getVertex() != null)
            {
                //convert estimated location to PositionEstimate
                PositionEstimate result = new PositionEstimate();
                Vertex           v      = currentEstimate.getVertex();
                AbsoluteLocation a      = v.AbsoluteLocations.First();

                result.VertexID    = v.ID;
                result.Building_ID = v.Building_ID;
                result.Latitude    = (double)a.latitude;
                result.Longitude   = (double)a.longitude;
                result.Altitude    = (double)a.longitude;
                result.Accuracy    = currentEstimate.getErrorEstimate();
                result.HasAccuracy = true;
                result.HasBearing  = false;
                result.HasSpeed    = false;
                result.Provider    = WIFI_PROVIDER;
                result.Time        = DateTime.Now;

                return(result);
            }
            else //We do not have a result
            {
                return(null);
            }
        }