Пример #1
0
        public void ADD_rr_rr_sets_HF_appropriately(string dest, string src, byte opcode, byte?prefix)
        {
            SetReg(src, 0x10);
            foreach (byte b in new byte[] { 0x0F, 0x7F, 0xFF })
            {
                SetReg(dest, NumberUtils.CreateShort(0xFF, b));

                Execute(opcode, prefix);
                Assert.AreEqual(1, Registers.HF);

                Execute(opcode, prefix);
                Assert.AreEqual(0, Registers.HF);
            }
        }
Пример #2
0
        public static IntegerListModel Create <T>(IReadOnlyList <T> values, Func <T, int> selector)
        {
            var minValue  = values.Min(selector);
            var maxValue  = values.Max(v => selector(v) - minValue);
            var byteWidth = NumberUtils.GetByteWidth(maxValue);
            var list      = new IntegerListModel(byteWidth, values.Count, minValue);

            for (int i = 0; i < values.Count; i++)
            {
                list[i] = selector(values[i]);
            }

            return(list);
        }
        public void GetPositiveDecimal_returns_decimal_greater_than_zero_on_repeated_runs()
        {
            // arrange
            var utils = new NumberUtils();

            // act
            for (var i = 0; i < 100; i++)
            {
                var num = utils.GetPositiveDecimal();
                Console.Out.WriteLine(num);
                // assert
                Assert.Greater(num, 0.0M);
            }
        }
 /// <summary>
 /// Construct an <b>NumberIncrementor</b> processor that will
 /// increment a property value by a specified amount, returning
 /// either the old or the new value as specified.
 /// </summary>
 /// <remarks>
 /// The .NET type of the <paramref name="numInc"/> parameter will
 /// dictate the .NET type of the original and the new value.
 /// </remarks>
 /// <param name="name">
 /// The property name.
 /// </param>
 /// <param name="numInc">
 /// The object representing the magnitude and sign of the increment.
 /// </param>
 /// <param name="postIncrement">
 /// Pass <b>true</b> to return the value as it was before it was
 /// incremented, or pass <b>false</b> to return the value as it is
 /// after it is incremented.
 /// </param>
 public NumberIncrementor(string name, object numInc, bool postIncrement) : base(name)
 {
     if (numInc == null)
     {
         throw new ArgumentNullException("numInc", "Argument 'numInc' cannot be null.");
     }
     if (numInc != null && !NumberUtils.IsNumber(numInc))
     {
         throw new ArgumentException("Bad parameter format! " +
                                     numInc.GetType().Name + " is not supported type.");
     }
     m_numInc  = numInc;
     m_postInc = postIncrement;
 }
        private static CableTrayAndMassIntersectionModel GetIntersection(CableTrayModel CableTrayModel, MassFormModel massFormModel)
        {
            var intersectionsInstance = new CableTrayAndMassIntersectionModel
            {
                CableTray = CableTrayModel,
                MassForm  = massFormModel
            };

            var cableTrayCurveStartPoint = CableTrayModel.StarPoint;
            var cableTrayCurveEndPoint   = CableTrayModel.EndPoint;

            foreach (var massFace in massFormModel.Faces)
            {
                IntersectionResultArray intersectionResultArray = null;
                massFace.Intersect(CableTrayModel.Curve, out intersectionResultArray);
                if (intersectionResultArray == null)
                {
                    continue;
                }
                foreach (IntersectionResult intResult in intersectionResultArray)
                {
                    if (intResult.XYZPoint == null)
                    {
                        continue;
                    }



                    var intersectPoint = intResult.XYZPoint;

                    bool isIntersectPointInRange
                        = NumberUtils.IsInRange(
                              intersectPoint.Z,
                              Math.Min(cableTrayCurveStartPoint.Z, cableTrayCurveStartPoint.Z),
                              Math.Max(cableTrayCurveEndPoint.Z, cableTrayCurveEndPoint.Z));

                    //проверяем находится ли точка на линии
                    if (GeomShark.PointUtils.IsPointBetweenOtherTwoPoints(
                            cableTrayCurveStartPoint.X, cableTrayCurveStartPoint.Y,
                            cableTrayCurveEndPoint.X, cableTrayCurveEndPoint.Y,
                            intersectPoint.X, intersectPoint.Y, 4))
                    {
                        intersectionsInstance.IntersectionPoints.Add(intersectPoint);
                    }
                }
            }

            return((intersectionsInstance.IntersectionPoints.Count > 0) ? intersectionsInstance : null);
        }
