public VesselData(VesselData vd)
            {
                name = vd.name;
                id = vd.id;
                craftURL = vd.craftURL;
                craftPart = vd.craftPart;
                flagURL = vd.flagURL;
                vesselType = vd.vesselType;
                body = vd.body;
                orbit = vd.orbit;
                latitude = vd.latitude;
                longitude = vd.longitude;
                altitude = vd.altitude;
                height = vd.height;
                orbiting = vd.orbiting;
                owned = vd.owned;
                pqsCity = vd.pqsCity;
                pqsOffset = vd.pqsOffset;
                heading = vd.heading;
                pitch = vd.pitch;
                roll = vd.roll;

                foreach (CrewData cd in vd.crew)
                {
                    crew.Add(new CrewData(cd));
                }
            }
        public void Setup()
        {
            //Instance Fields Setup
            BooleanField = null;
            ByteField = null;
            SByteField = null;
            IntField = null;
            LongField = null;
            Int16Field = null;
            UInt16Field = null;
            Int32Field = null;
            UInt32Field = null;
            Int64Field = null;
            UInt64Field = null;
            CharField = null;
            DoubleField = null;
            FloatField = null;

            //Static Fields Setup
            BooleanFieldStatic = null;
            ByteFieldStatic = null;
            SByteFieldStatic = null;
            IntFieldStatic = null;
            LongFieldStatic = null;
            Int16FieldStatic = null;
            UInt16FieldStatic = null;
            Int32FieldStatic = null;
            UInt32FieldStatic = null;
            Int64FieldStatic = null;
            UInt64FieldStatic = null;
            CharFieldStatic = null;
            DoubleFieldStatic = null;
            FloatFieldStatic = null;
        }
Exemple #3
0
        protected override bool OnDeactivate()
        {
            selectedColor = null;
            selectedValue = null;

            return base.OnDeactivate();
        }
Exemple #4
0
 private void SetAllNull()
 {
     this.Top = null;
     this.Percent = null;
     this.Val = 0.0;
     this.FilterValue = null;
 }
Exemple #5
0
        public double Compute()
        {
            if (InputSynapses.Count == 0)
            {
                _calculatedCompute = 0;
                return 0;
            }

            if (_calculatedCompute.HasValue)
                return _calculatedCompute.Value;

            //защита от рекурсивных вызовов
            if (_loopProtector)
            {
               LoopDetected = true;
               return 0;
            }

            /*
            if (InputSynapses.Any(syn => syn.HasComputed!=true))
            {
                throw new Exception("LOOP");
            }*/

            _loopProtector = true;
            _calculatedCompute = _activationFunc(InputSynapses.Sum(s => s.Compute()));
            _loopProtector = false;

            return _calculatedCompute.Value;
        }
        private void SetSingleAreaValue(IGroupDataReader groupDataReader, Area area, Grouping grouping, TimePeriod period)
        {
            IList<CoreDataSet> dataList = groupDataReader.GetCoreData(grouping, period, area.Code);
            if (dataList.Count == 1)
            {
                var data = dataList.First();
                if (data.IsValueValid)
                {
                    Value = data.Value;

                    if (area.IsGpPractice == false)
                    {
                        // Calculate average

                        var areasReader = ReaderFactory.GetAreasReader();

                        int count = area.IsCountry ?
                            areasReader.GetAreaCountForAreaType(grouping.AreaTypeId) :
                            areasReader.GetChildAreaCount(area.Code, grouping.AreaTypeId);

                        Value /= count;
                    }
                }
            }
            else if (dataList.Count > 1)
            {
                throw new FingertipsException(string.Format(
                    "More data than expected on determination of QOF list size: area:{0}", area.Code));
            }
        }
        private Task StartWatcher(int i, int count)
        {
            IServiceBus serviceBus = ServiceBus.Configure()
                .WithEventStoreEndpoints<ITestMessage1>()
                .Named("Obvs.TestService")
                .ConnectToEventStore(EventStoreConnectionString)
                .SerializedAsJson()
                .AsServer()
                .UsingConsoleLogging()
                .Create();

            double?[] times = new double?[count];
            long[] received = {0};

            var dis = serviceBus.Commands.OfType<TestCommand>().Subscribe(x =>
            {
                var increment = Interlocked.Increment(ref received[0]);
                if (increment%100 == 0)
                    Console.WriteLine($"Watcher {i}: {increment} msgs");
                var ms = (Stopwatch.GetTimestamp() - x.Ticks)/((double) Stopwatch.Frequency/1000);
                times[x.Id] = ms;
            });

            return Task.Run(() =>
            {
                SpinWait.SpinUntil(() => Interlocked.Read(ref received[0]) == count);

                Console.WriteLine(
                    $"******* Watcher {i}: Total {_sw.ElapsedMilliseconds}ms ({count} msgs), Min/Avg/Max (ms) = {times.Min(d => d.Value):0}/{times.Average(d => d.Value):0}/{times.Max(d => d.Value):0}");

                dis.Dispose();
                ((IDisposable) serviceBus).Dispose();
            });
        }
 public MushroomRule(IDataProvider dataProvider, int generacion, char classValue)
 {
     DataProvider = dataProvider;
     Generation = generacion;
     ClassValue = classValue;
     solution = null;
 }
Exemple #9
0
        /// <summary>
        /// Get the next sample point from the gaussian distribution.
        /// </summary>
        public double NextDouble()
        {
            if (null != _spareValue)
            {
                double tmp = _spareValue.Value;
                _spareValue = null;
                return tmp;
            }

            // Generate two new gaussian values.
            double x, y, sqr;

            // We need a non-zero random point inside the unit circle.
            do
            {
                x = 2.0 * _rng.NextDouble() - 1.0;
                y = 2.0 * _rng.NextDouble() - 1.0;
                sqr = x * x + y * y;
            }
            while (sqr > 1.0 || sqr == 0);

            // Make the Box-Muller transformation.
            double fac = Math.Sqrt(-2.0 * Math.Log(sqr) / sqr);

            _spareValue = x * fac;
            return y * fac;
        }
Exemple #10
0
 public Battery(string model, BatteryType type)
     : this(model)
 {
     this.hoursIdle = null;  //setting the field
     this.hoursTalk = null;  //setting the field
     this.Type = type;       //setting the property
 }
        private StringWithQualityHeaderValue(StringWithQualityHeaderValue source)
        {
            Contract.Requires(source != null);

            _value = source._value;
            _quality = source._quality;
        }
      /// <summary>
      /// Processes IfcSite attributes.
      /// </summary>
      /// <param name="ifcIFCSite">The IfcSite handle.</param>
      protected override void Process(IFCAnyHandle ifcIFCSite)
      {
         base.Process(ifcIFCSite);

         RefElevation = IFCImportHandleUtil.GetOptionalScaledLengthAttribute(ifcIFCSite, "RefElevation", 0.0);

         IList<int> refLatitudeList = IFCAnyHandleUtil.GetAggregateIntAttribute<List<int>>(ifcIFCSite, "RefLatitude");
         IList<int> refLongitudeList = IFCAnyHandleUtil.GetAggregateIntAttribute<List<int>>(ifcIFCSite, "RefLongitude");

         if (refLatitudeList != null)
         {
            m_RefLatitude = 0.0;
            int numLats = Math.Min(refLatitudeList.Count, 4);   // Only support up to degress, minutes, seconds, and millionths of seconds.
            for (int ii = 0; ii < numLats; ii++)
            {
               m_RefLatitude += ((double)refLatitudeList[ii]) / GetLatLongScale(ii);
            }
         }

         if (refLongitudeList != null)
         {
            m_RefLongitude = 0.0;
            int numLongs = Math.Min(refLongitudeList.Count, 4);   // Only support up to degress, minutes, seconds, and millionths of seconds.
            for (int ii = 0; ii < numLongs; ii++)
            {
               m_RefLongitude += ((double)refLongitudeList[ii]) / GetLatLongScale(ii);
            }
         }

         m_LandTitleNumber = IFCAnyHandleUtil.GetStringAttribute(ifcIFCSite, "LandTitleNumber");
      }
