예제 #1
0
        public void SetExistingKeyTest()
        {
            var list = new List <KeyValuePair <string, string> >(2)
            {
                new KeyValuePair <string, string>(K1, V1),
            };

            Baggage.Current.SetBaggage(new KeyValuePair <string, string>(K1, V1));
            var baggage = Baggage.SetBaggage(K1, V1);

            Baggage.SetBaggage(new Dictionary <string, string> {
                [K1] = V1
            }, baggage);

            Assert.Equal(list, Baggage.GetBaggage());
        }
        public string GetBaggageItem(string key)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

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

            string value;

            Baggage.TryGetValue(key, out value);
            return(value);
        }
예제 #3
0
        public void ContextFlowTest()
        {
            var baggage  = Baggage.SetBaggage(K1, V1);
            var baggage2 = Baggage.Current.SetBaggage(K2, V2);
            var baggage3 = Baggage.SetBaggage(K3, V3);

            Assert.Equal(1, baggage.Count);
            Assert.Equal(2, baggage2.Count);
            Assert.Equal(3, baggage3.Count);

            Baggage.Current = baggage;

            var baggage4 = Baggage.SetBaggage(K3, V3);

            Assert.Equal(2, baggage4.Count);
            Assert.DoesNotContain(new KeyValuePair <string, string>(K2, V2), baggage4.GetBaggage());
        }
예제 #4
0
        public async Task <Result <AgentAccommodation, ProblemDetails> > GetAccommodation(Guid searchId, string htId, AgentContext agent, string languageCode)
        {
            Baggage.AddSearchId(searchId);

            var accommodation = await _mapperClient.GetAccommodation(htId, languageCode);

            if (accommodation.IsFailure)
            {
                return(accommodation.Error);
            }

            _bookingAnalyticsService.LogAccommodationAvailabilityRequested(accommodation.Value, searchId, htId, agent);

            var searchSettings = await _accommodationBookingSettingsService.Get(agent);

            return(accommodation.Value.ToEdoContract().ToAgentAccommodation(searchSettings.IsSupplierVisible));
        }
예제 #5
0
        public void ConveyorPassBaggage()
        {
            DropOff  drop = new DropOff(5, "Drop1");
            Conveyor conv = new Conveyor(drop, "Conv1");

            conv.IsBroken = false;
            Conveyor conv1 = new Conveyor(drop, "Conv2");

            conv1.IsBroken = false;
            Passenger passenger = new Passenger("111", drop);
            Baggage   baggage   = new Baggage(drop, 50, passenger);

            conv.next = conv1;
            conv.PassBaggage(baggage);

            Assert.AreEqual(conv1.baggage.Count, 0);
        }
예제 #6
0
 public void Next()
 {
     if (!station.IsFull)
     {
         if (baggageCount.Count != 0)
         {
             var bags = baggageCount.Where((p, i) => currCount.ElementAt(i).Value <= p.Value);
             if (bags.Count() > 0)
             {
                 KeyValuePair <string, int> pair = bags.ElementAt(rand.Next(bags.Count()));
                 Baggage b = new Baggage(pair.Key, currCount[pair.Key], currColor[pair.Key]);
                 station.AddBag(b);
                 currCount[pair.Key] += 1;
             }
         }
     }
 }