Пример #6
0
        /// <summary>
        /// The RETI instruction.
        /// </summary>
        private byte RETI()
        {
            FetchFinished(isRet: true);

            var sp    = (ushort)Registers.SP;
            var newPC = NumberUtils.CreateShort(
                ProcessorAgent.ReadFromMemory(sp),
                ProcessorAgent.ReadFromMemory((ushort)(sp + 1)));

            Registers.PC = (ushort)newPC;

            Registers.SP += 2;

            return(14);
        }
        public void Remove(int index)
        {
            int arrayIndex = NumberUtils.WrapMod(index, _array.Length);

            if (_array[arrayIndex].Index != index)
            {
                throw new ArgumentOutOfRangeException(nameof(index), index, "Cannot remove wrapped index");
            }

            _array[arrayIndex] = new Element()
            {
                Index = -1,
                Value = default(T)
            };
        }
Пример #8
0
        /// <summary>
        /// Returns a value for the arithmetic modulus operator node.
        /// </summary>
        /// <param name="context">Context to evaluate expressions against.</param>
        /// <param name="evalContext">Current expression evaluation context.</param>
        /// <returns>Node's value.</returns>
        protected override object Get(object context, EvaluationContext evalContext)
        {
            var leftVal  = GetLeftValue(context, evalContext);
            var rightVal = GetRightValue(context, evalContext);

            if (NumberUtils.IsNumber(leftVal) && NumberUtils.IsNumber(rightVal))
            {
                return(NumberUtils.Modulus(leftVal, rightVal));
            }
            throw new ArgumentException("Cannot calculate modulus for instances of '"
                                        + leftVal.GetType().FullName
                                        + "' and '"
                                        + rightVal.GetType().FullName
                                        + "'.");
        }
Пример #9
0
        // Problem 2: Even Fibonacci numbers
        // Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
        //
        // 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
        //
        // By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
        /// <summary>
        /// For this problem, we're summing all of the even Fibonacci numbers under a given limit.
        /// I'm using a recursive Fibonacci method.
        /// </summary>
        /// <param name="limit">The ceiling that the Fibonacci sequence will be evaluated up to.</param>
        /// <returns>Returns the sum of all even Fibonacci numbers under the given limit.</returns>
        public int PE0002(int limit = 4000000)
        {
            int  sum = 0, result = 0;
            uint i = 0;

            while ((result = NumberUtils.Fibonacci(i++)) < limit) //we're assigning result the next Fibonacci number in the sequence and keeping track of the sequence with i
            {                                                     //we're looping over the odd Fibonacci numbers
                if (result % 2 != 0)
                {
                    continue;
                }
                sum += result; //add the even Fibonacci number to the running total
            }
            return(sum);
        }
Пример #10
0
        /// <summary>
        /// The POP BC instruction.
        /// </summary>
        private byte POP_BC()
        {
            FetchFinished();

            var sp    = Registers.SP.ToUShort();
            var newBC = NumberUtils.CreateShort(
                ProcessorAgent.ReadFromMemory(sp),
                ProcessorAgent.ReadFromMemory(sp.Inc()));

            Registers.BC = newBC;

            Registers.SP = Registers.SP.Add(2);

            return(10);
        }
Пример #11
0
 public float Parse(string v)
 {
     if (!Exp(v))
     {
         if (NumberUtils.IsNan(v))
         {
             return(float.Parse(v));
         }
         else
         {
             throw new RuntimeException(v + " not parse !");
         }
     }
     return(Eval(v));
 }