Exemple #13
0
 public Battery(string model)
 {
     this.Model = model;     //setting the property
     this.hoursIdle = null;  //setting the field
     this.hoursTalk = null;  //setting the field
     this.type = null;       //setting the field
 }
        public void Calculate()
        {
            if (_done) return;

            Sum = null; Min = null; Max = null;
            DateSum = null;
            DateMin = null; DateMax = null;

            foreach (var cell in Cells)
            {
                if (Element.IsNumeric)
                {
                    if (cell.DoubleValue != null)
                    {
                        if (Sum == null) Sum = 0;
                        if (Min == null) Min = cell.DoubleValue;
                        if (Max == null) Max = cell.DoubleValue;

                        Sum += cell.DoubleValue;
                        if (cell.DoubleValue < Min) Min = cell.DoubleValue;
                        if (cell.DoubleValue > Max) Max = cell.DoubleValue;
                    }
                }

                if (Element.IsDateTime)
                {
                    if (cell.DateTimeValue != null)
                    {
                        //Uses ticks/kTickDivider = seconds for calculations
                        if (DateSum == null) DateSum = cell.DateTimeValue.Value.Ticks / kTickDivider;
                        else DateSum += cell.DateTimeValue.Value.Ticks / kTickDivider;

                        if (DateMin == null) DateMin = cell.DateTimeValue;
                        if (DateMax == null) DateMax = cell.DateTimeValue;

                        if (cell.DateTimeValue < DateMin) DateMin = cell.DateTimeValue;
                        if (cell.DateTimeValue > DateMax) DateMax = cell.DateTimeValue;
                    }
                }
            }

            //Total of totals for a count -> we make the sum
            if (!IsSerie && Element.TotalAggregateFunction == AggregateFunction.Count) Value = IsTotalTotal ? Sum : Cells.Count;

            if (Cells.Count > 0)
            {
                AggregateFunction aggregatFunction = IsSerie ? Element.AggregateFunction : Element.TotalAggregateFunction;
                if (IsSerie && aggregatFunction == AggregateFunction.Count) Value = Sum; //Count aggregat for a serie -> we make the sum
                else if (IsTotalTotal && Element.AggregateFunction == AggregateFunction.Count && Element.TotalAggregateFunction == AggregateFunction.Sum) Value = Sum; //Count aggregat for totals -> we use the sum
                else if (Sum != null && Element.IsNumeric && aggregatFunction == AggregateFunction.Sum) Value = Sum;
                else if (Min != null && Element.IsNumeric && aggregatFunction == AggregateFunction.Min) Value = Min;
                else if (Max != null && Element.IsNumeric && aggregatFunction == AggregateFunction.Max) Value = Max;
                else if (Sum != null && Element.IsNumeric && aggregatFunction == AggregateFunction.Avg) Value = Sum / Cells.Count;
                else if (DateMin != null && Element.IsDateTime && aggregatFunction == AggregateFunction.Min) Value = DateMin;
                else if (DateMax != null && Element.IsDateTime && aggregatFunction == AggregateFunction.Max) Value = DateMax;
                else if (DateSum != null && Element.IsDateTime && aggregatFunction == AggregateFunction.Avg) Value = new DateTime((long)(DateSum.Value * kTickDivider / Cells.Count));
            }

            _done = true;
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="sampleCount">Number of samples used in this mean filter.</param>
 public MyAverageFiltering(int sampleCount)
 {
     Debug.Assert(sampleCount > 0);
     m_sampleMaxCount = sampleCount;
     m_samples = new List<double>(sampleCount);
     m_cachedFilteredValue = null;
 }
        public Task OpenAsync(PartitionContext context)
        {
            /*client = new HttpClient();
            client.DefaultRequestHeaders.Add("X-ZUMO-APPLICATION", APP_KEY_MOBILE_SERVICES);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            return Task.FromResult<object>(null);*/

            var storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
            var tableClient = storageAccount.CreateCloudTableClient();
            sensorLogTable = tableClient.GetTableReference("SensorLog");
            //sensorLogTable = tableClient.GetTableReference("SensorLog" + context.Lease.PartitionId);

            // 閾値の取得
            if (thresholdTempWarning == null)
            {
                var sensorConfigTable = tableClient.GetTableReference("SensorConfig");
                var query = new TableQuery<SensorConfig>();
                var configData = sensorConfigTable.ExecuteQuery(query);
                foreach (SensorConfig config in configData)
                {
                    if (config.PartitionKey == "TemperatureWarning")
                    {
                        thresholdTempWarning = config.Threshold;
                        System.Console.WriteLine("ThresholdTempWarning: " + thresholdTempWarning);
                    }
                    else if (config.PartitionKey == "TemperatureDanger")
                    {
                        thresholdTempDanger = config.Threshold;
                        System.Console.WriteLine("ThresholdTempDanger: " + thresholdTempDanger);
                    }
                }
            }

            return sensorLogTable.CreateIfNotExistsAsync();
        }
        public void AddNullableDoubleTest() {
            var leftSequence = new double?[] { 1, 2, 3, 4, 5 };
            var rightSequence = new double?[] { 1, 2, 3, 4, 5 };
            var expected = new double?[] { 2, 4, 6, 8, 10 };

            var actual = LinqTool.Add(leftSequence, rightSequence);
            Assert.IsTrue(expected.SequenceEqual(actual));

            //------------------------------//

            leftSequence = new double?[] { 1, 2, 3, double.NaN, double.PositiveInfinity };
            rightSequence = new double?[] { 1, 2, 3, 4, 5 };
            expected = new double?[] { 2, 4, 6, double.NaN, double.PositiveInfinity };

            actual = LinqTool.Add(leftSequence, rightSequence);
            Assert.IsTrue(expected.SequenceEqual(actual));

            //------------------------------//

            leftSequence = new double?[] { 1, null, 3, double.NaN, double.PositiveInfinity };
            rightSequence = new double?[] { 1, 2, 3, 4, 5 };
            expected = new double?[] { 2, null, 6, double.NaN, double.PositiveInfinity };

            actual = LinqTool.Add(leftSequence, rightSequence);
            Assert.IsTrue(expected.SequenceEqual(actual));
        }
Exemple #18
0
 public void Update()
 {
     var dotProduct = Inputs.Select(kvp => kvp.Value)
         .Sum(synapse => synapse.Input.GetValue()*synapse.Weight);
     double output = _activationFunction.Activate(dotProduct);
     _cachedOutput = output;
 }
Exemple #19
0
    public static ExpressionMatrix ReadMatrix(this TCGATechnologyType ttt, TCGADataType tdt, List<BarInfo> bis, List<string> genes)
    {
      double?[,] data = new double?[genes.Count, bis.Count];
      for (int i = 0; i < bis.Count; i++)
      {
        var reader = ttt.GetTechnology().GetReader();
        var fn = tdt == TCGADataType.Count ? ttt.GetTechnology().GetCountFilename(bis[i].FileName) : bis[i].FileName;
        var dd = reader.ReadFromFile(fn).Values.ToDictionary(m => m.Name, m => m.Value);
        for (int j = 0; j < genes.Count; j++)
        {
          if (dd.ContainsKey(genes[j]))
          {
            data[j, i] = dd[genes[j]];
          }
          else
          {
            data[j, i] = null;
          }
        }
      }

      ExpressionMatrix result = new ExpressionMatrix();
      result.Values = data;
      result.Rownames = genes.ToArray();
      result.Colnames = bis.ConvertAll(m => m.BarCode).ToArray();
      return result;
    }
Exemple #20
0
 public Mercadoria(string referência, byte dígito, Tabela tabela)
 {
     campos = new MercadoriaCamposLeve(referência, dígito, null, null, null);
     this.referencia = campos.ReferênciaNumérica;
     this.peso = campos.PesoOriginal;
     this.tabela = tabela;
 }
Exemple #21
0
        private double? offsetX; // Not for horizontals

        private Line(double? slope, ICartesianCoordinate point)
        {
            this.slope = slope;

            offsetX = slope.HasValue ? (slope.Value.Equals(0.0) ? (double?) null : point.X - point.Y / slope.Value) : point.X;
            offsetY = slope.HasValue ? point.Y - slope.Value * point.X : (double?)null;
        }
        public void CumulativeStdevNullableDoubleTest() {
            IEnumerable<double?> source;
            IEnumerable<double?> expected;
            IEnumerable<double?> actual;

            source = new double?[] { 1, 2, 3, 4, null, 6, 7, 8, 9, double.NaN, 11 };
            expected = new double?[] { .707, 1, 1.291, 1.291, 1.924, 2.317, 2.637, 2.928, double.NaN, double.NaN };

            actual = source.CumulativeStDev().Select(V => V.Value).Round(3).Cast<double?>();
            Assert.IsTrue(expected.SequenceEqual(actual));

            //------------------------------//

            try {
                source = new double?[] { 9 };
                int x = source.CumulativeStDev().Count();
                Assert.Fail();
            }
            catch(ArgumentException e) {
                Assert.IsTrue(e.ParamName == "source");
            }
            catch(InvalidOperationException) {}
            catch(Exception) {
                Assert.Fail();
            }

            //------------------------------//

            source = new double?[] { null, null, null, 4, 5, null, 7, 8, 9, 10, 11 };
            expected = new double?[] { double.NaN, double.NaN, double.NaN, 0.707, 0.707, 1.528, 1.826, 2.074, 2.317, 2.563 };

            actual = source.CumulativeStDev().Select(V => V.Value).Round(3).Cast<double?>();
            Assert.IsTrue(expected.SequenceEqual(actual));
        }
Exemple #23
0
        public void ParseStream(StreamReader reader)
        {
            _length = null; // basically an 'isDirty' flag

            //this is a 'trigram' model so just hard code first two characters
            if (reader.EndOfStream) return; // too short == no trigrams
            char first = (char)reader.Read();

            if (reader.EndOfStream) return;
            char second = (char)reader.Read(); // too short == no trigrams

            while (!reader.EndOfStream)
            {
                char third = (char)reader.Read();

                // wishin' this were python about now ;-)
                // ..initialize data structures if needed
                if (!_trigramModel.ContainsKey(first))
                    _trigramModel.Add(first, new SortedList<char, SortedList<char, long>>());
                if (!_trigramModel[first].ContainsKey(second))
                    _trigramModel[first].Add(second, new SortedList<char, long>());

                // ...increment, or initialize count for this trigram
                if (!_trigramModel[first][second].ContainsKey(third))
                    _trigramModel[first][second].Add(third, 1);
                else
                    _trigramModel[first][second][third]++;

                // .. cycle through characters
                first = second;
                second = third;
            }
        }
        public async Task<double> GetDistanceInCmAsync(int timeoutInMilliseconds)
        {
            _distance = null;
            try
            {
                _stopwatch.Reset();

                // turn on the pulse
                _gpioPinTrig.Write(GpioPinValue.High);
                await Task.Delay(TimeSpan.FromMilliseconds(10));
                _gpioPinTrig.Write(GpioPinValue.Low);

                _stopwatch.Start();
                for (var i = 0; i < timeoutInMilliseconds / 100; i++)
                {
                    if (_distance.HasValue)
                        return _distance.Value;

                    await Task.Delay(TimeSpan.FromMilliseconds(100));
                }
            }
            finally
            {
                _stopwatch.Stop();
            }
            return double.MaxValue;
        }
 private KnnMultiDimensional(INeighbour[] population, int dimensions)
     : base(population)
 {
     _vectorDimensions = population[0].KnnVectors[0].Length;
     _vectorMins = new double?[_vectorDimensions];
     _vectorMaxs = new double?[_vectorDimensions];
 }
Exemple #26
0
        /// <inheritdoc />
        public void Calculate(State state)
        {
			if (state.StateValues.ContainsKey(StateValue.CourseOverGroundDirection))
            {
				var cogRads = AngleUtilities.DegreestoRadians(state.StateValues[StateValue.CourseOverGroundDirection]);

				//make sure whe're not in an "exclusion" aka a few seconds before/after a known tack
				if (!_lastTackAt.HasValue || (_lastTackAt.Value + _dataExclusionTime < state.BestTime)) {
					if (!_currentTackStartCourseOverGroundRadians.HasValue) {
						_currentTackStartCourseOverGroundRadians = cogRads;
					}
					_history.Add (new CourseHistory () { Time = state.BestTime, CourseOverGroundRadians = cogRads });

					//make sure we have enough data to do the calculation accurately
					if (_history.Count > 1) {
						if (_history.Max (x => x.Time) - _history.Min (x => x.Time) > _tackThresholdTime) {
							CheckForTack (state);
						}
					}
				} 

                //calculate the delta on the current tack
				if (state.StateValues.ContainsKey(StateValue.CourseOverGroundDirection) && _currentTackStartCourseOverGroundRadians.HasValue)
                {
                    var delta = AngleUtilities.AngleDifference(cogRads, _currentTackStartCourseOverGroundRadians.Value);
					state.StateValues[StateValue.CurrentTackCourseOverGroundDelta] = AngleUtilities.RadiansToDegrees(delta);
                }
            }

            PurgeOldHistory();
        }
 public GenericObjectMeasureInfo()
 {
     double? nullable = null;
     this.sum = nullable;
     this.average = this.sum = nullable;
     this.max = this.min = null;
 }
Exemple #28
0
 internal V_SF(SeamlessViewsContext Context, SF SF)
     : base(Context)
 {
     _SFKEY = SF.SFKEY;
     _SURNAME = SF.SURNAME;
     _FIRST_NAME = SF.FIRST_NAME;
     _SECOND_NAME = SF.SECOND_NAME;
     _PREF_NAME = SF.PREF_NAME;
     _TITLE = SF.TITLE;
     _FACULTY01 = SF.FACULTY01;
     _FACULTY02 = SF.FACULTY02;
     _FACULTY03 = SF.FACULTY03;
     _FACULTY04 = SF.FACULTY04;
     _SUBJECT01 = SF.SUBJECT01;
     _SUBJECT02 = SF.SUBJECT02;
     _SUBJECT03 = SF.SUBJECT03;
     _SUBJECT04 = SF.SUBJECT04;
     _SUBJECT05 = SF.SUBJECT05;
     _SUBJECT06 = SF.SUBJECT06;
     _SUBJECT07 = SF.SUBJECT07;
     _SUBJECT08 = SF.SUBJECT08;
     _SUBJECT09 = SF.SUBJECT09;
     _SUBJECT10 = SF.SUBJECT10;
     _FTE = SF.FTE;
     _MAJORA = SF.MAJORA;
     _MAJORB = SF.MAJORB;
     _MAJORC = SF.MAJORC;
     _PAYROLL_CLASS = SF.PAYROLL_CLASS;
     _PAYROLL_REC_NO = SF.PAYROLL_REC_NO;
 }
 public CampaignForDetail(Model.hp_goodinfo model)
 {
     var campaignModel = entity.hp_campaign.First(o => o.goodid == model.id);
     id = model.id;
     title = model.title;
     images = model.images;
     price = campaignModel.price;
     oldprice = model.oldprice;
     favorite = StringHelper.NORMAL;
     address = model.adddetail;
     lng = model.lng.ToString();
     lat = model.lat.ToString();
     tel = campaignModel.tel;
     hostname = campaignModel.host;
     hostdate = campaignModel.hostdate.ToString();
     label = "无此字段";
     begintime = campaignModel.begintime.ToString();
     endtime = campaignModel.endtime.ToString();
     closetime = "无此字段";
     numall = campaignModel.num.ToString();
     numnow = "无此字段";
     summary = "无此字段";
     beforebuy = "无此字段";
     commentnum = commentManager.GetNumOfGoodById(model.id);
     comment = commentManager.GetCommentFirst(model.id);
 }
        private void FitSize() {
            var parent = Parent as FrameworkElement;
            if (parent == null) return;

            if (_originalFontSize == null) {
                _originalFontSize = FontSize;
            }

            var targetWidthSize = FontSize;
            var targetHeightSize = FontSize;

            var maxWidth = double.IsNaN(Width) ? double.IsInfinity(MaxWidth) ? parent.ActualWidth : MaxWidth : Width;
            var maxHeight = double.IsNaN(Height) ? double.IsInfinity(MaxHeight) ? parent.ActualHeight : MaxHeight : Height;


            if (ActualWidth > maxWidth) {
                targetWidthSize = FontSize * (maxWidth / (ActualWidth + _defaultMargin));
            }

            if (ActualHeight > maxHeight) {
                var ratio = maxHeight / ActualHeight;

                // Normalize due to Height miscalculation. We do it step by step repeatedly until the requested height is reached. Once the fontsize is changed, this event is re-raised
                // And the ActualHeight is lowered a bit more until it doesnt enter the enclosing If block.
                ratio = 1 - ratio > 0.04 ? Math.Sqrt(ratio) : ratio;
                targetHeightSize = FontSize * ratio;
            }

            FontSize = Math.Min(targetWidthSize, targetHeightSize);
        }
 /// <inheritdoc cref="ReactiveEnergy.FromMegavoltampereReactiveHours(double?)"/>
 public static ReactiveEnergy?MegavoltampereReactiveHours(this double?value) => ReactiveEnergy.FromMegavoltampereReactiveHours(value);
 void IView.SetVScroll(double?value)
 {
     VertScroller.Enabled        = value.HasValue;
     VertScroller.KnobProportion = 0.0001f;
     VertScroller.DoubleValue    = value.GetValueOrDefault();
 }
Exemple #33
0
 public ChromatogramSet ChangeAnalyteConcentration(double?concentration)
 {
     return(ChangeProp(ImClone(this), im => im.AnalyteConcentration = concentration));
 }
        private ResponseClass DeserializeEditItem(Guid sessionID, Guid storeID, Guid itemId, int?amount, double?rank, double?price, string name = null, string categories = null, string keyWords = null)
        {
            string        json     = marketFacade.EditItem(sessionID, storeID, itemId, amount, rank, price, name, categories, keyWords);
            ResponseClass response = JsonConvert.DeserializeObject <ResponseClass>(json);

            return(response);
        }
        internal string EditItemError(Guid sessionID, Guid storeID, Guid itemId, int?amount, double?rank, double?price, string name = null, string categories = null, string keyWords = null)
        {
            ResponseClass response = DeserializeEditItem(sessionID, storeID, itemId, amount, rank, price, name, categories, keyWords);

            return(response.Success ? null : response.AnswerOrExceptionJson);
        }
        internal void EditItemSuccess(Guid sessionID, Guid storeID, Guid itemId, int?amount, double?rank, double?price, string name = null, string categories = null, string keyWords = null)
        {
            ResponseClass response = DeserializeEditItem(sessionID, storeID, itemId, amount, rank, price, name, categories, keyWords);

            if (!response.Success)
            {
                throw new ActionOutcomeException();
            }
        }
        private ResponseClass DeserializeSearchItems(Guid sessionID, double?filterItemRank, double?filterMinPrice, double?filterMaxPrice, double?filterStoreRank, string name, string category, string keywords)
        {
            string        jsonAnswer = marketFacade.SearchItems(sessionID, filterItemRank, filterMinPrice, filterMaxPrice, filterStoreRank, name, category, keywords);
            ResponseClass response   = JsonConvert.DeserializeObject <ResponseClass>(jsonAnswer);

            return(response);
        }
Exemple #38
0
    public NeuralNet(int inputSize, int hiddenSize, int outputSize, int numHiddenLayers = 1, double?learnRate = null, double?momentum = null)
    {
        LearnRate    = learnRate ?? .4;
        Momentum     = momentum ?? .9;
        InputLayer   = new List <Neuron>();
        HiddenLayers = new List <List <Neuron> >();
        OutputLayer  = new List <Neuron>();

        for (var i = 0; i < inputSize; i++)
        {
            InputLayer.Add(new Neuron());
        }

        for (int i = 0; i < numHiddenLayers; i++)
        {
            HiddenLayers.Add(new List <Neuron>());
            for (var j = 0; j < hiddenSize; j++)
            {
                HiddenLayers[i].Add(new Neuron(i == 0 ? InputLayer : HiddenLayers[i - 1]));
            }
        }

        for (var i = 0; i < outputSize; i++)
        {
            OutputLayer.Add(new Neuron(HiddenLayers[numHiddenLayers - 1]));
        }
    }
Exemple #39
0
        private Mock <IAircraft> CreateAircraft(int icao = 0x400f86, double?latitude = 51.1, double?longitude = -0.6)
        {
            var result = TestUtilities.CreateMockInstance <IAircraft>();

            result.SetupGet(r => r.UniqueId).Returns(icao);
            result.SetupGet(r => r.Icao24).Returns(icao.ToString("X6"));
            result.SetupGet(r => r.Latitude).Returns(latitude);
            result.SetupGet(r => r.Longitude).Returns(longitude);

            return(result);
        }
        public static TView Font <TView>(this TView view, double?fontSize = null, bool?bold = null, bool?italic = null, string family = null) where TView : View
        {
            var attributes = bold == true ? FontAttributes.Bold :
                             italic == true ? FontAttributes.Italic :
                             bold.HasValue || italic.HasValue ? FontAttributes.None :
                             (FontAttributes?)null;

            switch (view)
            {
            case Button button: if (fontSize.HasValue)
                {
                    button.FontSize = fontSize.Value;
                }
                if (attributes.HasValue)
                {
                    button.FontAttributes = attributes.Value;
                }
                if (family != null)
                {
                    button.FontFamily = family;
                }
                break;

            case Label label: if (fontSize.HasValue)
                {
                    label.FontSize = fontSize.Value;
                }
                if (attributes.HasValue)
                {
                    label.FontAttributes = attributes.Value;
                }
                if (family != null)
                {
                    label.FontFamily = family;
                }
                break;

            case Entry entry: if (fontSize.HasValue)
                {
                    entry.FontSize = fontSize.Value;
                }
                if (attributes.HasValue)
                {
                    entry.FontAttributes = attributes.Value;
                }
                if (family != null)
                {
                    entry.FontFamily = family;
                }
                break;

            case Picker picker: if (fontSize.HasValue)
                {
                    picker.FontSize = fontSize.Value;
                }
                if (attributes.HasValue)
                {
                    picker.FontAttributes = attributes.Value;
                }
                if (family != null)
                {
                    picker.FontFamily = family;
                }
                break;
            }
            return(view);
        }
Exemple #41
0
        public static WaypointGenerator Create(ConfigNode configNode, WaypointGeneratorFactory factory)
        {
            WaypointGenerator wpGenerator = new WaypointGenerator();

            // Waypoint Manager integration
            EventData <string> onWaypointIconAdded = GameEvents.FindEvent <EventData <string> >("OnWaypointIconAdded");

            bool valid = true;
            int  index = 0;

            foreach (ConfigNode child in ConfigNodeUtil.GetChildNodes(configNode))
            {
                DataNode dataNode = new DataNode("WAYPOINT_" + index, factory.dataNode, factory);
                try
                {
                    ConfigNodeUtil.SetCurrentDataNode(dataNode);
                    dataNode["type"] = child.name;

                    double?      altitude = null;
                    WaypointData wpData   = new WaypointData(child.name);

                    // Use an expression to default - then it'll work for dynamic contracts
                    if (!child.HasValue("targetBody"))
                    {
                        child.AddValue("targetBody", "@/targetBody");
                    }
                    valid &= ConfigNodeUtil.ParseValue <CelestialBody>(child, "targetBody", x => wpData.waypoint.celestialName = x != null ? x.name : "", factory);

                    valid &= ConfigNodeUtil.ParseValue <List <string> >(child, "name", x => wpData.names = x, factory, new List <string>());
                    valid &= ConfigNodeUtil.ParseValue <double?>(child, "altitude", x => altitude = x, factory, (double?)null);
                    valid &= ConfigNodeUtil.ParseValue <List <string> >(child, "parameter", x => wpData.parameter = x, factory, new List <string>());
                    valid &= ConfigNodeUtil.ParseValue <bool>(child, "hidden", x => wpData.waypoint.visible = !x, factory, false);

                    Action <string> assignWaypoint = (x) =>
                    {
                        wpData.waypoint.id = x;
                        if (onWaypointIconAdded != null)
                        {
                            onWaypointIconAdded.Fire(x);
                        }
                    };
                    if (!wpData.waypoint.visible)
                    {
                        valid &= ConfigNodeUtil.ParseValue <string>(child, "icon", assignWaypoint, factory, "");
                    }
                    else
                    {
                        valid &= ConfigNodeUtil.ParseValue <string>(child, "icon", assignWaypoint, factory);
                    }

                    valid &= ConfigNodeUtil.ParseValue <bool>(child, "underwater", x => wpData.underwater = x, factory, false);
                    valid &= ConfigNodeUtil.ParseValue <bool>(child, "clustered", x => wpData.waypoint.isClustered = x, factory, false);

                    // Track the index
                    wpData.waypoint.index = index++;

                    // Get altitude
                    if (altitude == null)
                    {
                        wpData.waypoint.altitude = 0.0;
                        wpData.randomAltitude    = true;
                    }
                    else
                    {
                        wpData.waypoint.altitude = altitude.Value;
                    }

                    // Get settings that differ by type
                    if (child.name == "WAYPOINT")
                    {
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "latitude", x => wpData.waypoint.latitude = x, factory);
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "longitude", x => wpData.waypoint.longitude = x, factory);
                    }
                    else if (child.name == "RANDOM_WAYPOINT")
                    {
                        // Get settings for randomization
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "waterAllowed", x => wpData.waterAllowed = x, factory, true);
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "forceEquatorial", x => wpData.forceEquatorial = x, factory, false);
                        valid &= ConfigNodeUtil.ParseValue <int>(child, "count", x => wpData.count = x, factory, 1, x => Validation.GE(x, 1));
                    }
                    else if (child.name == "RANDOM_WAYPOINT_NEAR")
                    {
                        // Get settings for randomization
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "waterAllowed", x => wpData.waterAllowed = x, factory, true);

                        // Get near waypoint details
                        valid &= ConfigNodeUtil.ParseValue <int>(child, "nearIndex", x => wpData.nearIndex = x, factory,
                                                                 x => Validation.GE(x, 0) && Validation.LT(x, wpGenerator.waypoints.Count));
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "chained", x => wpData.chained = x, factory, false);
                        valid &= ConfigNodeUtil.ParseValue <int>(child, "count", x => wpData.count = x, factory, 1, x => Validation.GE(x, 1));

                        // Get distances
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "minDistance", x => wpData.minDistance = x, factory, 0.0, x => Validation.GE(x, 0.0));
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "maxDistance", x => wpData.maxDistance = x, factory, x => Validation.GT(x, 0.0));
                    }
                    else if (child.name == "PQS_CITY")
                    {
                        wpData.randomAltitude = false;
                        valid &= ConfigNodeUtil.ParseValue <string>(child, "pqsCity", x => {}, factory, x =>
                        {
                            bool v = true;
                            if (!string.IsNullOrEmpty(wpData.waypoint.celestialName))
                            {
                                try
                                {
                                    CelestialBody body = FlightGlobals.Bodies.Where(b => b.name == wpData.waypoint.celestialName).First();
                                    wpData.pqsCity     = body.GetComponentsInChildren <PQSCity>(true).Where(pqs => pqs.name == x).First();
                                }
                                catch (Exception e)
                                {
                                    LoggingUtil.LogError(typeof(WaypointGenerator), "Couldn't load PQSCity with name '" + x + "'");
                                    LoggingUtil.LogException(e);
                                    v = false;
                                }
                            }
                            else
                            {
                                // Force this to get re-run when the targetBody is loaded
                                throw new DataNode.ValueNotInitialized("/targetBody");
                            }
                            return(v);
                        });
                        valid &= ConfigNodeUtil.ParseValue <Vector3d>(child, "pqsOffset", x => wpData.pqsOffset = x, factory, new Vector3d());
                    }
                    else
                    {
                        LoggingUtil.LogError(factory, "Unrecognized waypoint node: '" + child.name + "'");
                        valid = false;
                    }

                    // Check for unexpected values
                    valid &= ConfigNodeUtil.ValidateUnexpectedValues(child, factory);

                    // Copy waypoint data
                    WaypointData old = wpData;
                    for (int i = 0; i < old.count; i++)
                    {
                        wpData = new WaypointData(old, null);
                        wpGenerator.waypoints.Add(wpData);

                        if (old.parameter.Any())
                        {
                            wpData.parameter = new List <string>();
                            wpData.parameter.Add(old.parameter.Count() == 1 ? old.parameter.First() : old.parameter.ElementAtOrDefault(i));
                        }

                        // Set the name
                        if (old.names.Any())
                        {
                            wpData.waypoint.name = (old.names.Count() == 1 ? old.names.First() : old.names.ElementAtOrDefault(i));
                        }
                        if (string.IsNullOrEmpty(wpData.waypoint.name) || wpData.waypoint.name.ToLower() == "site")
                        {
                            wpData.waypoint.name = StringUtilities.GenerateSiteName(random.Next(), wpData.waypoint.celestialBody, !wpData.waterAllowed);
                        }

                        // Handle waypoint chaining
                        if (wpData.chained && i != 0)
                        {
                            wpData.nearIndex = wpGenerator.waypoints.Count - 2;
                        }
                    }
                }
                finally
                {
                    ConfigNodeUtil.SetCurrentDataNode(factory.dataNode);
                }
            }

            return(valid ? wpGenerator : null);
        }
        public override HitObject Parse(string text)
        {
            string[] split = text.Split(',');

            Vector2 pos = new Vector2((int)Parsing.ParseFloat(split[0], Parsing.MAX_COORDINATE_VALUE), (int)Parsing.ParseFloat(split[1], Parsing.MAX_COORDINATE_VALUE));

            double startTime = Parsing.ParseDouble(split[2]) + Offset;

            ConvertHitObjectType type = (ConvertHitObjectType)Parsing.ParseInt(split[3]);

            int comboOffset = (int)(type & ConvertHitObjectType.ComboOffset) >> 4;

            type &= ~ConvertHitObjectType.ComboOffset;

            bool combo = type.HasFlag(ConvertHitObjectType.NewCombo);

            type &= ~ConvertHitObjectType.NewCombo;

            var soundType = (LegacySoundType)Parsing.ParseInt(split[4]);
            var bankInfo  = new SampleBankInfo();

            HitObject result = null;

            if (type.HasFlag(ConvertHitObjectType.Circle))
            {
                result = CreateHit(pos, combo, comboOffset);

                if (split.Length > 5)
                {
                    readCustomSampleBanks(split[5], bankInfo);
                }
            }
            else if (type.HasFlag(ConvertHitObjectType.Slider))
            {
                PathType pathType = PathType.Catmull;
                double?  length   = null;

                string[] pointSplit = split[5].Split('|');

                int pointCount = 1;

                foreach (var t in pointSplit)
                {
                    if (t.Length > 1)
                    {
                        pointCount++;
                    }
                }

                var points = new Vector2[pointCount];

                int pointIndex = 1;

                foreach (string t in pointSplit)
                {
                    if (t.Length == 1)
                    {
                        switch (t)
                        {
                        case @"C":
                            pathType = PathType.Catmull;
                            break;

                        case @"B":
                            pathType = PathType.Bezier;
                            break;

                        case @"L":
                            pathType = PathType.Linear;
                            break;

                        case @"P":
                            pathType = PathType.PerfectCurve;
                            break;
                        }

                        continue;
                    }

                    string[] temp = t.Split(':');
                    points[pointIndex++] = new Vector2((int)Parsing.ParseDouble(temp[0], Parsing.MAX_COORDINATE_VALUE), (int)Parsing.ParseDouble(temp[1], Parsing.MAX_COORDINATE_VALUE)) - pos;
                }

                int repeatCount = Parsing.ParseInt(split[6]);

                if (repeatCount > 9000)
                {
                    throw new ArgumentOutOfRangeException(nameof(repeatCount), @"Repeat count is way too high");
                }

                // osu-stable treated the first span of the slider as a repeat, but no repeats are happening
                repeatCount = Math.Max(0, repeatCount - 1);

                if (split.Length > 7)
                {
                    length = Math.Max(0, Parsing.ParseDouble(split[7]));
                    if (length == 0)
                    {
                        length = null;
                    }
                }

                if (split.Length > 10)
                {
                    readCustomSampleBanks(split[10], bankInfo);
                }

                // One node for each repeat + the start and end nodes
                int nodes = repeatCount + 2;

                // Populate node sample bank infos with the default hit object sample bank
                var nodeBankInfos = new List <SampleBankInfo>();
                for (int i = 0; i < nodes; i++)
                {
                    nodeBankInfos.Add(bankInfo.Clone());
                }

                // Read any per-node sample banks
                if (split.Length > 9 && split[9].Length > 0)
                {
                    string[] sets = split[9].Split('|');

                    for (int i = 0; i < nodes; i++)
                    {
                        if (i >= sets.Length)
                        {
                            break;
                        }

                        SampleBankInfo info = nodeBankInfos[i];
                        readCustomSampleBanks(sets[i], info);
                    }
                }

                // Populate node sound types with the default hit object sound type
                var nodeSoundTypes = new List <LegacySoundType>();
                for (int i = 0; i < nodes; i++)
                {
                    nodeSoundTypes.Add(soundType);
                }

                // Read any per-node sound types
                if (split.Length > 8 && split[8].Length > 0)
                {
                    string[] adds = split[8].Split('|');

                    for (int i = 0; i < nodes; i++)
                    {
                        if (i >= adds.Length)
                        {
                            break;
                        }

                        int.TryParse(adds[i], out var sound);
                        nodeSoundTypes[i] = (LegacySoundType)sound;
                    }
                }

                // Generate the final per-node samples
                var nodeSamples = new List <IList <HitSampleInfo> >(nodes);
                for (int i = 0; i < nodes; i++)
                {
                    nodeSamples.Add(convertSoundType(nodeSoundTypes[i], nodeBankInfos[i]));
                }

                result = CreateSlider(pos, combo, comboOffset, convertControlPoints(points, pathType), length, repeatCount, nodeSamples);

                // The samples are played when the slider ends, which is the last node
                result.Samples = nodeSamples[nodeSamples.Count - 1];
            }
            else if (type.HasFlag(ConvertHitObjectType.Spinner))
            {
                double endTime = Math.Max(startTime, Parsing.ParseDouble(split[5]) + Offset);

                result = CreateSpinner(new Vector2(512, 384) / 2, combo, comboOffset, endTime);

                if (split.Length > 6)
                {
                    readCustomSampleBanks(split[6], bankInfo);
                }
            }
            else if (type.HasFlag(ConvertHitObjectType.Hold))
            {
                // Note: Hold is generated by BMS converts

                double endTime = Math.Max(startTime, Parsing.ParseDouble(split[2]));

                if (split.Length > 5 && !string.IsNullOrEmpty(split[5]))
                {
                    string[] ss = split[5].Split(':');
                    endTime = Math.Max(startTime, Parsing.ParseDouble(ss[0]));
                    readCustomSampleBanks(string.Join(":", ss.Skip(1)), bankInfo);
                }

                result = CreateHold(pos, combo, comboOffset, endTime + Offset);
            }

            if (result == null)
            {
                throw new InvalidDataException($"Unknown hit object type: {split[3]}");
            }

            result.StartTime = startTime;

            if (result.Samples.Count == 0)
            {
                result.Samples = convertSoundType(soundType, bankInfo);
            }

            FirstObject = false;

            return(result);
        }