예제 #7
0
    static void Main(string[] args)
    {
        var l = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray();
        var n = l[0]; var m = l[1]; var q = l[2];
        var baggages = new List <Baggage>();

        for (var i = 0; n > i; i++)
        {
            var wv      = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray();
            var baggage = new Baggage(wv[0], wv[1]);
            baggages.Add(baggage);
        }
        var defaultBoxes = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray();
        var queries      = new List <Tuple <int, int> >();

        for (var i = 0; q > i; i++)
        {
            var lr    = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray();
            var query = new Tuple <int, int>(lr[0], lr[1]);
            queries.Add(query);
        }
        foreach (var query in queries)
        {
            var boxes = new List <int>(defaultBoxes);
            for (var i = query.Item1 - 1; query.Item2 > i; i++)
            {
                boxes.RemoveAt(query.Item1 - 1);
            }
            baggages = baggages.OrderByDescending(x => x.Price).ToList();
            boxes    = boxes.OrderBy(x => x).ToList();
            var count = 0;
            for (var ba = 0; baggages.Count > ba; ba++)
            {
                for (var bo = 0; boxes.Count > bo; bo++)
                {
                    if (baggages[ba].Size <= boxes[bo])
                    {
                        count += baggages[ba].Price;
                        boxes.RemoveAt(bo);
                        break;
                    }
                }
            }
            Console.WriteLine(count);
        }
    }
        /// <inheritdoc />
        public SpanContext Extract <TCarrier>(IFormat <TCarrier> format, TCarrier carrier)
        {
            if (carrier is IBinary s)
            {
                var ctx     = BinaryCarrier.Parser.ParseFrom(s.Get());
                var traceId = ctx.BasicCtx.TraceId;
                var spanId  = ctx.BasicCtx.SpanId;
                var baggage = new Baggage();
                foreach (var item in ctx.BasicCtx.BaggageItems)
                {
                    baggage.Set(item.Key, item.Value);
                }
                return(new SpanContext(traceId.ToString(), spanId.ToString(), baggage));
            }

            return(null);
        }
예제 #9
0
        private void View_OnBaggageAddItem(object sender, BaggageManagementEventArgs e)
        {
            if (e == null)
            {
                throw new ArgumentNullException(nameof(BaggageManagementEventArgs));
            }

            var bag = new Baggage()
            {
                Type         = e.Type,
                MaxKilograms = e.MaxKilograms,
                Size         = e.Size,
                Price        = e.Price,
                BookingId    = e.BookingId
            };

            e.Id = this.baggageServices.AddBaggage(bag);
        }
        public void ChainLinkNode_ShouldAddProcessingLog()
        {
            var timerMock = new Mock <ITimerService>();

            timerMock.Setup(time => time.SimulationMultiplier).Returns(1);
            var conveyorMock = new Mock <OneToOneConveyor>(10, Guid.NewGuid().ToString(), timerMock.Object);

            conveyorMock.SetupGet(conv => conv.Destination).Returns("Psc");
            var bag = new Baggage();

            var node = new CheckInDesk(Guid.NewGuid().ToString(), timerMock.Object);

            node.AddSuccessor(conveyorMock.Object);

            node.PassBaggage(bag);

            bag.Log.Count.ShouldBe(1);
        }
        public void ChainLinkNode_ShouldNotAddTransportingLog_WhenTransportationTImeIsNull()
        {
            var timerMock = new Mock <ITimerService>();

            timerMock.Setup(time => time.SimulationMultiplier).Returns(1);
            var conveyorMock = new Mock <OneToOneConveyor>(10, Guid.NewGuid().ToString(), timerMock.Object);

            conveyorMock.SetupGet(conv => conv.Destination).Returns("Psc");
            var bag = new Baggage();
            //bag.TransportationStartTime = null;

            var node = new CheckInDesk(Guid.NewGuid().ToString(), timerMock.Object);

            node.AddSuccessor(conveyorMock.Object);

            node.PassBaggage(bag);

            bag.Log.Count(l => l.Description.Contains(LoggingConstants.BagTransporterIdText)).ShouldBe(0);
        }
        public void ChainLinkNode_ShouldMove_WhenNextIsFree_AndHasBaggage()
        {
            var timerMock = new Mock <ITimerService>();

            timerMock.Setup(time => time.SimulationMultiplier).Returns(1);
            var conveyorMock = new Mock <OneToOneConveyor>(10, Guid.NewGuid().ToString(), timerMock.Object);

            conveyorMock.SetupGet(conv => conv.Destination).Returns("Psc");
            conveyorMock.SetupGet(conv => conv.Status).Returns(NodeState.Free);
            var bag = new Baggage();

            var node = new CheckInDesk(Guid.NewGuid().ToString(), timerMock.Object);

            node.AddSuccessor(conveyorMock.Object);

            node.PassBaggage(bag);

            conveyorMock.Verify(conv => conv.PassBaggage(bag), Times.Once);
        }