Пример #12
0
        /// <summary>
        /// Returns a value for the arithmetic exponent operator node.
        /// </summary>
        /// <param name="context">Context to evaluate expressions against.</param>
        /// <param name="evalContext">Current expression evaluation context.</param>
        /// <returns>Node's value.</returns>
        protected override object Get(object context, EvaluationContext evalContext)
        {
            var lhs = GetLeftValue(context, evalContext);
            var rhs = GetRightValue(context, evalContext);

            if (NumberUtils.IsNumber(lhs) && NumberUtils.IsNumber(rhs))
            {
                return(NumberUtils.Power(lhs, rhs));
            }
            throw new ArgumentException("Cannot calculate exponent for the instances of '"
                                        + lhs.GetType().FullName
                                        + "' and '"
                                        + rhs.GetType().FullName
                                        + "'.");
        }
Пример #13
0
        /// <summary>
        /// The RETI instruction.
        /// </summary>
        private byte RETI()
        {
            FetchFinished(isRet: true);

            var sp    = Registers.SP.ToUShort();
            var newPC = NumberUtils.CreateShort(
                ProcessorAgent.ReadFromMemory(sp),
                ProcessorAgent.ReadFromMemory(sp.Inc()));

            Registers.PC = newPC.ToUShort();

            Registers.SP = Registers.SP.Add(2);

            return(14);
        }
Пример #14
0
        public void IdEncodingDecodingGivesOriginalValues()
        {
            const long input = 10;

            var encoded = NumberUtils.EncodeLongToHexString(input);
            var decoded = NumberUtils.DecodeHexString(encoded);

            Assert.AreEqual(input, decoded);

            const string encodedInput   = "00000000000000AA";
            var          decodedInput   = NumberUtils.DecodeHexString(encodedInput);
            var          reEncodedInput = NumberUtils.EncodeLongToHexString(decodedInput);

            Assert.AreEqual(encodedInput, reEncodedInput);
        }
Пример #15
0
 private void Validate()
 {
     if (Id <= 0)
     {
         throw new InvalidAppException(string.Format("Id must be positive. Found {0}", Id));
     }
     if (NumberUtils.IntLength(Id) > MaxIdLength)
     {
         throw new InvalidAppException(string.Format("Id value is too long. Id must not exceed {0} digits in length. Found {0}", MaxIdLength, Id));
     }
     if (Version <= 0)
     {
         throw new InvalidAppException(string.Format("Version number must be positive. Found {0}", Version));
     }
 }
Пример #16
0
    private void LoadBlockStats(object blockInfo)
    {
        Tuple <double, double> bHealthAndReward = (Tuple <double, double>)blockInfo;
        BlockSpawnData         blockSpawnData   = dataSavingManager.GetBlockSpawnData();

        int bPerLevel   = (int)dataSavingManager.GetOtherValue("BlocksPerLevel");
        int totalBKills = (int)dataSavingManager.GetOtherValue("TotalBlocksKilled");

        blockHealth.text       = NumberUtils.FormatLargeNumbers(bHealthAndReward.Item1);
        blockKillReward.text   = NumberUtils.FormatLargeNumbers(bHealthAndReward.Item2);
        blocksPerLevel.text    = bPerLevel.ToString();
        maxBlocksSpawned.text  = blockSpawnData.maxCurrentBlocks.ToString();
        blockSpawnSpeed.text   = NumberUtils.FormatLargeNumbers(blockSpawnData.spawnTime);
        totalBlocksKilled.text = NumberUtils.FormatLargeNumbers(totalBKills);
    }
Пример #17
0
        /// <summary>
        /// The POP BC instruction.
        /// </summary>
        private byte POP_BC()
        {
            FetchFinished();

            var sp    = (ushort)Registers.SP;
            var newBC = NumberUtils.CreateShort(
                ProcessorAgent.ReadFromMemory(sp),
                ProcessorAgent.ReadFromMemory((ushort)(sp + 1)));

            Registers.BC = newBC;

            Registers.SP += 2;

            return(10);
        }
