static void Main(string[] args) { var x = 5 * US.Feet; var y = 15.5 * SI.Centimeter; var length = (x + y).RoundUp(5 * US.Inch); var load = 250 * US.Lbf; var area = x * y; var side = area.Sqrt(); var P = load; var L = length; var E = 29e6 * US.Psi; var b = 0.5 * US.Inch; var h = 2.0 * US.Inch; var I = b * h * h * h / 12.0; var I2 = b * h.Pow(3) / 12.0; var ts = (Quantity) TimeSpan.FromMinutes(5.0); var ts2 = new Quantity(TimeSpan.FromMinutes(5.0)); var r = Quantity.ReturnChecked(P * L.Pow(3) / (3 * E * I), Quantity.Length); Console.WriteLine("x: {0}, y: {1}, length: {2}, area: {3}, side: {4}", x, y, length, area, side); var pOverL = Quantity.op_DivideDot(h, b); var another_pOverL = h.ConvertTo(b); Console.WriteLine("length (in): {0}, length (mm): {1}", length.ConvertTo(US.Inch), length.ConvertTo(SI.Millimeter)); Quantity.CheckDimensionalConstraints( FSharpList<Tuple<Quantity, Quantity>>.Cons(Tuple.Create(length, Fundamental.Length), FSharpList<Tuple<Quantity, Quantity>>.Cons(Tuple.Create(area, Derived.Area), FSharpList<Tuple<Quantity, Quantity>>.Cons(Tuple.Create(load, Derived.Force), FSharpList<Tuple<Quantity, Quantity> >.Empty)))); Quantity.CheckDimensionalConstraints( SeqModule.ToList(new [] { Tuple.Create(length, Fundamental.Length), Tuple.Create(area, Derived.Area), Tuple.Create(load, Derived.Force) })); Quantity.CheckDimensionalConstraints( new List<Tuple<Quantity, Quantity>> { Tuple.Create(length, Fundamental.Length), Tuple.Create(area, Derived.Area), Tuple.Create(load, Derived.Force) }); Quantity.CheckDimensionalConstraints(new[] { length, Fundamental.Length, area, Derived.Area, load, Derived.Force }); Console.ReadKey(); }
public void ThenComparisonOperatorsWorkAsExpected() { var amount1 = new Quantity(1, kg); var amount2 = new Quantity(2, kg); Assert.IsTrue(amount1 < amount2); Assert.IsFalse(amount1 > amount2); Assert.IsTrue(amount1 <= amount2); Assert.IsFalse(amount1 >= amount2); amount1 = new Quantity(1, kg); amount2 = new Quantity(1, kg); Assert.IsFalse(amount1 < amount2); Assert.IsFalse(amount1 > amount2); Assert.IsTrue(amount1 <= amount2); Assert.IsTrue(amount1 >= amount2); amount2 = null; Assert.IsFalse(amount1 < amount2); Assert.IsTrue(amount1 > amount2); Assert.IsFalse(amount1 <= amount2); Assert.IsTrue(amount1 >= amount2); amount1 = null; Assert.IsFalse(amount1 < amount2); Assert.IsFalse(amount1 > amount2); Assert.IsTrue(amount1 <= amount2); Assert.IsTrue(amount1 >= amount2); }
public void Verify_that_ridiculous_dimension_times_absurd_dimension_is_correct_in_inches( double aValue, double bValue, int expectedValue) { var a = new Quantity(aValue, SiV.MetersPerMinute.Squared(), SiA.SquareMeter.Squared(), SiL.Kilometer.Invert()); var b = new Quantity(bValue, SiV.MetersPerSecond, SiA.SquareMeter.Invert(), UsL.Foot.Invert()); var s = T.Second; var inch = UsL.Inch; var initial = a*b; var result = initial.ConvertTo(inch); Assert.That((int) result.Value, Is.EqualTo(expectedValue)); Assert.That(result.Dimensions .AreCompatible(new[] {inch.Cubed(), s.Invert().Cubed()}, true)); }
public void ThenKilogramBehavesCorrectly() { var mass100 = new Quantity(100, kg); var mass25 = new Quantity(25, kg); Assert.AreEqual(mass100/4, mass25); }
public void Verify_that_ridiculous_dimension_times_absurd_dimension_is_correct_in_feet( double aValue, double bValue, int expectedValue) { var a = new Quantity(aValue, SiV.MetersPerMinute.Squared(), SiA.SquareMeter.Squared(), SiL.Kilometer.Invert()); var b = new Quantity(bValue, SiV.MetersPerSecond, SiA.SquareMeter.Invert(), UsL.Foot.Invert()); var s = T.Second; var ft = UsL.Foot; var initial = a*b; // Same as previous test but by several (four) orders of inch-to-foot magnitudes. var result = initial.ConvertTo(ft); Assert.That((int) result.Value, Is.EqualTo(expectedValue)); Assert.That(result.Dimensions .AreCompatible(new[] {ft.Cubed(), s.Invert().Cubed()}, true)); }
public void DefaultPropertiesShouldBeSet() { IMeasurementService measurementService = new MeasurementServiceTest(); var quantity1 = new Quantity(measurementService); Assert.IsTrue(quantity1.IsIntegral()); Assert.IsTrue(quantity1.IsStrictlyComparableTo(new Quantity(measurementService))); }
public PurchaseItem(Purchase purchase, Guid productId, Money price, Quantity quantity) { Purchase = purchase; ProductId = productId; Price = price; Quantity = quantity; }
public ProductAddedToCart(Guid customerId, Guid productId, Quantity quantity, Money price) { CustomerId = customerId; ProductId = productId; Quantity = quantity; Price = price; }
public void ThenCanCompareEquivalentQuantities() { var hour1 = new Quantity(1, this.h); var hour2 = new Quantity(3600, this.s); Assert.AreEqual(hour1, hour2); }
public void ConvertTest() { Quantity kg_1 = new Quantity(1, SIUnit.MassUnits.kg); Quantity g_1000 = UnitManager.Convert(kg_1, SIUnit.MassUnits.g); Assert.AreEqual(new Quantity(1000, SIUnit.MassUnits.g), g_1000); }
public void ThenCanCheckEqualityForEquivalentQuantities() { var hour1 = new Quantity(1, this.h); var hour2 = new Quantity(3600, this.s); Assert.IsTrue(hour1 == hour2); Assert.AreEqual(hour1, hour2); }
public CheckReceivedCallsHandler(IReceivedCalls receivedCalls, ICallSpecificationFactory callSpecificationFactory, IReceivedCallsExceptionThrower exceptionThrower, MatchArgs matchArgs, Quantity requiredQuantity) { _receivedCalls = receivedCalls; _callSpecificationFactory = callSpecificationFactory; _exceptionThrower = exceptionThrower; _matchArgs = matchArgs; _requiredQuantity = requiredQuantity; }
public void ThenConvertedQuantitiesAreEquivalent() { var kWh = this.System.AddDerivedUnit("kWh", "kilowatt hour", UnitPrefix.k*this.W*this.h); var quantity = new Quantity(100, this.J); var result = quantity.Convert(kWh); Assert.AreEqual(quantity, result); }
public IRoute CheckReceivedCalls(ISubstituteState state, MatchArgs matchArgs, Quantity requiredQuantity) { return new Route(new ICallHandler[] { new ClearLastCallRouterHandler(state.SubstitutionContext) , new ClearUnusedCallSpecHandler(state) , new CheckReceivedCallsHandler(state.ReceivedCalls, state.CallSpecificationFactory, new ReceivedCallsExceptionThrower(), matchArgs, requiredQuantity) , ReturnDefaultForReturnTypeHandler() }); }
public void ThenCanMapToInfoAndBack() { var quantity = new Quantity(100, this.J/(this.m ^ 3)); var info = quantity.ToInfo(); var result = this.System.FromInfo(info); Assert.AreEqual(quantity, result); }
/// <summary> /// Ergänzt ein Tdm/Quantity Wertepaar /// </summary> /// <param name="totalQuantity"></param> /// <param name="vpPrice"></param> /// <param name="tdm"></param> public void AddTdm(Quantity totalQuantity, Money vpPrice, decimal? tdm) { if (totalQuantity != null && totalQuantity.Value > 0m && vpPrice != null && vpPrice.Amount > 0m && tdm.HasValue) { _qtyVpTdmSum += totalQuantity.ValueRounded*vpPrice.AmountRounded*tdm.Value; _qtyVpSum += totalQuantity.ValueRounded*vpPrice.AmountRounded; } }
public bool IsMinimumValid(Quantity qty) { bool isQtyValid = false; if (qty != null) isQtyValid = IsMinimumValid(qty.Value); return isQtyValid; }
public void CustomUnitToUnit_Then_ResultShouldBeExpected() { var steps = new Quantity(43, this.StepsUnit); const double Expected = 0.00080475637518549213354573461734671; var result = steps.ToUnit(UnitDefinitions.Meter); result.Should().BeApproximately(Expected, "m", TestHelper.DefaultAssertPrecision); }
public void ThenDividingQuantityOfSameUnitYieldsARatio() { var a = new Quantity(10, m); var b = new Quantity(2, m); var expected = new Quantity(5, System.NoUnit); var actual = a/b; Assert.AreEqual(expected, actual); }
public void ThenCanExponentizeQuantities() { var length = new Quantity(4, m); var square = m*m; var expected = new Quantity(16, square); var actual = length ^ 2; Assert.AreEqual(expected, actual); }
public void AddProduct(Product product, Quantity quantity) { if (product == null) throw new InvalidProductInstanceException(); if (quantity == null) throw new InvalidQuantityInstanceException(); Apply(new ProductAddedToCart(CustomerId, product.Id, quantity, product.Price)); }
public IRoute CheckReceivedCalls(ISubstituteState state, MatchArgs matchArgs, Quantity requiredQuantity) { return new Route(new ICallHandler[] { new ClearLastCallRouterHandler(state.SubstitutionContext) , new ClearUnusedCallSpecHandler(state.PendingSpecification) , new CheckReceivedCallsHandler(state.ReceivedCalls, state.CallSpecificationFactory, new ReceivedCallsExceptionThrower(), matchArgs, requiredQuantity) , new ReturnAutoValue(AutoValueBehaviour.ReturnAndForgetValue, state.AutoValueProviders, state.AutoValuesCallResults, state.CallSpecificationFactory) , ReturnDefaultForReturnTypeHandler() }); }
public void CompareShouldbeCorrect() { IMeasurementService measurementService = new MeasurementServiceTest(); var quantity1 = new Quantity(measurementService) { Magnitude = 0.1 }; var quantity2 = new Quantity(measurementService) { Magnitude = 0.2 }; var quantity3 = new Quantity(measurementService) { Magnitude = 0.2 }; Assert.AreEqual(0, quantity2.CompareTo(quantity3)); Assert.AreEqual(-1, quantity1.CompareTo(quantity2)); Assert.AreEqual(1, quantity2.CompareTo(quantity1)); }
public void ThenCanSubstractQuantities() { var kWh = UnitPrefix.k * W * h; var energy1 = new Quantity(100, kWh); var energy2 = new Quantity(20, kWh).Convert(this.J); var expected = new Quantity(80, kWh); var actual = energy1 - energy2; Assert.AreEqual(expected, actual); }
public void ThenCanCompareEquivalentQuantities() { var kWh = this.System.AddDerivedUnit("kWh", "kilowatt hour", UnitPrefix.k * this.W * this.h); var energy1 = new Quantity(100, this.J).Convert(kWh); var energy2 = new Quantity(101, this.J); Assert.IsTrue(energy1 < energy2); Assert.IsTrue(energy1 <= energy2); Assert.IsFalse(energy1 > energy2); Assert.IsFalse(energy1 >= energy2); Assert.IsFalse(energy1 == energy2); }
public void Throw(ICallSpecification callSpecification, IEnumerable<ICall> matchingCalls, IEnumerable<ICall> nonMatchingCalls, Quantity requiredQuantity) { var builder = new StringBuilder(); builder.AppendLine(string.Format("Expected to receive {0} matching:\n\t{1}", requiredQuantity.Describe("call", "calls"), callSpecification)); AppendMatchingCalls(callSpecification, matchingCalls, builder); if (requiredQuantity.RequiresMoreThan(matchingCalls)) { AppendNonMatchingCalls(callSpecification, nonMatchingCalls, builder); } throw new ReceivedCallsException(builder.ToString()); }
public virtual void UpdateAssessmentDetails( Quantity? quantity, MatterState? matterState, DustinessOrVolatility? dustinessOrVolatility, bool healthSurveillanceRequired, UserForAuditing currentUser) { Quantity = quantity; MatterState = matterState; DustinessOrVolatility = dustinessOrVolatility; HealthSurveillanceRequired = healthSurveillanceRequired; SetLastModifiedDetails(currentUser); }
public void ThenKilogramBehavesCorrectly() { var mg = this.System.AddDerivedUnit("mg", "milligram", this.kg/(1000*1000)); var t = this.System.AddDerivedUnit("t", "tonne", 1000*this.kg); var mass = new Quantity(10*1000, this.kg); Assert.AreEqual(mass, mass.Convert(mg)); Assert.AreEqual(mass, mass.Convert(t)); Assert.AreEqual("10000000000 mg", mass.ToString(mg)); Assert.AreEqual("10 t", mass.ToString(t)); }
public void ThenCanSerializeAndDeserializeUsingJsonNet() { var quantity = new Quantity(100, this.J/(this.m ^ 3)); var info = quantity.ToInfo(); var json = JsonConvert.SerializeObject(info); var deserializedInfo = JsonConvert.DeserializeObject<QuantityInfo>(json); var result = this.System.FromInfo(deserializedInfo); Assert.AreEqual(quantity, result); }
public void ThenCanSerializeAndDeserializeUsingJavaScriptSerializer() { var quantity = new Quantity(100, this.J/(this.m ^ 3)); var info = quantity.ToInfo(); var serializer = new JavaScriptSerializer(); var json = serializer.Serialize(info); var deserializedInfo = serializer.Deserialize<QuantityInfo>(json); var result = this.System.FromInfo(deserializedInfo); Assert.AreEqual(quantity, result); }
public void ShouldXXX() //bug { //GIVEN var something1 = Substitute.For <ISomething>(); var something2 = Substitute.For <ISomething>(); //WHEN something1.Do1(); something1.Do1(); something2.Do1(); //THEN something1.Invoking(s => s.ReceivedOnly(Quantity.Exactly(1)).Do1()) .Should().ThrowExactly <ReceivedCallsException>() .WithMessage(@" Expected to receive *exactly 1 call total on this substitute*. Actually received the following calls: Do1() Do1() "); something2.Invoking(s => s.ReceivedOnly(Quantity.Exactly(1)).Do1()).Should().NotThrow(); }
private static IQuantity ParseValueUnit(ValueUnit vu) { // "MassUnit.Kilogram" => "MassUnit" and "Kilogram" string unitEnumTypeName = vu.Unit.Split('.')[0]; string unitEnumValue = vu.Unit.Split('.')[1]; // "UnitsNet.Units.MassUnit,UnitsNet" string unitEnumTypeAssemblyQualifiedName = "UnitsNet.Units." + unitEnumTypeName + ",UnitsNet"; // -- see http://stackoverflow.com/a/6465096/1256096 for details Type unitEnumType = Type.GetType(unitEnumTypeAssemblyQualifiedName); if (unitEnumType == null) { var ex = new UnitsNetException("Unable to find enum type."); ex.Data["type"] = unitEnumTypeAssemblyQualifiedName; throw ex; } double value = vu.Value; Enum unitValue = (Enum)Enum.Parse(unitEnumType, unitEnumValue); // Ex: MassUnit.Kilogram return(Quantity.From(value, unitValue)); }
public NamedUnit(IUnitSystem unitSystem, String name, Quantity physicalQuantity, CalculatorEnvironment environment /* = null */) { this.Environment = environment; if (physicalQuantity != null) { if ((unitSystem == null) && (physicalQuantity.Unit != null)) { unitSystem = physicalQuantity.Unit.ExponentsSystem; } if (physicalQuantity.Value != 0 && physicalQuantity.Value != 1) { this.pu = MakeScaledUnit(name, unitSystem, physicalQuantity.Unit, physicalQuantity.Value); } else { this.pu = physicalQuantity.Unit; } } else { this.pu = MakeBaseUnit(name, unitSystem); } }
public Boolean VariableSetLocal(String variableName, Quantity variableValue) { // Find identifier INametableItem Item; Boolean Found = FindLocalIdentifier(variableName, out Item); if (Found && Item.Identifierkind == IdentifierKind.Variable) { // Identifier is a variable in local context; set it to specified value SetLocalIdentifier(variableName, new NamedVariable(variableValue, this)); } else { if (Found && Item.Identifierkind != IdentifierKind.Variable) { // Found locally but not as variable; Can't set as variable return(false); } else { // Variable not found; No local identifier with that name, Declare local variable this.NamedItems.Add(variableName, new NamedVariable(variableValue, this)); } } return(true); }
public IInputExchangeItem GetInputExchangeItem(int index) { // -- create a flow quanitity -- Dimension flowDimension = new Dimension(); flowDimension.SetPower(DimensionBase.Length, 3); flowDimension.SetPower(DimensionBase.Time, -1); Unit literPrSecUnit = new Unit("LiterPrSecond", 0.001, 0, "Liters pr Second"); Quantity flowQuantity = new Quantity(literPrSecUnit, "Flow", "Flow", global::OpenMI.Standard.ValueType.Scalar, flowDimension); Element element = new Element(); element.ID = "DummyElement"; ElementSet elementSet = new ElementSet("Dummy ElementSet", "DummyElementSet", ElementType.IDBased, new SpatialReference("no reference")); elementSet.AddElement(element); InputExchangeItem inputExchangeItem = new InputExchangeItem(); inputExchangeItem.ElementSet = elementSet; inputExchangeItem.Quantity = flowQuantity; return(inputExchangeItem); }
public IActionResult ConvertAndAdd([FromBody] Quantity quantity) { try { var result = this.quantityMeasurementBusiness.ConvertAndAdd(quantity); if (!result.Result.Equals(0)) { bool success = true; var message = "Data Added Sucessfully"; return(this.Ok(new { success, message, data = result })); } else { bool success = false; var message = "Failed To Add Data"; return(this.NotFound(new { success, message, data = result })); } } catch (Exception e) { bool success = false; return(this.BadRequest(new { success, message = e.Message })); } }
public async Task UpdatingAResource_ThenWeCanAccessHistoricValues() { var saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight")); var newResourceValues = Samples.GetJsonSample("WeightInGrams") .UpdateId(saveResult.RawResourceElement.Id); var updateResult = await Mediator.UpsertResourceAsync(newResourceValues, WeakETag.FromVersionId(saveResult.RawResourceElement.VersionId)); var getV1Result = (await Mediator.GetResourceAsync(new ResourceKey <Observation>(saveResult.RawResourceElement.Id, saveResult.RawResourceElement.VersionId))).ToResourceElement(_deserializer); Assert.NotNull(getV1Result); Assert.Equal(saveResult.RawResourceElement.Id, getV1Result.Id); Assert.Equal(updateResult.RawResourceElement.Id, getV1Result.Id); var oldObservation = getV1Result.ToPoco <Observation>(); Assert.NotNull(oldObservation); Assert.NotNull(oldObservation.Value); Quantity sq = Assert.IsType <Quantity>(oldObservation.Value); Assert.Equal(67, sq.Value); }
public void Verify_fully_calculated_trajectory( [PlanarAngleValues] IQuantity vlaQty, [VelocityValues] IQuantity ivQty) { Parameters.VerticalLaunchAngleQty = vlaQty; Parameters.InitialVelocityQty = ivQty; var ms = T.Millisecond; var t = new Quantity(100d, ms); var currentTimeQty = Quantity.Zero(ms); using (Calculator.ObserveCalculated.Subscribe(OnNext)) { // Keep calculating while we are allowed to do so. while (Continue) { Calculator.Calculate(currentTimeQty += t); } } // Verify that we have a valid trajectory. _trajectory.Verify(MaxHeightQty); }
/// <summary> /// Initializes a new instance of the <see cref="OrderFillEvent"/> class. /// </summary> /// <param name="accountId">The event account identifier.</param> /// <param name="orderId">The event order identifier.</param> /// <param name="executionId">The event order execution identifier.</param> /// <param name="positionIdBroker">The event broker position identifier.</param> /// <param name="symbol">The event order symbol.</param> /// <param name="orderSide">The event order side.</param> /// <param name="filledQuantity">The event order filled quantity.</param> /// <param name="averagePrice">The event order average price.</param> /// <param name="quoteCurrency">The event quote currency.</param> /// <param name="executionTime">The event order execution time.</param> /// <param name="eventType">The event type.</param> /// <param name="eventId">The event identifier.</param> /// <param name="eventTimestamp">The event timestamp.</param> protected OrderFillEvent( AccountId accountId, OrderId orderId, ExecutionId executionId, PositionIdBroker positionIdBroker, Symbol symbol, OrderSide orderSide, Quantity filledQuantity, Price averagePrice, Currency quoteCurrency, ZonedDateTime executionTime, Type eventType, Guid eventId, ZonedDateTime eventTimestamp) : base( orderId, eventType, eventId, eventTimestamp) { Condition.NotDefault(orderSide, nameof(orderSide)); Condition.NotDefault(quoteCurrency, nameof(quoteCurrency)); Debug.NotDefault(executionTime, nameof(executionTime)); Debug.NotDefault(eventId, nameof(eventId)); Debug.NotDefault(eventTimestamp, nameof(eventTimestamp)); this.AccountId = accountId; this.PositionIdBroker = positionIdBroker; this.ExecutionId = executionId; this.Symbol = symbol; this.OrderSide = orderSide; this.FilledQuantity = filledQuantity; this.AveragePrice = averagePrice; this.Currency = quoteCurrency; this.ExecutionTime = executionTime; }
/// <inheritdoc/> public string ToDelimitedString() { CultureInfo culture = CultureInfo.CurrentCulture; return(string.Format( culture, StringHelper.StringFormatSequence(0, 15, Configuration.FieldSeparator), Id, SetIdTq1.HasValue ? SetIdTq1.Value.ToString(culture) : null, Quantity?.ToDelimitedString(), RepeatPattern != null ? string.Join(Configuration.FieldRepeatSeparator, RepeatPattern.Select(x => x.ToDelimitedString())) : null, ExplicitTime != null ? string.Join(Configuration.FieldRepeatSeparator, ExplicitTime.Select(x => x.ToString(Consts.TimeFormatPrecisionSecond, culture))) : null, RelativeTimeAndUnits != null ? string.Join(Configuration.FieldRepeatSeparator, RelativeTimeAndUnits.Select(x => x.ToDelimitedString())) : null, ServiceDuration?.ToDelimitedString(), StartDateTime.HasValue ? StartDateTime.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null, EndDateTime.HasValue ? EndDateTime.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null, Priority != null ? string.Join(Configuration.FieldRepeatSeparator, Priority.Select(x => x.ToDelimitedString())) : null, ConditionText?.ToDelimitedString(), TextInstruction?.ToDelimitedString(), Conjunction, OccurrenceDuration?.ToDelimitedString(), TotalOccurrences.HasValue ? TotalOccurrences.Value.ToString(Consts.NumericFormat, culture) : null ).TrimEnd(Configuration.FieldSeparator.ToCharArray())); }
abstract public Boolean Evaluate(CalculatorEnvironment localContext, List <Quantity> parameterlist, out Quantity functionResult, ref String resultLine);
private void ActionTask(string status) { try { if (Quantity == 0 && status != "2" && status != "3") { _navigationService.DisplayAlert("Task Error", @"Quantity is not valid!", "Ok"); return; } DataContext.Quantity = Quantity; string qty = Quantity.ToString(); if (String.IsNullOrEmpty(DataContext.BoxNo) && status == "0") { _navigationService.DisplayAlert("Task Error", @"Box Number is not valid!", "Ok"); return; } if (status == "0") { DataContext.TaskWasWIP = false; } Result result; string lastPigeonHole = ""; if (DataContext.BoxNo.Length > 4) { lastPigeonHole = DataContext.BoxNo.Substring(DataContext.BoxNo.Length - 4, 4); } string fromLocationCode = DataContext.FromLocationCode; //Result validUser = ConnectionService.ValidateUsertask(AppSession.UserId, DataContext.TaskDetailID); //if (!validUser.Status) //{ // _navigationService.DisplayAlert("Task User Error", "User is not connected to backend system.You will be logged off", "Ok"); // ReSetTaskDetail(); // _navigationService.PushAsync(new LoginPage()); // return; //} result = ConnectionService.CompleteFinePickTask(DataContext, AppSession.UserId, status, DataContext.TaskDetailID, false); if (result.Status) { DataContext = JsonConvert.DeserializeObject <GetNextTaskModel>(result.Data.ToString()); switch (status) { case "2": _navigationService.DisplayAlert("Skip Complete", $"{qty} units has been skipped!", "Ok"); break; case "3": _navigationService.DisplayAlert("On Hold Complete", $"{qty} units has been put on hold!", "Ok"); break; default: break; } } else { AppSession.ExecutingTaskId = 0; AppSession.LastRoleId = 0; if (result.Message.Contains("No more tasks for")) { _navigationService.DisplayAlert("No Tasks", result.Message, "Ok"); _navigationService.PushAsync(new FinePickSearchPage()); } else { if (result.Message.Contains("This order was already place in a PigeonHole")) { //ViewController.ShowMessage(this, "Task Error", result.Message, true); //isNewPigeonHole = true; //dataContext.BoxNo = fromLocationCode + result.Data.ToString(); //lbPigHoleDisplay.Text = result.Data.ToString(); //totalQty--; //txtBoxNo.Text = totalQty.ToString(); //txtBoxNo.Text = string.Empty; //txtBoxNo.Focus(); _navigationService.DisplayAlert("Task Error", result.Message, "Ok"); _dataContext.BoxNo = fromLocationCode + result.Data.ToString(); } else { _navigationService.DisplayAlert("Task Error", result.Message, "Ok"); } } } } catch (Exception ex) { _navigationService.DisplayAlert("Task Error", ex.Message, "Ok"); } }
public void Save(string time, double price) { Revenue = CumulativeRevenue - Commission; list.Add(string.Concat(DateTime.ParseExact(time.Substring(0, 6), "yyMMdd", CultureInfo.CurrentCulture).ToString("yy-MM-dd"), ',', (long)(Quantity.Equals(0) ? 0 : (Quantity > 0 ? price - PurchasePrice : PurchasePrice - price) * st.TransactionMultiplier * Math.Abs(Quantity)), ',', Revenue - TodayRevenue, ',', CumulativeRevenue - Commission)); TodayRevenue = Revenue; }
public void Configure(EntityTypeBuilder <OrderLine> orderLineConfiguration) { orderLineConfiguration.Property(b => b.Id).HasColumnName("OrderLineID"); orderLineConfiguration.Property(b => b.Quantity).HasConversion(p => p.Value, p => Quantity.Create(p).Value).IsRequired(); orderLineConfiguration.Property(b => b.Tax).HasConversion(p => p.Value, p => Tax.Create(p).Value).IsRequired(); orderLineConfiguration.HasOne(s => s.Item).WithMany().IsRequired(); orderLineConfiguration.HasOne(s => s.Order).WithMany(s => s.OrderLines).IsRequired(); }
public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { void Assertion(int expectedValue, Enum expectedUnit, IQuantity quantity) { Assert.Equal(expectedUnit, quantity.Unit); Assert.Equal(expectedValue, quantity.Value); } Assertion(3, AccelerationUnit.StandardGravity, Quantity.From(3, AccelerationUnit.StandardGravity)); Assertion(3, AmountOfSubstanceUnit.PoundMole, Quantity.From(3, AmountOfSubstanceUnit.PoundMole)); Assertion(3, AmplitudeRatioUnit.DecibelVolt, Quantity.From(3, AmplitudeRatioUnit.DecibelVolt)); Assertion(3, AngleUnit.Tilt, Quantity.From(3, AngleUnit.Tilt)); Assertion(3, ApparentEnergyUnit.VoltampereHour, Quantity.From(3, ApparentEnergyUnit.VoltampereHour)); Assertion(3, ApparentPowerUnit.Voltampere, Quantity.From(3, ApparentPowerUnit.Voltampere)); Assertion(3, AreaUnit.UsSurveySquareFoot, Quantity.From(3, AreaUnit.UsSurveySquareFoot)); Assertion(3, AreaDensityUnit.KilogramPerSquareMeter, Quantity.From(3, AreaDensityUnit.KilogramPerSquareMeter)); Assertion(3, AreaMomentOfInertiaUnit.MillimeterToTheFourth, Quantity.From(3, AreaMomentOfInertiaUnit.MillimeterToTheFourth)); Assertion(3, BitRateUnit.TerabytePerSecond, Quantity.From(3, BitRateUnit.TerabytePerSecond)); Assertion(3, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, Quantity.From(3, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour)); Assertion(3, CapacitanceUnit.Picofarad, Quantity.From(3, CapacitanceUnit.Picofarad)); Assertion(3, CoefficientOfThermalExpansionUnit.InverseKelvin, Quantity.From(3, CoefficientOfThermalExpansionUnit.InverseKelvin)); Assertion(3, DensityUnit.TonnePerCubicMillimeter, Quantity.From(3, DensityUnit.TonnePerCubicMillimeter)); Assertion(3, DurationUnit.Year365, Quantity.From(3, DurationUnit.Year365)); Assertion(3, DynamicViscosityUnit.Reyn, Quantity.From(3, DynamicViscosityUnit.Reyn)); Assertion(3, ElectricAdmittanceUnit.Siemens, Quantity.From(3, ElectricAdmittanceUnit.Siemens)); Assertion(3, ElectricChargeUnit.MilliampereHour, Quantity.From(3, ElectricChargeUnit.MilliampereHour)); Assertion(3, ElectricChargeDensityUnit.CoulombPerCubicMeter, Quantity.From(3, ElectricChargeDensityUnit.CoulombPerCubicMeter)); Assertion(3, ElectricConductanceUnit.Siemens, Quantity.From(3, ElectricConductanceUnit.Siemens)); Assertion(3, ElectricConductivityUnit.SiemensPerMeter, Quantity.From(3, ElectricConductivityUnit.SiemensPerMeter)); Assertion(3, ElectricCurrentUnit.Picoampere, Quantity.From(3, ElectricCurrentUnit.Picoampere)); Assertion(3, ElectricCurrentDensityUnit.AmperePerSquareMeter, Quantity.From(3, ElectricCurrentDensityUnit.AmperePerSquareMeter)); Assertion(3, ElectricCurrentGradientUnit.AmperePerSecond, Quantity.From(3, ElectricCurrentGradientUnit.AmperePerSecond)); Assertion(3, ElectricFieldUnit.VoltPerMeter, Quantity.From(3, ElectricFieldUnit.VoltPerMeter)); Assertion(3, ElectricInductanceUnit.Nanohenry, Quantity.From(3, ElectricInductanceUnit.Nanohenry)); Assertion(3, ElectricPotentialUnit.Volt, Quantity.From(3, ElectricPotentialUnit.Volt)); Assertion(3, ElectricPotentialAcUnit.VoltAc, Quantity.From(3, ElectricPotentialAcUnit.VoltAc)); Assertion(3, ElectricPotentialChangeRateUnit.VoltPerSecond, Quantity.From(3, ElectricPotentialChangeRateUnit.VoltPerSecond)); Assertion(3, ElectricPotentialDcUnit.VoltDc, Quantity.From(3, ElectricPotentialDcUnit.VoltDc)); Assertion(3, ElectricResistanceUnit.Ohm, Quantity.From(3, ElectricResistanceUnit.Ohm)); Assertion(3, ElectricResistivityUnit.PicoohmMeter, Quantity.From(3, ElectricResistivityUnit.PicoohmMeter)); Assertion(3, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, Quantity.From(3, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter)); Assertion(3, EnergyUnit.WattHour, Quantity.From(3, EnergyUnit.WattHour)); Assertion(3, EntropyUnit.MegajoulePerKelvin, Quantity.From(3, EntropyUnit.MegajoulePerKelvin)); Assertion(3, ForceUnit.TonneForce, Quantity.From(3, ForceUnit.TonneForce)); Assertion(3, ForceChangeRateUnit.PoundForcePerSecond, Quantity.From(3, ForceChangeRateUnit.PoundForcePerSecond)); Assertion(3, ForcePerLengthUnit.TonneForcePerMillimeter, Quantity.From(3, ForcePerLengthUnit.TonneForcePerMillimeter)); Assertion(3, FrequencyUnit.Terahertz, Quantity.From(3, FrequencyUnit.Terahertz)); Assertion(3, FuelEfficiencyUnit.MilePerUsGallon, Quantity.From(3, FuelEfficiencyUnit.MilePerUsGallon)); Assertion(3, HeatFluxUnit.WattPerSquareMeter, Quantity.From(3, HeatFluxUnit.WattPerSquareMeter)); Assertion(3, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, Quantity.From(3, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin)); Assertion(3, IlluminanceUnit.Millilux, Quantity.From(3, IlluminanceUnit.Millilux)); Assertion(3, InformationUnit.Terabyte, Quantity.From(3, InformationUnit.Terabyte)); Assertion(3, IrradianceUnit.WattPerSquareMeter, Quantity.From(3, IrradianceUnit.WattPerSquareMeter)); Assertion(3, IrradiationUnit.WattHourPerSquareMeter, Quantity.From(3, IrradiationUnit.WattHourPerSquareMeter)); Assertion(3, KinematicViscosityUnit.Stokes, Quantity.From(3, KinematicViscosityUnit.Stokes)); Assertion(3, LapseRateUnit.DegreeCelsiusPerKilometer, Quantity.From(3, LapseRateUnit.DegreeCelsiusPerKilometer)); Assertion(3, LengthUnit.Yard, Quantity.From(3, LengthUnit.Yard)); Assertion(3, LevelUnit.Neper, Quantity.From(3, LevelUnit.Neper)); Assertion(3, LinearDensityUnit.PoundPerInch, Quantity.From(3, LinearDensityUnit.PoundPerInch)); Assertion(3, LinearPowerDensityUnit.WattPerMillimeter, Quantity.From(3, LinearPowerDensityUnit.WattPerMillimeter)); Assertion(3, LuminosityUnit.Watt, Quantity.From(3, LuminosityUnit.Watt)); Assertion(3, LuminousFluxUnit.Lumen, Quantity.From(3, LuminousFluxUnit.Lumen)); Assertion(3, LuminousIntensityUnit.Candela, Quantity.From(3, LuminousIntensityUnit.Candela)); Assertion(3, MagneticFieldUnit.Tesla, Quantity.From(3, MagneticFieldUnit.Tesla)); Assertion(3, MagneticFluxUnit.Weber, Quantity.From(3, MagneticFluxUnit.Weber)); Assertion(3, MagnetizationUnit.AmperePerMeter, Quantity.From(3, MagnetizationUnit.AmperePerMeter)); Assertion(3, MassUnit.Tonne, Quantity.From(3, MassUnit.Tonne)); Assertion(3, MassConcentrationUnit.TonnePerCubicMillimeter, Quantity.From(3, MassConcentrationUnit.TonnePerCubicMillimeter)); Assertion(3, MassFlowUnit.TonnePerHour, Quantity.From(3, MassFlowUnit.TonnePerHour)); Assertion(3, MassFluxUnit.KilogramPerSecondPerSquareMillimeter, Quantity.From(3, MassFluxUnit.KilogramPerSecondPerSquareMillimeter)); Assertion(3, MassFractionUnit.Percent, Quantity.From(3, MassFractionUnit.Percent)); Assertion(3, MassMomentOfInertiaUnit.TonneSquareMilimeter, Quantity.From(3, MassMomentOfInertiaUnit.TonneSquareMilimeter)); Assertion(3, MolarEnergyUnit.MegajoulePerMole, Quantity.From(3, MolarEnergyUnit.MegajoulePerMole)); Assertion(3, MolarEntropyUnit.MegajoulePerMoleKelvin, Quantity.From(3, MolarEntropyUnit.MegajoulePerMoleKelvin)); Assertion(3, MolarityUnit.PicomolesPerLiter, Quantity.From(3, MolarityUnit.PicomolesPerLiter)); Assertion(3, MolarMassUnit.PoundPerMole, Quantity.From(3, MolarMassUnit.PoundPerMole)); Assertion(3, PermeabilityUnit.HenryPerMeter, Quantity.From(3, PermeabilityUnit.HenryPerMeter)); Assertion(3, PermittivityUnit.FaradPerMeter, Quantity.From(3, PermittivityUnit.FaradPerMeter)); Assertion(3, PowerUnit.Watt, Quantity.From(3, PowerUnit.Watt)); Assertion(3, PowerDensityUnit.WattPerLiter, Quantity.From(3, PowerDensityUnit.WattPerLiter)); Assertion(3, PowerRatioUnit.DecibelWatt, Quantity.From(3, PowerRatioUnit.DecibelWatt)); Assertion(3, PressureUnit.Torr, Quantity.From(3, PressureUnit.Torr)); Assertion(3, PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, Quantity.From(3, PressureChangeRateUnit.PoundForcePerSquareInchPerSecond)); Assertion(3, RatioUnit.Strain, Quantity.From(3, RatioUnit.Strain)); Assertion(3, RatioChangeRateUnit.PercentPerSecond, Quantity.From(3, RatioChangeRateUnit.PercentPerSecond)); Assertion(3, ReactiveEnergyUnit.VoltampereReactiveHour, Quantity.From(3, ReactiveEnergyUnit.VoltampereReactiveHour)); Assertion(3, ReactivePowerUnit.VoltampereReactive, Quantity.From(3, ReactivePowerUnit.VoltampereReactive)); Assertion(3, RelativeHumidityUnit.Percent, Quantity.From(3, RelativeHumidityUnit.Percent)); Assertion(3, RotationalAccelerationUnit.RevolutionPerSecondSquared, Quantity.From(3, RotationalAccelerationUnit.RevolutionPerSecondSquared)); Assertion(3, RotationalSpeedUnit.RevolutionPerSecond, Quantity.From(3, RotationalSpeedUnit.RevolutionPerSecond)); Assertion(3, RotationalStiffnessUnit.PoundForceFootPerDegrees, Quantity.From(3, RotationalStiffnessUnit.PoundForceFootPerDegrees)); Assertion(3, RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, Quantity.From(3, RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot)); Assertion(3, ScalarUnit.Amount, Quantity.From(3, ScalarUnit.Amount)); Assertion(3, SolidAngleUnit.Steradian, Quantity.From(3, SolidAngleUnit.Steradian)); Assertion(3, SpecificEnergyUnit.WattHourPerKilogram, Quantity.From(3, SpecificEnergyUnit.WattHourPerKilogram)); Assertion(3, SpecificEntropyUnit.MegajoulePerKilogramKelvin, Quantity.From(3, SpecificEntropyUnit.MegajoulePerKilogramKelvin)); Assertion(3, SpecificVolumeUnit.MillicubicMeterPerKilogram, Quantity.From(3, SpecificVolumeUnit.MillicubicMeterPerKilogram)); Assertion(3, SpecificWeightUnit.TonneForcePerCubicMillimeter, Quantity.From(3, SpecificWeightUnit.TonneForcePerCubicMillimeter)); Assertion(3, SpeedUnit.YardPerSecond, Quantity.From(3, SpeedUnit.YardPerSecond)); Assertion(3, StandardVolumeFlowUnit.StandardLiterPerMinute, Quantity.From(3, StandardVolumeFlowUnit.StandardLiterPerMinute)); Assertion(3, TemperatureUnit.SolarTemperature, Quantity.From(3, TemperatureUnit.SolarTemperature)); Assertion(3, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, Quantity.From(3, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond)); Assertion(3, TemperatureDeltaUnit.MillidegreeCelsius, Quantity.From(3, TemperatureDeltaUnit.MillidegreeCelsius)); Assertion(3, ThermalConductivityUnit.WattPerMeterKelvin, Quantity.From(3, ThermalConductivityUnit.WattPerMeterKelvin)); Assertion(3, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, Quantity.From(3, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt)); Assertion(3, TorqueUnit.TonneForceMillimeter, Quantity.From(3, TorqueUnit.TonneForceMillimeter)); Assertion(3, TorquePerLengthUnit.TonneForceMillimeterPerMeter, Quantity.From(3, TorquePerLengthUnit.TonneForceMillimeterPerMeter)); Assertion(3, TurbidityUnit.NTU, Quantity.From(3, TurbidityUnit.NTU)); Assertion(3, VitaminAUnit.InternationalUnit, Quantity.From(3, VitaminAUnit.InternationalUnit)); Assertion(3, VolumeUnit.UsTeaspoon, Quantity.From(3, VolumeUnit.UsTeaspoon)); Assertion(3, VolumeConcentrationUnit.PicolitersPerMililiter, Quantity.From(3, VolumeConcentrationUnit.PicolitersPerMililiter)); Assertion(3, VolumeFlowUnit.UsGallonPerSecond, Quantity.From(3, VolumeFlowUnit.UsGallonPerSecond)); Assertion(3, VolumePerLengthUnit.OilBarrelPerFoot, Quantity.From(3, VolumePerLengthUnit.OilBarrelPerFoot)); Assertion(3, WarpingMomentOfInertiaUnit.MillimeterToTheSixth, Quantity.From(3, WarpingMomentOfInertiaUnit.MillimeterToTheSixth)); }
override public Boolean Evaluate(CalculatorEnvironment localContext, List <Quantity> actualParameterlist, out Quantity functionResult, ref String resultLine) { if (PhysicalFunction.ExecuteCommandsCallback != null) { // Set params in local context int ParamIndex = 0; if (formalparamlist != null) { foreach (PhysicalQuantityFunctionParam Param in formalparamlist) { if (actualParameterlist.Count <= ParamIndex) { resultLine = "Missing parameter no " + (ParamIndex + 1).ToString() + " " + Param.Name; functionResult = null; return(false); } Quantity paramValue = actualParameterlist[ParamIndex]; if (Param.Unit != null) { Quantity paramValueConverted = paramValue.ConvertTo(Param.Unit); if (paramValueConverted == null) { resultLine = "Parameter no " + (ParamIndex + 1).ToString() + " " + Param.Name + " " + paramValue.ToString() + " has invalid unit.\nThe unit " + paramValue.Unit.ToPrintString() + " can't be converted to " + Param.Unit.ToPrintString(); functionResult = null; return(false); } else { paramValue = paramValueConverted; } } localContext.NamedItems.SetItem(Param.Name, new NamedVariable(paramValue)); ParamIndex++; } } if (ParamIndex < actualParameterlist.Count) { resultLine = "Too many parameters specified in function call: " + actualParameterlist.Count + ". " + ParamIndex + " parameters was expected"; functionResult = null; return(false); } // Run commands String FuncBodyResult = ""; // Dummy: Never used return(PhysicalFunction.ExecuteCommandsCallback(localContext, Commands, ref FuncBodyResult, out functionResult)); } else { if (Commands != null) { resultLine = "Function call: PhysicalFunction.ExecuteCommandsCallback is null. Don't know how to evaluate function."; } functionResult = null; return(false); } }
public void Throw(ICallSpecification callSpecification, IEnumerable <ICall> matchingCalls, IEnumerable <ICall> nonMatchingCalls, Quantity requiredQuantity) { _wasCalled = true; _callSpecification = callSpecification; _matchingCalls = matchingCalls; _nonMatchingCalls = nonMatchingCalls; _requiredQuantity = requiredQuantity; }
public UnitTestStubGenerator(Quantity quantity) { _quantity = quantity; }
private Temperature(Quantity <ITemperature> quantity) => Quantity = quantity;
public bool Validate() { return(Quantity.Validate() && MonkeyList.Validate()); }
public Quantity adjust(Quantity balance, Quantity adjustment) { return(balance.subtract(adjustment)); }
public void Initialize(System.Collections.Hashtable properties) { if (properties.ContainsKey("ModelID")) { _modelID = (string)properties["ModelID"]; } if (properties.ContainsKey("TimeStepLength")) { _timeStepLength = Convert.ToDouble((string)properties["TimeStepLength"]); } // -- create a flow quanitity -- Dimension flowDimension = new Dimension(); flowDimension.SetPower(DimensionBase.Length, 3); flowDimension.SetPower(DimensionBase.Time, -1); Unit literPrSecUnit = new Unit("LiterPrSecond", 0.001, 0, "Liters pr Second"); Quantity flowQuantity = new Quantity(literPrSecUnit, "Flow", "Flow", global::OpenMI.Standard.ValueType.Scalar, flowDimension); // -- create leakage quantity -- Quantity leakageQuantity = new Quantity(literPrSecUnit, "Leakage", "Leakage", global::OpenMI.Standard.ValueType.Scalar, flowDimension); // -- create and populate elementset to represente the whole river network -- ElementSet fullRiverElementSet = new ElementSet("WholeRiver", "WholeRiver", ElementType.XYPolyLine, new SpatialReference("no reference")); for (int i = 0; i < _numberOfNodes - 1; i++) { Element element = new Element(); element.ID = "Branch:" + i.ToString(); element.AddVertex(new Vertex(_xCoordinate[i], _yCoordinate[i], -999)); element.AddVertex(new Vertex(_xCoordinate[i + 1], _yCoordinate[i + 1], -999)); fullRiverElementSet.AddElement(element); } // --- populate input exchange items for flow to individual nodes --- for (int i = 0; i < _numberOfNodes; i++) { Element element = new Element(); element.ID = "Node:" + i.ToString(); ElementSet elementSet = new ElementSet("Individual nodes", "Node:" + i.ToString(), ElementType.IDBased, new SpatialReference("no reference")); elementSet.AddElement(element); InputExchangeItem inputExchangeItem = new InputExchangeItem(); inputExchangeItem.ElementSet = elementSet; inputExchangeItem.Quantity = flowQuantity; _inputExchangeItems.Add(inputExchangeItem); } // --- Populate input exchange item for flow to the whole georeferenced river --- InputExchangeItem wholeRiverInputExchangeItem = new InputExchangeItem(); wholeRiverInputExchangeItem.ElementSet = fullRiverElementSet; wholeRiverInputExchangeItem.Quantity = flowQuantity; _inputExchangeItems.Add(wholeRiverInputExchangeItem); // --- Populate output exchange items for flow in river branches --- for (int i = 0; i < _numberOfNodes - 1; i++) { Element element = new Element(); element.ID = "Branch:" + i.ToString(); ElementSet elementSet = new ElementSet("Individual nodes", "Branch:" + i.ToString(), ElementType.IDBased, new SpatialReference("no reference")); elementSet.AddElement(element); OutputExchangeItem outputExchangeItem = new OutputExchangeItem(); outputExchangeItem.ElementSet = elementSet; outputExchangeItem.Quantity = flowQuantity; _outputExchangeItems.Add(outputExchangeItem); } // --- polulate output exchange items for leakage for individual branches -- for (int i = 0; i < _numberOfNodes - 1; i++) { Element element = new Element(); element.ID = "Branch:" + i.ToString(); ElementSet elementSet = new ElementSet("Individual nodes", "Branch:" + i.ToString(), ElementType.IDBased, new SpatialReference("no reference")); elementSet.AddElement(element); OutputExchangeItem outputExchangeItem = new OutputExchangeItem(); outputExchangeItem.ElementSet = elementSet; outputExchangeItem.Quantity = leakageQuantity; _outputExchangeItems.Add(outputExchangeItem); } // --- Populate output exchange item for leakage from the whole georeferenced river --- OutputExchangeItem wholeRiverOutputExchangeItem = new OutputExchangeItem(); wholeRiverOutputExchangeItem.ElementSet = fullRiverElementSet; wholeRiverOutputExchangeItem.Quantity = leakageQuantity; _outputExchangeItems.Add(wholeRiverOutputExchangeItem); // --- populate with initial state variables --- for (int i = 0; i < _numberOfNodes - 1; i++) { _flow[i] = 7; } _currentTimeStepNumber = 1; _initializeMethodWasInvoked = true; }
override public Boolean Evaluate(CalculatorEnvironment localContext, List <Quantity> actualParameterlist, out Quantity functionResult, ref String resultLine) { if (!CheckParams(actualParameterlist, ref resultLine)) { functionResult = null; return(false); } functionResult = F(actualParameterlist[0], actualParameterlist[1]); return(true); }
public Boolean Evaluate(CalculatorEnvironment localContext, out Quantity functionResult, ref String resultLine) => Evaluate(localContext, null, out functionResult, ref resultLine);
public void ShouldHaveBeenToldToThrowWith(ICallSpecification callSpecification, IEnumerable <ICall> matchingCalls, IEnumerable <ICall> nonMatchingCalls, Quantity requiredQuantity) { Assert.That(_callSpecification, Is.EqualTo(callSpecification)); Assert.That(_matchingCalls.ToArray(), Is.EquivalentTo(matchingCalls.ToArray())); Assert.That(_nonMatchingCalls.ToArray(), Is.EquivalentTo(nonMatchingCalls.ToArray())); Assert.That(_requiredQuantity, Is.EqualTo(requiredQuantity)); }
public Item Mutate(Mobile from, Item item) { if (item != null && !(item is BaseWand)) { if (item is BaseWeapon && 1 > Utility.Random(100)) { item.Delete(); item = new FireHorn(); return(item); } if (item is BaseWeapon || item is BaseArmor || item is BaseJewel || item is BaseHat) { if (item is BaseWeapon) { var weapon = (BaseWeapon)item; if (55 > Utility.Random(100)) { weapon.AccuracyLevel = (WeaponAccuracyLevel)GetRandomOldBonus(); } if (45 > Utility.Random(100)) { int damageLevel = GetRandomOldBonus(); if (PseudoSeerStone.Instance != null && PseudoSeerStone.Instance._HighestDamageLevelSpawn < damageLevel) { if (damageLevel == 5 && PseudoSeerStone.ReplaceVanqWithSkillScrolls) { return(PuzzleChest.CreateRandomSkillScroll()); } int platAmount = PseudoSeerStone.PlatinumPerMissedDamageLevel * (damageLevel - PseudoSeerStone.Instance._HighestDamageLevelSpawn); if (platAmount > 0) { return(new Platinum(platAmount)); } damageLevel = PseudoSeerStone.Instance._HighestDamageLevelSpawn; } weapon.DamageLevel = (WeaponDamageLevel)damageLevel; } if (25 > Utility.Random(100)) { weapon.DurabilityLevel = (WeaponDurabilityLevel)GetRandomOldBonus(); } if (5 > Utility.Random(100)) { weapon.Slayer = SlayerName.Silver; } if (1 > Utility.Random(1000) || (weapon.AccuracyLevel == 0 && weapon.DamageLevel == 0 && weapon.DurabilityLevel == 0 && weapon.Slayer == SlayerName.None && 5 > Utility.Random(100))) { weapon.Slayer = from != null?SlayerGroup.GetLootSlayerType(from.GetType()) : BaseRunicTool.GetRandomSlayer(); } if (weapon.AccuracyLevel == 0 && weapon.DamageLevel == 0 && weapon.DurabilityLevel == 0 && weapon.Slayer == SlayerName.None) { weapon.Identified = true; } } else if (item is BaseArmor) { var armor = (BaseArmor)item; if (55 > Utility.Random(100)) { armor.ProtectionLevel = (ArmorProtectionLevel)GetRandomOldBonus(); } if (25 > Utility.Random(100)) { armor.Durability = (ArmorDurabilityLevel)GetRandomOldBonus(); } if (armor.ProtectionLevel == 0 && armor.Durability == 0) { armor.Identified = true; } } } else if (item is BaseInstrument) { SlayerName slayer = from == null || from.EraAOS ? BaseRunicTool.GetRandomSlayer() : SlayerGroup.GetLootSlayerType(from.GetType()); var instr = (BaseInstrument)item; instr.Quality = InstrumentQuality.Regular; instr.Slayer = slayer; } else if (item is Spellbook) //Randomize spellbook { var book = item as Spellbook; if (MaxIntensity == 100 && MinIntensity / 1000.0 > Utility.RandomDouble()) { book.LootType = LootType.Blessed; } if (MaxIntensity == 100 && MinIntensity >= 50 && (MinIntensity / 3000.0 > Utility.RandomDouble())) { book.Dyable = true; } int rnd = Utility.RandomMinMax(MinIntensity, MaxIntensity); var circle = (int)((rnd / 12.5) + 1.0); if (circle >= 8 && 0.33 > Utility.RandomDouble()) { book.Content = ulong.MaxValue; } else { circle = Math.Min(circle, 8); //do we fill this circle? for (int i = 0; i < circle; i++) { if (Utility.RandomBool()) { book.Content |= (ulong)Utility.Random(0x100) << (i * 8); } } } } if (item.Stackable) { // Note: do not check hits max here if you want to multiply against gold // the max hits have not been set when this function is called // The inital loot is added to the BaseCreature before the attributes are set // for the specific mob type if (item is Gold) { item.Amount = (int)Math.Ceiling(Quantity.Roll() * DynamicSettingsController.GoldMulti); } else { item.Amount = Quantity.Roll(); } } } return(item); }
public string GetInfo() { return ($"{PrintInCentre(Id.ToString())}{PrintInCentre(Traider.SecondName)}{PrintInCentre(StockType.Type)}{PrintInCentre(Quantity.ToString())}"); }
public MockSettings() { Metres = new SiUnit("Metres", "m") { QuantityName = "Length" }; SiUnits.Add(Metres); Length = Metres.Quantity; Seconds = new SiUnit("Seconds", "s") { QuantityName = "Time" }; SiUnits.Add(Seconds); Time = Seconds.Quantity; Kilograms = new SiUnit("Kilograms", "kg") { QuantityName = "Mass" }; SiUnits.Add(Kilograms); Mass = Kilograms.Quantity; Amperes = new SiUnit("Amperes", "A") { QuantityName = "ElectricalCurrent" }; SiUnits.Add(Amperes); Current = Amperes.Quantity; MetresPerSecond = new DerivedUnit( "MetresPerSecond", "m/s", new UnitAndPower(Metres, 1), new UnitAndPower(Seconds, -1)) { QuantityName = "Speed" }; DerivedUnits.Add(MetresPerSecond); Speed = MetresPerSecond.Quantity; Newtons = new DerivedUnit( "Newtons", "N", new UnitAndPower(Kilograms, 1), new UnitAndPower(Metres, 1), new UnitAndPower(Seconds, -2)) { QuantityName = "Force" }; DerivedUnits.Add(Newtons); Force = Newtons.Quantity; Joules = new DerivedUnit( "Joules", "J", new UnitAndPower(Newtons, 1), new UnitAndPower(Metres, 1)) { QuantityName = "Energy" }; DerivedUnits.Add(Joules); Energy = Joules.Quantity; Watts = new DerivedUnit( "Watts", "W", new UnitAndPower(Joules, 1), new UnitAndPower(Seconds, -1)) { QuantityName = "Power" }; DerivedUnits.Add(Watts); Power = Watts.Quantity; Volts = new DerivedUnit( "Volts", "V", new UnitAndPower(Watts, 1), new UnitAndPower(Amperes, -1)) { QuantityName = "Voltage" }; DerivedUnits.Add(Volts); Voltage = Volts.Quantity; Coloumbs = new DerivedUnit( "Coloumbs", "C", new UnitAndPower(Seconds, 1), new UnitAndPower(Amperes, 1)) { QuantityName = "ElectricCharge" }; DerivedUnits.Add(Coloumbs); ElectricCharge = Coloumbs.Quantity; SquareMetres = new DerivedUnit("SquareMetres", "m^2", new UnitAndPower(Metres, 2)) { QuantityName = "Area" }; DerivedUnits.Add(SquareMetres); Area = SquareMetres.Quantity; CubicMetres = new DerivedUnit("CubicMetres", "m^3", new UnitAndPower(Metres, 3)) { QuantityName = "Volume" }; DerivedUnits.Add(CubicMetres); Volume = CubicMetres.Quantity; Hertz = new DerivedUnit("Hertz", "1/s", new UnitAndPower(Seconds, -1)) { QuantityName = "Frequency" }; DerivedUnits.Add(Hertz); Frequency = Hertz.Quantity; }
public Item Mutate(Mobile from, int luckChance, Item item) { if (item != null) { if (item is BaseWeapon && 1 > Utility.Random(100)) { item.Delete(); item = new FireHorn(); return(item); } if (item is BaseWeapon || item is BaseArmor || item is BaseJewel || item is BaseHat) { if (Core.AOS) { // Try to generate a new random item based on the creature killed if (Core.HS && RandomItemGenerator.Enabled && from is BaseCreature) { if (RandomItemGenerator.GenerateRandomItem(item, ((BaseCreature)from).LastKiller, (BaseCreature)from)) { return(item); } } int bonusProps = GetBonusProperties(); _ = MinIntensity; _ = MaxIntensity; if (bonusProps < MaxProps && LootPack.CheckLuck(luckChance)) { ++bonusProps; } int props = 1 + bonusProps; // Make sure we're not spawning items with 6 properties. if (props > MaxProps) { props = MaxProps; } // Use the older style random generation if (item is BaseWeapon) { BaseRunicTool.ApplyAttributesTo((BaseWeapon)item, false, luckChance, props, MinIntensity, MaxIntensity); } else if (item is BaseArmor) { BaseRunicTool.ApplyAttributesTo((BaseArmor)item, false, luckChance, props, MinIntensity, MaxIntensity); } else if (item is BaseJewel) { BaseRunicTool.ApplyAttributesTo((BaseJewel)item, false, luckChance, props, MinIntensity, MaxIntensity); } else if (item is BaseHat) { BaseRunicTool.ApplyAttributesTo((BaseHat)item, false, luckChance, props, MinIntensity, MaxIntensity); } } else // not aos { if (item is BaseWeapon) { BaseWeapon weapon = (BaseWeapon)item; if (80 > Utility.Random(100)) { weapon.AccuracyLevel = (WeaponAccuracyLevel)GetRandomOldBonus(); } if (60 > Utility.Random(100)) { weapon.DamageLevel = (WeaponDamageLevel)GetRandomOldBonus(); } if (40 > Utility.Random(100)) { weapon.DurabilityLevel = (WeaponDurabilityLevel)GetRandomOldBonus(); } if (5 > Utility.Random(100)) { weapon.Slayer = SlayerName.Silver; } if (from != null && weapon.AccuracyLevel == 0 && weapon.DamageLevel == 0 && weapon.DurabilityLevel == 0 && weapon.Slayer == SlayerName.None && 5 > Utility.Random(100)) { weapon.Slayer = SlayerGroup.GetLootSlayerType(from.GetType()); } } else if (item is BaseArmor armor) { if (80 > Utility.Random(100)) { armor.ProtectionLevel = (ArmorProtectionLevel)GetRandomOldBonus(); } if (40 > Utility.Random(100)) { armor.Durability = (ArmorDurabilityLevel)GetRandomOldBonus(); } } } } else if (item is BaseInstrument) { SlayerName slayer; if (Core.AOS) { slayer = BaseRunicTool.GetRandomSlayer(); } else { slayer = SlayerGroup.GetLootSlayerType(from.GetType()); } if (slayer == SlayerName.None) { item.Delete(); return(null); } BaseInstrument instr = (BaseInstrument)item; instr.Quality = ItemQuality.Normal; instr.Slayer = slayer; } if (item.Stackable) { item.Amount = Quantity.Roll(); } } return(item); }