예제 #13
0
        public override string Turn()
        {
            string res     = "";
            int    health  = Health;
            double battery = BatteryCharge;

            foreach (var item in Baggage)
            {
                if (item.Damage > 0)
                {
                    Health -= item.Damage;
                }
                if (item.Collapses)
                {
                    if (item.StoneHealth > 1)
                    {
                        item.DecreaseHealth();
                    }
                    else
                    {
                        res += DropCollapsedStone(item);
                    }
                }
                BatteryCharge -= item.Weight * 0.1;
            }

            foreach (var item in StonesToDrop)
            {
                CurrentWeight -= item.Weight;
                Baggage.Remove(item);
            }

            BatteryCharge--;
            if (CurrentWeight > MaxWeight * 0.8)
            {
                Random rnd = new Random();
                if (rnd.Next(11) < 3)
                {
                    BatteryCharge = 0;
                }
            }
            return("Turns harm: " + (health - Health) + ", battery charge: " + (BatteryCharge >= 0 ? BatteryCharge : 0) + ", battery lost: " + (battery - BatteryCharge) + ", " + res);
        }
예제 #14
0
        static void Main(string[] args)
        {
            DropOff         drop       = new DropOff(5, "drop1");
            CheckIn         check      = new CheckIn(drop, "check1", 4);
            CheckIn         check2     = new CheckIn(drop, "check2", 5);
            Conveyor        conveyorl  = new Conveyor(drop, "convl");
            Conveyor        conveyorl1 = new Conveyor(drop, "convl1");
            Conveyor        conveyorb2 = new Conveyor(drop, "convb");
            Conveyor        conveyorb3 = new Conveyor(drop, "convb1");
            MainProcessArea mpa        = new MainProcessArea("mpa1");

            LinkedList l = new LinkedList();
            LinkedList b = new LinkedList();

            l.AddLast(check);
            l.AddLast(conveyorl);
            //l.AddLast(mpa);
            l.AddLast(conveyorl1);
            l.AddLast(drop);

            b.AddLast(check2);
            b.AddLast(conveyorb2);
            //b.AddLast(mpa);
            b.AddLast(conveyorb3);
            b.AddLast(drop);

            Airport airport = new Airport();



            Baggage x  = new Baggage(drop, 5, new Passenger("bag1", drop));
            Baggage xy = new Baggage(drop, 6, new Passenger("bag2", drop));

            l.PassBaggage(x);
            b.PassBaggage(xy);
            //Console.WriteLine(l.first.Name);
            //Console.WriteLine(l.first.Name);

            //l.printAllNodes();

            Console.ReadKey();
        }
예제 #15
0
        public ISpan Start(ISpanBuilder spanBuilder)
        {
            if (spanBuilder == null)
            {
                throw new ArgumentNullException(nameof(spanBuilder));
            }

            var traceId = spanBuilder.References?.FirstOrDefault()?.SpanContext?.TraceId ?? Guid.NewGuid().ToString();
            var spanId  = Guid.NewGuid().ToString();

            Baggage baggage = new Baggage();

            foreach (var reference in spanBuilder.References)
            {
                baggage.Merge(reference.SpanContext.Baggage);
            }
            var spanContext = _spanContextFactory.Create(new SpanContextPackage(traceId, spanId, _sampler.ShouldSample(), baggage));

            return(new Span(spanBuilder.OperationName, spanContext, _spanQueue));
        }