Пример #18
0
        public List <Object> BuscarMarcadores()
        {
            var sql = Services.session.CreateSQLQuery(string.Format(@"
            SELECT Linea, Tipo, NI, NF, REPLACE(Long1,'.',',') as Long1, REPLACE(Lat1,'.',',') as Lat1, REPLACE(Long2,'.',',') as Long2, REPLACE(Lat2,'.',',') as Lat2
            FROM gq_xylineas            
            ORDER BY NI"));

            sql.SetResultTransformer(new NHibernate.Transform.AliasToBeanResultTransformer(typeof(XYLineasDto)));

            var items = sql.List <XYLineasDto>();

            Dictionary <string, Object> Nodo  = new Dictionary <string, Object>();
            Dictionary <string, Object> Linea = new Dictionary <string, Object>();

            foreach (var item in items)
            {
                if (!Nodo.ContainsKey(item.NI))
                {
                    var nodo = new Marker {
                        Id = item.NI, Position = new double[] { NumberUtils.ConvertTo <Double>(item.Lat1), NumberUtils.ConvertTo <Double>(item.Long1) }, Label = item.NI, FillColor = "#0000FF"
                    };
                    Nodo.Add(nodo.Id, nodo);
                }
                if (!Nodo.ContainsKey(item.NF))
                {
                    var nodo = new Marker {
                        Id = item.NF, Position = new double[] { NumberUtils.ConvertTo <Double>(item.Lat2), NumberUtils.ConvertTo <Double>(item.Long2) }, Label = item.NF, FillColor = "#0000FF"
                    };
                    Nodo.Add(nodo.Id, nodo);
                }
                if (!Linea.ContainsKey(item.Linea))
                {
                    var nodo = new MarcadorMapa {
                        Id = item.Linea, Polyline = new List <double[]>()
                        {
                            new double[] { NumberUtils.ConvertTo <Double>(item.Lat1), NumberUtils.ConvertTo <Double>(item.Long1) }, new double[] { NumberUtils.ConvertTo <Double>(item.Lat2), NumberUtils.ConvertTo <Double>(item.Long2) }
                        }, Type = MarcadorMapa.TYPE_POLYLINEA, StrokeColor = "#0000FF", StrokeOpacity = 1, StrokeWeight = 4
                    };
                    Linea.Add(nodo.Id, nodo);
                }
            }
            var list = new List <Object>();

            list.AddRange(Nodo.Values);
            list.AddRange(Linea.Values);

            return(list);
        }
Пример #19
0
        public unsafe Object convert(int pointer)
        {
            switch (type)
            {
            case 10: return(*(float *)pointer);

            //case 11: return 1;  // granny_int8
            case 12: return(*(byte *)pointer);                            // granny_uint8

            case 14: return(*(byte *)pointer);                            // granny_uint8

            case 21: return(NumberUtils.halfToFloat(*(UInt16 *)pointer)); // 16bit float

            default: return(null);
            }
        }
Пример #20
0
        public override int GetHashCode()
        {
            uint prime  = 31;
            uint result = 17;

            result = prime * result + NumberUtils.FloatToIntBits(x);
            result = prime * result + NumberUtils.FloatToIntBits(y);
            result = prime * result + NumberUtils.FloatToIntBits(scaleX);
            result = prime * result + NumberUtils.FloatToIntBits(scaleY);
            for (int j = 0; j < points.Length; j++)
            {
                long val = NumberUtils.FloatToIntBits(this.points[j]);
                result += 31 * result + (uint)(val ^ (val >> 32));
            }
            return((int)result);
        }
Пример #21
0
        public void CanToPositiveDegrees()
        {
            Assert.AreEqual(NumberUtils.ToPositiveDegrees(0.0), 0.0);

            Assert.AreEqual(NumberUtils.ToPositiveDegrees(1.0), 1.0);
            Assert.AreEqual(NumberUtils.ToPositiveDegrees(360.0), 0.0);
            Assert.AreEqual(NumberUtils.ToPositiveDegrees(361.0), 1.0);
            Assert.AreEqual(NumberUtils.ToPositiveDegrees(720.0), 0.0);
            Assert.AreEqual(NumberUtils.ToPositiveDegrees(721.0), 1.0);

            Assert.AreEqual(NumberUtils.ToPositiveDegrees(-1.0), 359.0);
            Assert.AreEqual(NumberUtils.ToPositiveDegrees(-360.0), 0.0);
            Assert.AreEqual(NumberUtils.ToPositiveDegrees(-361.0), 359.0);
            Assert.AreEqual(NumberUtils.ToPositiveDegrees(-720.0), 0.0);
            Assert.AreEqual(NumberUtils.ToPositiveDegrees(-721.0), 359.0);
        }
        public void Update(int index, T value)
        {
            int arrayIndex   = NumberUtils.WrapMod(index, _array.Length);
            int currentIndex = _array[arrayIndex].Index;

            if (currentIndex != index)
            {
                throw new ArgumentOutOfRangeException(nameof(index), index, "Cannot update when value is not the same");
            }

            _array[arrayIndex] = new Element()
            {
                Index = index,
                Value = value
            };
        }
Пример #23
0
        // Problem 4: Largest palindrome product
        // A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
        //
        // Find the largest palindrome made from the product of two 3-digit numbers.
        /// <summary>
        /// For this problem, we're making a list of all palindromic numbers that can be gotten by multiplying two 3-digit numbers together, then returning the biggest one.
        /// </summary>
        /// <returns>Returns the largest palindrome made from the product of two 3-digit numbers.</returns>
        public int PE0004()
        {
            List <int> PalindromeList = new List <int>();

            for (int i = 100; i < 1000; ++i)
            {
                for (int j = 100; j < 1000; ++j)
                {
                    if (NumberUtils.IsPalindromeProduct(i, j))
                    {
                        PalindromeList.Add(i * j);
                    }
                }
            }
            return(PalindromeList.Max());
        }
Пример #24
0
 public override string ToString()
 {
     if (_valueType == JSValueType.Integer)
     {
         return(Tools.Int32ToString(_iValue));
     }
     if (_valueType == JSValueType.Double)
     {
         return(NumberUtils.DoubleToString(_dValue));
     }
     if (_iValue != 0)
     {
         return(Tools.Int32ToString(_iValue));
     }
     return(NumberUtils.DoubleToString(_dValue));
 }
Пример #25
0
        public override bool Equals(object o)
        {
            if (this == o)
            {
                return(true);
            }
            if (o == null || GetType() != o.GetType())
            {
                return(false);
            }

            Plane plane = (Plane)o;

            return(NumberUtils.Compare(plane.d, d) == 0 &&
                   normal.Equals(plane.normal));
        }
        public void Set(int index, T value)
        {
            int arrayIndex   = NumberUtils.WrapMod(index, _array.Length);
            int currentIndex = _array[arrayIndex].Index;

            if (currentIndex != -1)
            {
                throw new ArgumentOutOfRangeException(nameof(index), index, "Cannot set a when value already exists");
            }

            _array[arrayIndex] = new Element()
            {
                Index = index,
                Value = value
            };
        }
Пример #27
0
        /// <summary>
        /// The RET C instruction.
        /// </summary>
        private void RET_C()
        {
            if (CF == 0)
            {
                return;
            }

            var sp    = (ushort)SP;
            var newPC = NumberUtils.CreateShort(
                Memory[sp],
                Memory[(ushort)(sp + 1)]);

            PC = (ushort)newPC;

            SP += 2;
        }
Пример #28
0
        public void GetFrame(int?number = null)
        {
            if (number != null)
            {
                _nextNumber = (int)number;
            }
            float ratio = _frame < StopPercentage * FramesPerTransition ? 0 :
                          (_frame - StopPercentage * FramesPerTransition) / (FramesPerTransition * (1 - StopPercentage));

            _controlPoints = _pointEvaluator.evaluate(ratio,
                                                      NumberUtils.getControlPointsFor(_currentNumber), NumberUtils.getControlPointsFor(_nextNumber));

            if (_controlPoints == null)
            {
                return;
            }

            int length = _controlPoints.Length / _controlPoints.Rank;

            float minDimen = _height > _width ? _width : _height;

            PathFigure pathFigure = new PathFigure();

            pathFigure.StartPoint = new Point(minDimen * _controlPoints[0, 0], minDimen * _controlPoints[0, 1]);

            for (int i = 1; i < length; i += 3)
            {
                BezierSegment bezierSegment = new BezierSegment();
                bezierSegment.Point1 = new Point(minDimen * _controlPoints[i, 0], minDimen * _controlPoints[i, 1]);
                bezierSegment.Point2 = new Point(minDimen * _controlPoints[i + 1, 0], minDimen * _controlPoints[i + 1, 1]);
                bezierSegment.Point3 = new Point(minDimen * _controlPoints[i + 2, 0], minDimen * _controlPoints[i + 2, 1]);

                pathFigure.Segments.Add(bezierSegment);
            }
            PathData.Figures.Clear();
            PathData.Figures.Add(pathFigure);

            if (_frame < FramesPerTransition)
            {
                _frame++;
            }
            else
            {
                _frame         = 0;
                _currentNumber = _nextNumber;
            }
        }
Пример #29
0
        public async Task <string> Remove(SocketTextChannel channel, ulong messageId, string reason)
        {
            IMessage message = await channel.GetMessageAsync(messageId);

            await channel.DeleteMessageAsync(message);

            User user = await UserService.GetUser(message.GetAuthor());

            User.Warning warning = new User.Warning();
            warning.Action    = User.Warning.Actions.PostRemoved;
            warning.ChannelId = channel.Id;
            warning.Comment   = reason;
            user.Warnings.Add(warning);
            await UserService.SaveUser(user);

            StringBuilder builder = new StringBuilder();

            builder.Append(message.GetAuthor().GetName());
            builder.Append(", a message you posted in the ");
            builder.Append(channel.Guild.Name);
            builder.Append(" #");
            builder.Append(channel.Name);
            builder.Append(" channel has been removed for the following reason: ");
            builder.Append(reason);
            builder.AppendLine(".");

            builder.Append("This is your ");
            builder.Append(user.Warnings.Count);
            builder.Append(NumberUtils.GetOrdinal(user.Warnings.Count));
            builder.Append(" warning.");

            builder.AppendLine();
            builder.AppendLine("This action was taken manually by a human moderator.");
            builder.Append("Please contact a moderator on the ");
            builder.Append(channel.Guild.Name);
            builder.Append(" server if you would like to discus this action.");

            await message.GetAuthor().SendMessageAsync(builder.ToString());

            builder.Clear();
            builder.AppendLine("Message removed.");
            builder.Append(message.GetAuthor().GetName());
            builder.Append(" has now been warned ");
            builder.Append(user.Warnings.Count);
            builder.Append(" times");
            return(builder.ToString());
        }
Пример #30
0
        /// <summary>
        /// Reads a <b>RawInt128</b> value from <b>DataReader</b>.
        /// </summary>
        /// <param name="reader">
        /// The <b>DataReader</b> to read from.
        /// </param>
        /// <returns>
        /// <b>RawInt128</b> value.
        /// </returns>
        public virtual RawInt128 ReadPackedRawInt128(DataReader reader)
        {
            const int cb    = 16;
            var       ab    = new byte[cb + 1];
            int       b     = reader.ReadByte();
            bool      isNeg = (b & 0x40) != 0;
            int       of    = cb;
            int       cBits = 6;

            ab[of] = (byte)(b & 0x3F);

            while ((b & 0x80) != 0)
            {
                b      = reader.ReadByte();
                ab[of] = (byte)((ab[of] & 0xFF) | ((b & 0x7F) << cBits));
                cBits += 7;
                if (cBits >= 8)
                {
                    cBits -= 8;
                    --of;

                    if (cBits > 0 && of >= 0)
                    {
                        ab[of] = (byte)(NumberUtils.URShift((b & 0x7F), (7 - cBits)));
                    }
                }
            }

            if (ab[of] == 0 && of < 16)
            {
                of++;
            }

            var result = new byte[ab.Length - of];

            Buffer.BlockCopy(ab, of, result, 0, result.Length);

            if (isNeg)
            {
                for (of = 0; of < result.Length; ++of)
                {
                    result[of] = (byte)~result[of];
                }
            }

            return(new RawInt128(result, isNeg));
        }