Exemple #43
0
 /// <summary>
 /// 获取格式化字符串
 /// </summary>
 /// <param name="number">数值</param>
 /// <param name="defaultValue">空值显示的默认文本</param>
 public static string Format(this double?number, string defaultValue = "")
 {
     return(Format(number.SafeValue(), defaultValue));
 }
Exemple #44
0
            /// <summary>
            /// Конструктор нормального распределения по умолчанию
            /// </summary>
            public ConRandVal()
            {
                ConRandVal T = new ConRandVal(BasisDistribution.Normal, 0, 1);

                this.f = T.f; this.m = T.m; this.d = T.d;
            }
Exemple #45
0
 /// <summary>
 /// Creates a new <see cref="EntityProperty"/> object that represents the specified <see cref="Double"/> value.
 /// </summary>
 /// <param name="input">The value for the new <see cref="EntityProperty"/>.</param>
 /// <returns>A new <see cref="EntityProperty"/> of the <see cref="Double"/> type.</returns>
 public static EntityProperty GeneratePropertyForDouble(double?input)
 {
     return(new EntityProperty(input));
 }
Exemple #46
0
        public Network(int inputSize, int[] hiddenSizes, int outputSize, double?learnRate = null, double?momentum = null)
        {
            LearnRate    = learnRate ?? .9;
            Momentum     = momentum ?? .9;
            InputLayer   = new List <Neuron>();
            HiddenLayers = new List <List <Neuron> >();
            OutputLayer  = new List <Neuron>();

            for (var i = 0; i < inputSize; i++)
            {
                InputLayer.Add(new Neuron());
            }

            var firstHiddenLayer = new List <Neuron>();

            for (var i = 0; i < hiddenSizes[0]; i++)
            {
                firstHiddenLayer.Add(new Neuron(InputLayer));
            }

            HiddenLayers.Add(firstHiddenLayer);

            for (var i = 1; i < hiddenSizes.Length; i++)
            {
                var hiddenLayer = new List <Neuron>();
                for (var j = 0; j < hiddenSizes[i]; j++)
                {
                    hiddenLayer.Add(new Neuron(HiddenLayers[i - 1]));
                }
                HiddenLayers.Add(hiddenLayer);
            }

            for (var i = 0; i < outputSize; i++)
            {
                OutputLayer.Add(new Neuron(HiddenLayers.Last()));
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="WasteRegisterPublicApiApiModelsRequestsWasteRegisterMunicipalSewageSludgeCardV1CreateKekosResearchCardRequest" /> class.
 /// </summary>
 /// <param name="batchOfGeneratedSedimentId">Id wpisu wytworzone osady.</param>
 /// <param name="researchNumber">Numer badania.</param>
 /// <param name="researchDate">Data badania.</param>
 /// <param name="phReaction">Odczyn pH.</param>
 /// <param name="dryMatterContent">Zawartość suchej masy [% s.m.].</param>
 /// <param name="contentOfOrganicSubstances">Zawartość substancji organicznych [% s.m.].</param>
 /// <param name="contentOfAmmoniumNitrogen">Zawartość azotu ogólnego [% s.m.].</param>
 /// <param name="contentOfTotalNitrogen">w tym azotu amonowego[% s.m.].</param>
 /// <param name="contentOfTotalPhosphorus">Zawartość fosforu ogólnego [% s.m.].</param>
 /// <param name="calciumContent">Zawartość wapnia [% s.m.].</param>
 /// <param name="magnesiumContent">Zawartość magnezu [% s.m.].</param>
 /// <param name="numberOfParasiticEggs">Łączna liczba żywych jaj pasożytów [liczba/kg s.m osadu].</param>
 /// <param name="salmonellaBacteria">Bakterie z rodzaju Salmonella w 100g osadów przeznaczonych do badań.</param>
 /// <param name="cadmiumContent">Kadm [mg/kg s.m.].</param>
 /// <param name="copperContent">Miedź [mg/kg s.m.].</param>
 /// <param name="leadContent">Ołów [mg/kg s.m.].</param>
 /// <param name="mercuryContent">Rtęć [mg/kg s.m.].</param>
 /// <param name="nickelContent">Nikiel [mg/kg s.m.].</param>
 /// <param name="chromeContent">Chrom [mg/kg s.m.].</param>
 /// <param name="zincContent">Cynk [mg/kg s.m.].</param>
 /// <param name="isSewageSludgeFormLiquid">Postać komunalnych osadów ściekowych: płynna.</param>
 /// <param name="isSewageSludgeFormMazist">Postać komunalnych osadów ściekowych: mazista.</param>
 /// <param name="isSewageSludgeFormEarthy">Postać komunalnych osadów ściekowych: ziemista.</param>
 public WasteRegisterPublicApiApiModelsRequestsWasteRegisterMunicipalSewageSludgeCardV1CreateKekosResearchCardRequest(Guid?batchOfGeneratedSedimentId = default(Guid?), string researchNumber = default(string), DateTime?researchDate = default(DateTime?), double?phReaction = default(double?), double?dryMatterContent = default(double?), double?contentOfOrganicSubstances = default(double?), double?contentOfAmmoniumNitrogen = default(double?), double?contentOfTotalNitrogen = default(double?), double?contentOfTotalPhosphorus = default(double?), double?calciumContent = default(double?), double?magnesiumContent = default(double?), double?numberOfParasiticEggs = default(double?), bool?salmonellaBacteria = default(bool?), double?cadmiumContent = default(double?), double?copperContent = default(double?), double?leadContent = default(double?), double?mercuryContent = default(double?), double?nickelContent = default(double?), double?chromeContent = default(double?), double?zincContent = default(double?), bool?isSewageSludgeFormLiquid = default(bool?), bool?isSewageSludgeFormMazist = default(bool?), bool?isSewageSludgeFormEarthy = default(bool?))
 {
     this.BatchOfGeneratedSedimentId = batchOfGeneratedSedimentId;
     this.ResearchNumber             = researchNumber;
     this.ResearchDate               = researchDate;
     this.PhReaction                 = phReaction;
     this.DryMatterContent           = dryMatterContent;
     this.ContentOfOrganicSubstances = contentOfOrganicSubstances;
     this.ContentOfAmmoniumNitrogen  = contentOfAmmoniumNitrogen;
     this.ContentOfTotalNitrogen     = contentOfTotalNitrogen;
     this.ContentOfTotalPhosphorus   = contentOfTotalPhosphorus;
     this.CalciumContent             = calciumContent;
     this.MagnesiumContent           = magnesiumContent;
     this.NumberOfParasiticEggs      = numberOfParasiticEggs;
     this.SalmonellaBacteria         = salmonellaBacteria;
     this.CadmiumContent             = cadmiumContent;
     this.CopperContent              = copperContent;
     this.LeadContent                = leadContent;
     this.MercuryContent             = mercuryContent;
     this.NickelContent              = nickelContent;
     this.ChromeContent              = chromeContent;
     this.ZincContent                = zincContent;
     this.IsSewageSludgeFormLiquid   = isSewageSludgeFormLiquid;
     this.IsSewageSludgeFormMazist   = isSewageSludgeFormMazist;
     this.IsSewageSludgeFormEarthy   = isSewageSludgeFormEarthy;
 }
Exemple #48
0
 /// <summary>
 /// 获取格式化字符串,带%
 /// </summary>
 /// <param name="number">数值</param>
 public static string FormatPercent(this double?number)
 {
     return(FormatPercent(number.SafeValue()));
 }
Exemple #49
0
        public async static Task ScrollToItem2(this ListViewBase listViewBase, object item, VerticalAlignment alignment, bool highlight, double?pixel = null)
        {
            var scrollViewer = listViewBase.GetScrollViewer();

            if (scrollViewer == null)
            {
                return;
            }

            //listViewBase.SelectionMode = ListViewSelectionMode.Single;
            //listViewBase.SelectedItem = item;

            var selectorItem = listViewBase.ContainerFromItem(item) as SelectorItem;

            if (selectorItem == null)
            {
                // call task-based ScrollIntoViewAsync to realize the item
                await listViewBase.ScrollIntoViewAsync(item);

                // this time the item shouldn't be null again
                selectorItem = (SelectorItem)listViewBase.ContainerFromItem(item);
            }

            if (selectorItem == null)
            {
                return;
            }

            // calculate the position object in order to know how much to scroll to
            var transform = selectorItem.TransformToVisual((UIElement)scrollViewer.Content);
            var position  = transform.TransformPoint(new Point(0, 0));

            if (alignment == VerticalAlignment.Top)
            {
                if (pixel is double adjust)
                {
                    position.Y -= adjust;
                }
            }
            else if (alignment == VerticalAlignment.Center)
            {
                position.Y -= (listViewBase.ActualHeight - selectorItem.ActualHeight) / 2d;
            }
            else if (alignment == VerticalAlignment.Bottom)
            {
                position.Y -= listViewBase.ActualHeight - selectorItem.ActualHeight;

                if (pixel is double adjust)
                {
                    position.Y += adjust;
                }
            }

            // scroll to desired position with animation!
            scrollViewer.ChangeView(position.X, position.Y, null, alignment != VerticalAlignment.Center);

            if (highlight)
            {
                var bubble = selectorItem.Descendants <MessageBubble>().FirstOrDefault() as MessageBubble;
                if (bubble == null)
                {
                    return;
                }

                bubble.Highlight();
            }
        }
Exemple #50
0
 EntityProperty(double?input)
     : this(EdmType.Double)
 {
     this.IsNull           = !input.HasValue;
     this.PropertyAsObject = input;
 }
Exemple #51
0
 public PhraseSuggesterDescriptor <T> MaxErrors(double?maxErrors) => Assign(a => a.MaxErrors = maxErrors);
Exemple #52
0
        public static async Task ChangeViewAsync(this ScrollViewer scrollViewer, double?horizontalOffset, double?verticalOffset, bool disableAnimation)
        {
            var tcs = new TaskCompletionSource <object>();

            EventHandler <object> layoutUpdated = (s1, e1) => tcs.TrySetResult(null);
            EventHandler <ScrollViewerViewChangedEventArgs> viewChanged = (s, e) =>
            {
                scrollViewer.LayoutUpdated += layoutUpdated;
                scrollViewer.UpdateLayout();
            };

            try
            {
                scrollViewer.ViewChanged += viewChanged;
                scrollViewer.ChangeView(horizontalOffset, verticalOffset, null, disableAnimation);
                await tcs.Task;
            }
            finally
            {
                scrollViewer.ViewChanged   -= viewChanged;
                scrollViewer.LayoutUpdated -= layoutUpdated;
            }
        }
Exemple #53
0
 /// <summary>
 /// Creats a legacy Slider-type hit object.
 /// </summary>
 /// <param name="position">The position of the hit object.</param>
 /// <param name="newCombo">Whether the hit object creates a new combo.</param>
 /// <param name="comboOffset">When starting a new combo, the offset of the new combo relative to the current one.</param>
 /// <param name="controlPoints">The slider control points.</param>
 /// <param name="length">The slider length.</param>
 /// <param name="pathType">The slider curve type.</param>
 /// <param name="repeatCount">The slider repeat count.</param>
 /// <param name="nodeSamples">The samples to be played when the slider nodes are hit. This includes the head and tail of the slider.</param>
 /// <returns>The hit object.</returns>
 protected abstract HitObject CreateSlider(Vector2 position, bool newCombo, int comboOffset, Vector2[] controlPoints, double?length, PathType pathType, int repeatCount,
                                           List <IList <HitSampleInfo> > nodeSamples);
Exemple #54
0
 public PhraseSuggesterDescriptor <T> RealWordErrorLikelihood(double?realWordErrorLikelihood) =>
 Assign(a => a.RealWordErrorLikelihood = realWordErrorLikelihood);
Exemple #55
0
        private void AssertEvents(string symbol, double? oldSum, double? oldAvg, double? newSum, double? newAvg)
	    {
	        var oldData = _listener.LastOldData;
	        var newData = _listener.LastNewData;

	        Assert.AreEqual(1, oldData.Length);
	        Assert.AreEqual(1, newData.Length);

	        Assert.AreEqual(symbol, oldData[0].Get("Symbol"));
	        Assert.AreEqual(oldSum, oldData[0].Get("mySum"));
	        Assert.AreEqual(oldAvg, oldData[0].Get("myAvg"));

	        Assert.AreEqual(symbol, newData[0].Get("Symbol"));
	        Assert.AreEqual(newSum, newData[0].Get("mySum"));
            Assert.AreEqual(newAvg, newData[0].Get("myAvg"), "newData myAvg wrong");

	        _listener.Reset();
	        Assert.IsFalse(_listener.IsInvoked);
	    }
Exemple #56
0
 public PhraseSuggesterDescriptor <T> Confidence(double?confidence) => Assign(a => a.Confidence = confidence);
Exemple #57
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OrderBookL2" /> class.
 /// </summary>
 /// <param name="Symbol">Symbol (required).</param>
 /// <param name="Id">Id (required).</param>
 /// <param name="Side">Side (required).</param>
 /// <param name="Size">Size.</param>
 /// <param name="Price">Price.</param>
 public OrderBookL2(string Symbol = null, decimal?Id = null, string Side = null, decimal?Size = null, double?Price = null)
 {
     // to ensure "Symbol" is required (not null)
     if (Symbol == null)
     {
         throw new InvalidDataException("Symbol is a required property for OrderBookL2 and cannot be null");
     }
     else
     {
         this.Symbol = Symbol;
     }
     // to ensure "Id" is required (not null)
     if (Id == null)
     {
         throw new InvalidDataException("Id is a required property for OrderBookL2 and cannot be null");
     }
     else
     {
         this.Id = Id;
     }
     // to ensure "Side" is required (not null)
     if (Side == null)
     {
         throw new InvalidDataException("Side is a required property for OrderBookL2 and cannot be null");
     }
     else
     {
         this.Side = Side;
     }
     this.Size  = Size;
     this.Price = Price;
 }
 private static bool canConvert(this IWithDisplayUnit quantity, double?valueToConvert)
 {
     return(valueToConvert.HasValue && quantity.DisplayUnit != null && quantity.Dimension != null);
 }
 public AnyUiDialogueDataSelectQualifierPreset(
     string caption = "",
     double? maxWidth = null)
     : base(caption, maxWidth)
 {
 }
Exemple #60
0
        /// <summary>
        /// Called for a spell projectile to damage its target
        /// </summary>
        public void DamageTarget(WorldObject _target, double? damage, bool critical, bool critDefended, bool overpower)
        {
            var player = ProjectileSource as Player;

            var target = _target as Creature;
            var targetPlayer = _target as Player;

            if (targetPlayer != null && (targetPlayer.Invincible || targetPlayer.IsDead))
                return;

            uint amount;
            var percent = 0.0f;
            var heritageMod = 1.0f;
            var sneakAttackMod = 1.0f;

            // handle life projectiles for stamina / mana
            if (Spell.Category == SpellCategory.StaminaLowering)
            {
                percent = (float)damage / target.Stamina.MaxValue;
                amount = (uint)-target.UpdateVitalDelta(target.Stamina, (int)-Math.Round(damage.Value));
            }
            else if (Spell.Category == SpellCategory.ManaLowering)
            {
                percent = (float)damage / target.Mana.MaxValue;
                amount = (uint)-target.UpdateVitalDelta(target.Mana, (int)-Math.Round(damage.Value));
            }
            else
            {
                // for possibly applying sneak attack to magic projectiles,
                // only do this for health-damaging projectiles?
                if (player != null)
                {
                    // TODO: use target direction vs. projectile position, instead of player position
                    // could sneak attack be applied to void DoTs?
                    sneakAttackMod = player.GetSneakAttackMod(target);
                    //Console.WriteLine("Magic sneak attack:  + sneakAttackMod);
                    heritageMod = player.GetHeritageBonus(player.GetEquippedWand()) ? 1.05f : 1.0f;
                }

                // DR / DRR applies for magic too?
                var creatureSource = ProjectileSource as Creature;
                var damageRating = creatureSource != null ? creatureSource.GetDamageRating() : 0;
                var damageRatingMod = Creature.AdditiveCombine(Creature.GetPositiveRatingMod(damageRating), heritageMod, sneakAttackMod);
                var damageResistRatingMod = Creature.GetNegativeRatingMod(target.GetDamageResistRating(CombatType.Magic));
                damage *= damageRatingMod * damageResistRatingMod;

                //Console.WriteLine($"Damage rating: " + Creature.ModToRating(damageRatingMod));

                percent = (float)damage / target.Health.MaxValue;
                amount = (uint)-target.UpdateVitalDelta(target.Health, (int)-Math.Round(damage.Value));
                target.DamageHistory.Add(ProjectileSource, Spell.DamageType, amount);

                //if (targetPlayer != null && targetPlayer.Fellowship != null)
                    //targetPlayer.Fellowship.OnVitalUpdate(targetPlayer);
            }

            amount = (uint)Math.Round(damage.Value);    // full amount for debugging

            if (critical)
                target.EmoteManager.OnReceiveCritical(player);

            if (target.IsAlive)
            {
                string verb = null, plural = null;
                Strings.GetAttackVerb(Spell.DamageType, percent, ref verb, ref plural);
                var type = Spell.DamageType.GetName().ToLower();

                var critMsg = critical ? "Critical hit! " : "";
                var sneakMsg = sneakAttackMod > 1.0f ? "Sneak Attack! " : "";
                var overpowerMsg = overpower ? "Overpower! " : "";

                if (player != null)
                {
                    var critProt = critDefended ? " Your target's Critical Protection augmentation allows them to avoid your critical hit!" : "";

                    var attackerMsg = $"{critMsg}{overpowerMsg}{sneakMsg}You {verb} {target.Name} for {amount} points with {Spell.Name}.{critProt}";

                    // could these crit / sneak attack?
                    if (Spell.Category == SpellCategory.StaminaLowering || Spell.Category == SpellCategory.ManaLowering)
                    {
                        var vital = Spell.Category == SpellCategory.StaminaLowering ? "stamina" : "mana";
                        attackerMsg = $"With {Spell.Name} you drain {amount} points of {vital} from {target.Name}.";
                    }

                    if (!player.SquelchManager.Squelches.Contains(target, ChatMessageType.Magic))
                        player.Session.Network.EnqueueSend(new GameMessageSystemChat(attackerMsg, ChatMessageType.Magic));

                    player.Session.Network.EnqueueSend(new GameEventUpdateHealth(player.Session, target.Guid.Full, (float)target.Health.Current / target.Health.MaxValue));
                }

                if (targetPlayer != null)
                {
                    var critProt = critDefended ? " Your Critical Protection augmentation allows you to avoid a critical hit!" : "";

                    var defenderMsg = $"{critMsg}{overpowerMsg}{sneakMsg}{ProjectileSource.Name} {plural} you for {amount} points with {Spell.Name}.{critProt}";

                    if (Spell.Category == SpellCategory.StaminaLowering || Spell.Category == SpellCategory.ManaLowering)
                    {
                        var vital = Spell.Category == SpellCategory.StaminaLowering ? "stamina" : "mana";
                        defenderMsg = $"{ProjectileSource.Name} casts {Spell.Name} and drains {amount} points of your {vital}.";
                    }

                    if (!targetPlayer.SquelchManager.Squelches.Contains(ProjectileSource, ChatMessageType.Magic))
                        targetPlayer.Session.Network.EnqueueSend(new GameMessageSystemChat(defenderMsg, ChatMessageType.Magic));
                }
            }
            else
            {
                var lastDamager = ProjectileSource != null ? new DamageHistoryInfo(ProjectileSource) : null;
                target.OnDeath(lastDamager, Spell.DamageType, critical);
                target.Die();
            }
        }