예제 #16
0
        public async Task <HttpResponseMessage> PostData()
        {
            string value1 = Baggage.GetBaggage("key1");

            if (string.IsNullOrEmpty(value1))
            {
                throw new InvalidOperationException("Key1 was not found on Baggage.");
            }

            var stream = await this.Request.Content.ReadAsStreamAsync().ConfigureAwait(false);

            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(stream),
            };

            result.Content.Headers.ContentType = this.Request.Content.Headers.ContentType;

            return(result);
        }
        private static double GetBsuStayTimeInSeconds(Baggage bag)
        {
            if (bag == null)
            {
                return(0);
            }

            var receivedInBsuText         = string.Format(LoggingConstants.BagReceivedInTemplate, typeof(BSU).Name, bag.TransporterId);
            var receivedInRobotFromBucket = string.Format(LoggingConstants.ReceivedInRobotSendingTo, typeof(Mpa).Name, bag.TransporterId);

            var startTime = bag.Log.FirstOrDefault(log => log.Description.Contains(receivedInBsuText))?.LogCreated ?? TimeSpan.Zero;
            var endTime   = bag.Log.FirstOrDefault(log => log.Description.Contains(receivedInRobotFromBucket))?.LogCreated ?? TimeSpan.Zero;

            if (endTime == TimeSpan.Zero)
            {
                return(startTime.TotalSeconds);
            }

            return(endTime.TotalSeconds - startTime.TotalSeconds);
        }
예제 #18
0
    public override void OnEnd(Activity activity)
    {
        // Enrich activity with additional tags.
        activity.SetTag("myCustomTag", "myCustomTagValue");

        // Enriching from Baggage.
        // The below snippet adds every Baggage item.
        foreach (var baggage in Baggage.GetBaggage())
        {
            activity.SetTag(baggage.Key, baggage.Value);
        }

        // The below snippet adds specific Baggage item.
        var deviceTypeFromBaggage = Baggage.GetBaggage("device.type");

        if (deviceTypeFromBaggage != null)
        {
            activity.SetTag("device.type", deviceTypeFromBaggage);
        }
    }
        public void ProcessBaggage_If_Else_Statement()
        {
            Baggage baggage = new Baggage()
            {
                Secure = 6
            };

            Security security = new Security();
            CheckIn  checkIn  = new CheckIn();
            Conveyor conveyor = new Conveyor(5, 6);
            DropOff  dropOff  = new DropOff();

            checkIn.NextNode  = conveyor;
            conveyor.NextNode = security;
            security.NextNode = dropOff;

            security.PassBaggage(baggage);

            Assert.AreEqual(BaggageStatus.Free, security.Status);
        }
        public override int GetHashCode()
        {
            int hashcode = 157;

            unchecked {
                if ((ServerRole != null))
                {
                    hashcode = (hashcode * 397) + ServerRole.GetHashCode();
                }
                hashcode = (hashcode * 397) + Sampled.GetHashCode();
                if ((Baggage != null))
                {
                    hashcode = (hashcode * 397) + Baggage.GetHashCode();
                }
                if ((Downstream != null))
                {
                    hashcode = (hashcode * 397) + Downstream.GetHashCode();
                }
            }
            return(hashcode);
        }
        private int FindMostSuitableCheckin(Baggage baggage)
        {
            var chosenIndex   = 0;
            var shortestQueue = checkinQueues[0].Count;

            foreach (var index in Enumerable.Range(0, checkins.Count))
            {
                if (checkins[index].NodeStatus == NodeStatus.Free)
                {
                    return(index);
                }

                if (checkinQueues[index].Count < shortestQueue)
                {
                    shortestQueue = checkinQueues[index].Count;
                    chosenIndex   = index;
                }
            }

            return(chosenIndex);
        }
예제 #22
0
        public void RemoveTest()
        {
            var empty  = Baggage.Current;
            var empty2 = Baggage.RemoveBaggage(K1);

            Assert.True(empty == empty2);

            var baggage = Baggage.SetBaggage(new Dictionary <string, string>
            {
                [K1] = V1,
                [K2] = V2,
                [K3] = V3,
            });

            var baggage2 = Baggage.RemoveBaggage(K1, baggage);

            Assert.Equal(3, baggage.Count);
            Assert.Equal(2, baggage2.Count);

            Assert.DoesNotContain(new KeyValuePair <string, string>(K1, V1), baggage2.GetBaggage());
        }
예제 #23
0
        private void btPutBaggage_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbFlight.Text))
            {
                MessageBox.Show("航班号不能为空!");
                return;
            }
            if (string.IsNullOrEmpty(tbBaggage.Text))
            {
                MessageBox.Show("行李号不能为空!");
                return;
            }
            if (!algo.FlightTime.Keys.Contains(tbFlight.Text))
            {
                MessageBox.Show("航班号不存在,请先配置航班号!");
                return;
            }
            Baggage b = new Baggage(tbFlight.Text, int.Parse(tbBaggage.Text));

            station.AddBag(b);
        }
예제 #24
0
        public async Task TestInvalidBaggage()
        {
            validateBaggage = true;
            Baggage
            .SetBaggage("key", "value")
            .SetBaggage("bad/key", "value")
            .SetBaggage("goodkey", "bad/value");

            using var eventRecords = new ActivitySourceRecorder();

            using (var client = new HttpClient())
            {
                (await client.GetAsync(this.BuildRequestUrl())).Dispose();
            }

            Assert.Equal(2, eventRecords.Records.Count());
            Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Start"));
            Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop"));

            validateBaggage = false;
        }
예제 #25
0
        public async Task TestTraceStateAndBaggage()
        {
            try
            {
                using var eventRecords = new ActivitySourceRecorder();

                var parent = new Activity("w3c activity");
                parent.SetParentId(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom());
                parent.TraceStateString = "some=state";
                parent.Start();

                Baggage.SetBaggage("k", "v");

                // Send a random Http request to generate some events
                using (var client = new HttpClient())
                {
                    (await client.GetAsync(this.BuildRequestUrl())).Dispose();
                }

                parent.Stop();

                Assert.Equal(2, eventRecords.Records.Count());

                // Check to make sure: The first record must be a request, the next record must be a response.
                (Activity activity, HttpWebRequest startRequest) = AssertFirstEventWasStart(eventRecords);

                var traceparent = startRequest.Headers["traceparent"];
                var tracestate  = startRequest.Headers["tracestate"];
                var baggage     = startRequest.Headers["baggage"];
                Assert.NotNull(traceparent);
                Assert.Equal("some=state", tracestate);
                Assert.Equal("k=v", baggage);
                Assert.StartsWith($"00-{parent.TraceId.ToHexString()}-", traceparent);
                Assert.Matches("^[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$", traceparent);
            }
            finally
            {
                this.CleanUpActivity();
            }
        }
예제 #26
0
        public void SetAndGetTest()
        {
            var list = new List <KeyValuePair <string, string> >(2)
            {
                new KeyValuePair <string, string>(K1, V1),
                new KeyValuePair <string, string>(K2, V2),
            };

            Baggage.SetBaggage(K1, V1);
            Baggage.Current.SetBaggage(K2, V2);

            Assert.NotEmpty(Baggage.GetBaggage());
            Assert.Equal(list, Baggage.GetBaggage(Baggage.Current));

            Assert.Equal(V1, Baggage.GetBaggage(K1));
            Assert.Equal(V1, Baggage.GetBaggage(K1.ToLower()));
            Assert.Equal(V1, Baggage.GetBaggage(K1.ToUpper()));
            Assert.Null(Baggage.GetBaggage("NO_KEY"));
            Assert.Equal(V2, Baggage.Current.GetBaggage(K2));

            Assert.Throws <ArgumentNullException>(() => Baggage.GetBaggage(null));
        }
예제 #27
0
        public override string AddStone(params Stone[] stone)
        {
            Stone st = stone[0];

            if (st.Weight + CurrentWeight <= MaxWeight)
            {
                if (st.Damage < Health)
                {
                    if (st.Decryption)
                    {
                        Random random = new Random();
                        if (random.Next(5) < 3)
                        {
                            Baggage.Add(st);
                            CurrentWeight += st.Weight;
                            return(st.GetInfo() + "\r\n Succesfully decrypted and added");
                        }
                        else
                        {
                            return("Decryption failed");
                        }
                    }
                    else
                    {
                        Baggage.Add(st);
                        CurrentWeight += st.Weight;
                        return(st.GetInfo() + "\r\n Succesfully added");
                    }
                }
                else
                {
                    return("You are dead (9((9");
                }
            }
            else
            {
                return("You can`t lift this stone. Robot overload");
            }
        }
예제 #28
0
        public async Task <Result <string> > Register(AccommodationBookingRequest bookingRequest, AgentContext agentContext, string languageCode)
        {
            Baggage.AddSearchId(bookingRequest.SearchId);
            _logger.LogCreditCardBookingFlowStarted(bookingRequest.HtId);

            var(_, isFailure, booking, error) = await GetCachedAvailability(bookingRequest)
                                                .Ensure(IsPaymentTypeAllowed, "Payment type is not allowed")
                                                .Bind(Register)
                                                .Check(SendEmailToPropertyOwner)
                                                .Finally(WriteLog);

            if (isFailure)
            {
                return(Result.Failure <string>(error));
            }

            return(booking.ReferenceCode);

            async Task <Result <BookingAvailabilityInfo> > GetCachedAvailability(AccommodationBookingRequest bookingRequest)
            => await _evaluationStorage.Get(bookingRequest.SearchId, bookingRequest.HtId, bookingRequest.RoomContractSetId);


            bool IsPaymentTypeAllowed(BookingAvailabilityInfo availabilityInfo)
            => availabilityInfo.AvailablePaymentTypes.Contains(PaymentTypes.CreditCard);


            Task <Result <Booking> > Register(BookingAvailabilityInfo bookingAvailability)
            => _registrationService.Register(bookingRequest, bookingAvailability, PaymentTypes.CreditCard, agentContext, languageCode);


            async Task <Result> SendEmailToPropertyOwner(Booking booking)
            => await _bookingConfirmationService.SendConfirmationEmail(booking);


            Result <Booking> WriteLog(Result <Booking> result)
            => LoggerUtils.WriteLogByResult(result,
                                            () => _logger.LogBookingRegistrationSuccess(result.Value.ReferenceCode),
                                            () => _logger.LogBookingRegistrationFailure(bookingRequest.HtId, bookingRequest.ItineraryNumber, bookingRequest.MainPassengerName, result.Error));
        }
예제 #29
0
        public override string AddStone(params Stone[] stone)
        {
            Stone st = stone[0];

            if (st.Weight + CurrentWeight <= MaxWeight)
            {
                if (st.Decryption)
                {
                    Baggage.Add(st);
                    return(st.GetInfo() + "\r\n Succesfully decrypted and added");
                }
                else
                {
                    Baggage.Add(st);
                    return(st.GetInfo() + "\r\n Succesfully added");
                }
            }
            else
            {
                return("You can`t lift this stone. Robot overload");
            }
        }
예제 #30
0
        public BaggageWindow(Baggage baggage = null)
        {
            InitializeComponent();

            PreviewBaggage = new Baggage();

            PreviewBaggage.PropertyChanged += (sender, e) => btnOkay.IsEnabled = HasValidInput;

            if (baggage != null)
            {
                Baggage = baggage;

                PreviewBaggage.Weight              = baggage.Weight;
                PreviewBaggage.WeightLimit         = baggage.WeightLimit;
                PreviewBaggage.FeePerExtraKilogram = baggage.FeePerExtraKilogram;

                Title = "Gepäckstück bearbeiten";
            }
            else
            {
                Baggage = PreviewBaggage;

                Title = "Gepäckstück hinzufügen";
            }

            DataContext = PreviewBaggage;

            _baggageFeeMapper = new ObjectRelationalMapper <BaggageFeeInfo>(Config.DB_CONNECTION_STRING);

            DatabaseTable baggageFeeTable = new DatabaseTable("baggagefees");

            baggageFeeTable.AddAttribute("Limit");
            baggageFeeTable.AddAttribute("FeePerKilogram");

            _baggageFeeMapper.SourceTable = baggageFeeTable;

            //btnOkay.IsEnabled = HasValidInput;
        }
예제 #31
0
 public void GiveBaggage(int numberCarriage, Baggage baggage)
 {
     try
     {
         var baggageCarriage = this[numberCarriage] as BaggageCarriage;
         if (baggageCarriage != null)
             baggageCarriage.Add(baggage);
     }
     catch (Exception exception)
     {
         Console.WriteLine(exception.Message);
     }
 }