コード例 #1
0
        /// <summary>
        ///   The following method compares any 2 objects and test if they are equal.
        ///   It will also compare equality of numbers in a very special way.
        ///   Examples:
        ///   IsEqual(Int64.MaxValue, Int64.MaxValue) //is true
        ///   IsEqual(Int64.MaxValue, Int64.MaxValue-1) //is false
        ///   IsEqual(123, 123.0) //is true
        ///   IsEqual(654f, 654d) //is true
        /// </summary>
        internal static int Compare(IComparable a, IComparable b)
        {
            if (IsNumber(a) && IsNumber(b))
            {
                if (IsFloatingPoint(a) || IsFloatingPoint(b))
                {
                    double da, db;
                    if (Double.TryParse(a.ToString(), out da) && Double.TryParse(b.ToString(), out db))
                        return da.CompareTo(db);
                }
                else
                {
                    if (a.ToString().StartsWith("-") || b.ToString().StartsWith("-"))
                    {
                        var a1 = Convert.ToInt64(a);
                        var b1 = Convert.ToInt64(b);
                        
                        return a1.CompareTo(b1);
                    }
                    else
                    {
                        var a1 = Convert.ToUInt64(a);
                        var b1 = Convert.ToUInt64(b);

                        return a1.CompareTo(b1);
                    }
                }
            }

            return a.CompareTo(b);
        }
コード例 #2
0
 public static void merge(IComparable[] a, int lo, int mid, int hi)
 {
     // Merge a[lo..mid] with a[mid+1..hi].
     int i = lo, j = mid + 1;
     for (int k = lo; k <= hi; k++)
     {
         // Copy a[lo..hi] to aux[lo..hi].
         aux[k] = a[k];
     }
     for (int k = lo; k <= hi; k++)
     {
         // Merge back to a[lo..hi].
         if (i > mid)
         {
             a[k] = aux[j++];
         }
         else if (j > hi)
         {
             a[k] = aux[i++];
         }
         else if ((aux[j].CompareTo(aux[i]))<0)
         {
             a[k] = aux[j++];
         }
         else
         {
             a[k] = aux[i++];
         }
     }
 }
コード例 #3
0
ファイル: Shell.cs プロジェクト: kostasgrevenitis/algs4
        /// <summary>
        /// Rearranges the array in ascending order, using the natural order.
        /// </summary>
        /// <param name="a">a the array to be sorted</param>
        public static void Sort(IComparable[] a, IComparer c = null)
        {
            //make sure we have the comparer passed by argument or create default
            IComparer comparer = c ?? Comparer<object>.Default;

            int N = a.Length;

            int h = 1;

            //3*x +1 -> 1, 4, 13, 40, 121, 364, ..
            while (h < N / 3)
            {
                h = 3 * h + 1;
            }

            while (h >= 1)
            {

                //h- sort array
                for (int i = h; i < N; i++)
                {
                    for (int j = i; j >= h && less(comparer, a[j], a[j - h]); j -= h)
                    {
                        exch(a, j, j - h);
                    }
                }

                Debug.Assert(isHsorted(a, comparer, h));
                h = h / 3;
            }

            Debug.Assert(isSorted(a, comparer));
        }
コード例 #4
0
ファイル: Field.cs プロジェクト: pepipe/ISEL
        public Field(XmlElement elField)
        {
            String typeName = elField.GetAttribute("type");
            string lbStr = elField.GetAttribute("lower-bound");
            string ubStr = elField.GetAttribute("upper-bound");
            string fieldTypeStr = elField.GetAttribute("fieldtype");
            string valueStr = elField.InnerText;

            type = ClassTypes.GetType(typeName);
            fieldType = ParseTypeString(fieldTypeStr);

            if (!Formal)
            {
                value = ParseFieldValue(type, valueStr);
            }
            else
            {
                if (lbStr != null)
                {
                    lowerBound = (IComparable) ParseFieldValue(type, lbStr);
                }
                if (ubStr != null)
                {
                    upperBound = (IComparable) ParseFieldValue(type, ubStr);
                }
            }
        }
コード例 #5
0
        public void DevideCommand_Test()
        {
            var inputStringCommand = new[]
            {
                "5 5\r\n1 2 N\r\nLMLMLMLMM\r\n",
                "5 5\r\n1 2 N\r\nLMLMLMLMM\r\n1 2 N"
            };

            var outputValues = new IComparable[]
            {
                3,
                "ERROR"
            };

            for (int i = 0; i < inputStringCommand.Length; i++)
            {
                try
                {
                    DevideCommand devideCommand = new DevideCommand(inputStringCommand[i]);

                    Assert.AreEqual(devideCommand.GetArrayListCommand.Length, outputValues[i]);
                }
                catch (DevideCommandException exceptionDevideCommand)
                {
                    Assert.AreEqual(exceptionDevideCommand.Message, "Не достаточно данных для отправки");
                }
            }
        }
コード例 #6
0
 /// <summary>
 /// public sort method that is the entry point for sorting
 /// </summary>
 /// <param name="array">Array to sort</param>
 /// <param name="Length">Length of valid entries in the array. (Non null)</param>
 public void Sort(IComparable[] array, int Length)
 {
     //Set up the auxilary array and make it the size of the valid spots in the array to sort
     auxilary = new IComparable[Length];
     //call the private sort method which is also the recursive call
     sort(array, 0, Length - 1);
 }
コード例 #7
0
        public override void Sort(IComparable[] a)
        {
            int n = a.Length;
            int h = 1;
            int arrayLength = 1;

            while (h < n / 3)
            {
                h = h * 3 + 1;
                arrayLength++;
            }

            int[] hmas = new int[arrayLength--];
            hmas[arrayLength--] = h;
            h = h / 3;
            while (h >= 1)
            {
                hmas[arrayLength--] = h;
                h = h / 3;
            }

            for (int k = hmas.Length - 1; k >= 0; k--)
            {
                for (int i = hmas[k]; i < n; i++)
                {
                    for (int j = i; j > 0 && less(a[j], a[j - 1]); j -= h)
                    {
                        exch(a, j, j - 1);
                    }
                }
            }
        }
コード例 #8
0
ファイル: HeapSort.cs プロジェクト: jesconsa/Telerik-Academy
        private static int newHole(int hole, IComparable item, int lastIndex)
        {
            int left = (hole*2) + 1; //left child
            int right = (hole*2) + 2; //right child

            if (left > lastIndex)
                // hole has no childerns
                return hole;
            if (left == lastIndex) // hole has left child only
                if (item.CompareTo(elements[left]) < 0)
                    // item < left child
                    return left;
                else
                    // item  >= right child
                    return hole;
            // left child < right child
            if (elements[left].CompareTo(elements[right]) < 0)
                if (elements[right].CompareTo(item) < 0)
                    // right child <= item
                    return hole;
                else
                    // item < right child
                    return right;
            else 
                // left child >=right child
                if (elements[left].CompareTo(item) < 0)
                    // left child <= item
                    return hole;
                else
                    // item < left child
                    return left;
        }
コード例 #9
0
ファイル: RedBlackTree.cs プロジェクト: sillsdev/WorldPad
		/// <summary> Insert into the tree. Does nothing if item already present.
		/// </summary>
		/// <param name="item">the item to insert.
		/// </param>
		public virtual void  Insert(IComparable item)
		{
			current = parent = grand = header;
			nullNode.element = item;

			while (current.element.CompareTo(item) != 0)
			{
				great = grand; grand = parent; parent = current;
				current = item.CompareTo(current.element) < 0?current.left:current.right;

				// Check if two red children; fix if so
				if (current.left.color == RED && current.right.color == RED)
					handleReorient(item);
			}

			// Insertion fails if already present
			if (current != nullNode)
				return ;
			current = new RedBlackNode(item, nullNode, nullNode);

			// Attach to parent
			if (item.CompareTo(parent.element) < 0)
				parent.left = current;
			else
				parent.right = current;
			handleReorient(item);
		}
コード例 #10
0
        public bool CompareToRange(IComparable target, IComparable start, IComparable end)
        {
            if (target == null || start == null || end == null) return false;

            if (start.CompareTo(end) == 0 ) return target.CompareTo(start) == 0;
            return target.CompareTo(start) >= 0 && target.CompareTo(end) <= 0;
        }
コード例 #11
0
 public XIntervalSeries(IComparable key, bool autoSort, bool allowDuplicateXValues)
 {
   int num1 = autoSort ? 1 : 0;
   int num2 = allowDuplicateXValues ? 1 : 0;
   // ISSUE: explicit constructor call
   base.\u002Ector(key, num1 != 0, num2 != 0);
 }
コード例 #12
0
 //takes in array and area of the array that is populated
 public MergeSort(IComparable[] array, int length)
 {
     this.arraySize = length;
     this.array = array;
     //mergesort is called from the constructor
     MergeSort_Recursive(this.array, 0, arraySize - 1);
 }
コード例 #13
0
        public void DoMerge(IComparable[] numbers, int left, int mid, int right)
        {
            IComparable[] temp = new IComparable[arraySize];
            int i, left_end, num_elements, tmp_pos;

            left_end = (mid - 1);
            tmp_pos = left;
            num_elements = (right - left + 1);

            while ((left <= left_end) && (mid <= right))
            {
                if (numbers[left].CompareTo(numbers[mid]) <= 0)
                    temp[tmp_pos++] = numbers[left++];
                else
                    temp[tmp_pos++] = numbers[mid++];
            }

            while (left <= left_end)
                temp[tmp_pos++] = numbers[left++];

            while (mid <= right)
                temp[tmp_pos++] = numbers[mid++];

            for (i = 0; i < num_elements; i++)
            {
                numbers[right] = temp[right];
                right--;
            }
        }
コード例 #14
0
        public override void InsertKeyAndValue(IComparable key, object value)
        {
            var position = GetPositionOfKey(key);
            var addToExistingCollection = false;
            int realPosition;

            if (position >= 0)
            {
                addToExistingCollection = true;
                realPosition = position - 1;
            }
            else
            {
                realPosition = -position - 1;
            }

            // If there is an element at this position and the key is different,
            // then right shift, size
            // safety is guaranteed by the rightShiftFrom method
            if (realPosition < NbKeys && key.CompareTo(Keys[realPosition]) != 0)
                RightShiftFrom(realPosition, true);

            Keys[realPosition] = key;
            
            // This is a non unique btree node, manage collection
            ManageCollectionValue(realPosition, value);
            
            if (!addToExistingCollection)
                NbKeys++;
        }
コード例 #15
0
        public virtual IList Search(IComparable key)
        {
            var positionOfKey = GetPositionOfKey(key);
            var keyIsHere = positionOfKey > 0;
            int realPosition;
            
            if (keyIsHere)
            {
                realPosition = positionOfKey - 1;
                var valueAsList = GetValueAt(realPosition);

                return valueAsList;
            }
            
            if (IsLeaf())
            {
                // key is not here and node is leaf
                return null;
            }

            realPosition = -positionOfKey - 1;
            
            var node = (IBTreeNodeMultipleValuesPerKey) GetChildAt(realPosition, true);
            return node.Search(key);
        }
コード例 #16
0
ファイル: Node.cs プロジェクト: gitter-badger/LinksPlatform
 public Node(Node parent, IComparable key, object value, bool createNullChildren)
 {
     Parent = parent;
     Key = key;
     Value = value;
     CreateNullChildren = createNullChildren;
 }
コード例 #17
0
ファイル: QuickSort.cs プロジェクト: hong-rong/MyRepository
        private int Partition_Version_One(IComparable[] a, int lo, int hi)
        {
            int i = lo;
            int j = hi + 1;
            IComparable value = a[lo];

            while (true)
            {
                while (Less(a[++i], value))
                {
                    if (i == hi) break;
                }

                while (Less(value, a[--j]))
                {
                    if (j == lo) break;
                }

                if (i >= j)
                {
                    break;
                }

                Exchange(a, i, j);
            }

            Exchange(a, lo, j);

            return j;
        }
コード例 #18
0
 public void enqueue(IComparable item)
 {
     if (lastIndex == maxIndex)
         throw new InsufficientMemoryException("Heap is full");
     lastIndex += 1;
     reheapUp(item);
 }
コード例 #19
0
		public TimerEventSubscription (Guid timerId, Guid workflowInstanceId, DateTime expiresAt) : this ()
		{
			this.timerId = timerId;
			this.workflowInstanceId = workflowInstanceId;
			this.expiresAt = expiresAt;
			this.name = timerId;
		}
コード例 #20
0
ファイル: ArithmeticCriteria.cs プロジェクト: JZO001/Forge
        /// <summary>
        /// Initializes a new instance of the <see cref="ArithmeticCriteria"/> class.
        /// </summary>
        /// <param name="fieldName">Name of the field.</param>
        /// <param name="value">The value.</param>
        /// <param name="operand">The operand.</param>
        public ArithmeticCriteria(string fieldName, IComparable value, ArithmeticOperandEnum operand)
            : base(fieldName)
        {
            if (value == null)
            {
                ThrowHelper.ThrowArgumentNullException("value");
            }

            Type valueType = value.GetType();
            if (valueType.IsGenericType && valueType.GetGenericTypeDefinition().Equals(typeof(EntityBaseGenericId<>)))
            {
                dynamic dynValue = value;
                if (dynValue.Id == null)
                {
                    ThrowHelper.ThrowArgumentException(String.Format("Provided entity has not got identifier. Entity type: '{0}'.", valueType.FullName), "value");
                }
                if (fieldName.ToLower().Equals("id"))
                {
                    this.FieldName = fieldName;
                }
                else
                {
                    this.FieldName = fieldName.ToLower().EndsWith(".id") ? fieldName : String.Format("{0}.id", fieldName);
                }
                this.mValue = dynValue.Id;
            }
            else
            {
                this.mValue = value;
            }
            this.mOperand = operand;
        }
コード例 #21
0
        public override bool IsValid(IComparable value, IComparable valueToCompare)
        {
            if (valueToCompare == null)
                return false;

            return Comparer.GetComparisonResult(value, valueToCompare) >= 0;
        }
コード例 #22
0
ファイル: Quick.cs プロジェクト: kaplunov93/Algorithms
 private static void sort(IComparable[] a, int lo, int hi)
 {
     if (hi <= lo) return;
     int j = partition(a, lo, hi);
     sort(a, lo, j - 1); // Sort left part a[lo .. j-1].
     sort(a, j + 1, hi); // Sort right part a[j+1 .. hi].
 }
コード例 #23
0
        /// <summary>
        /// Indicates whether the instance is greater or equal to the reference value.
        /// </summary>
        /// <param name="value">The instance to test.</param>
        /// <param name="referenceValue">The reference value to test.</param>
        /// <returns><strong>true</strong> if the instance is greater or equal to the reference
        /// value; otherwise, <strong>false</strong>.</returns>
        /// <exception cref="ArgumentNullException"><em>value</em> or <em>referenceValue</em> is
        /// <strong>null</strong>.</exception>
        public static bool IsGreaterOrEqual(this IComparable value, IComparable referenceValue)
        {
            Precondition.IsNotNull(value, nameof(value));
            Precondition.IsNotNull(referenceValue, nameof(referenceValue));

            return value.IsGreater(referenceValue) || value.IsEqual(referenceValue);
        }
コード例 #24
0
        protected override IEnumerable<long> GetValues(ISonesIndex myIndex, IComparable myIComparable)
        {
            if (myIndex is ISonesRangeIndex)
            {
                //use the range funtionality
                foreach (var aVertexID in ((ISonesRangeIndex)myIndex).LowerThan(myIComparable, true))
                {
                    yield return aVertexID;
                }
            }
            else
            {
                //stupid, but works

                foreach (var aVertexIDSet in myIndex.Keys().Where(key => key.CompareTo(myIComparable) <= 0).Select(key => myIndex[key]))
                {
                    foreach (var aVertexID in aVertexIDSet)
                    {
                        yield return aVertexID;
                    }
                }
            }

            yield break;
        }
コード例 #25
0
        /// <summary>
        /// Indicates whether the instance is greater as the reference value.
        /// </summary>
        /// <param name="value">The instance to test.</param>
        /// <param name="referenceValue">The reference value to test.</param>
        /// <returns><strong>true</strong> if the instance is greater as the reference value;
        /// otherwise, <strong>false</strong>.</returns>
        /// <exception cref="ArgumentNullException"><em>value</em> or <em>referenceValue</em> is
        /// <strong>null</strong>.</exception>
        public static bool IsGreater(this IComparable value, IComparable referenceValue)
        {
            Precondition.IsNotNull(value, nameof(value));
            Precondition.IsNotNull(referenceValue, nameof(referenceValue));

            return value.CompareTo(referenceValue) == 1;
        }
コード例 #26
0
ファイル: Verify.cs プロジェクト: shanet/Asimov
 public static void ArgumentInRange(IComparable argument, IComparable minimum, IComparable maximum, string paramName = DefaultParamName)
 {
     if (argument.CompareTo(minimum) < 0 || argument.CompareTo(maximum) > 0)
     {
         throw new ArgumentException(string.Format("{0} must be between {1} and {2}.", paramName, minimum, maximum), paramName);
     }
 }
コード例 #27
0
    public static void Quicksort(IComparable[] elements, int left, int right)
    {
        int leftIndex = left, rightIndex = right;
        IComparable pivot = elements[(left + right) / 2];

        while (leftIndex <= rightIndex)
        {
            while (elements[leftIndex].CompareTo(pivot) < 0)
            {
                leftIndex++;
            }
            while (elements[rightIndex].CompareTo(pivot) > 0)
            {
                rightIndex--;
            }
            if (leftIndex <= rightIndex)
            {
                IComparable temp = elements[leftIndex];
                elements[leftIndex] = elements[rightIndex];
                elements[rightIndex] = temp;
                leftIndex++;
                rightIndex--;
            }
        }
        if (left < rightIndex)
        {
            Quicksort(elements, left, rightIndex);
        }

        if (leftIndex < right)
        {
            Quicksort(elements, leftIndex, right);
        }
    }
コード例 #28
0
ファイル: Heap.cs プロジェクト: jesconsa/Telerik-Academy
 public void enqueue(IComparable item)
 {
     if (lastIndex == maxIndex)
         throw new Exception("Priority queue is full");
     lastIndex = lastIndex + 1;
     reheapUp(item);
 }
コード例 #29
0
ファイル: Verify.cs プロジェクト: shanet/Asimov
 public static void ArgumentAtMost(IComparable argument, IComparable maximum, string paramName = DefaultParamName)
 {
     if (argument.CompareTo(maximum) > 0)
     {
         throw new ArgumentException(string.Format("{0} must be at most {1}.", paramName, maximum), paramName);
     }
 }
コード例 #30
0
        public override IEnumerable<long> GetMultipleIndexValues(IMultipleValueIndex<IComparable, long> myMultipleValueIndex, IComparable myIComparable)
        {
            if (myMultipleValueIndex is IRangeIndex<IComparable, long>)
            {
                //use the range funtionality

                foreach (var aVertexIDSet in ((IMultipleValueRangeIndex<IComparable, long>)myMultipleValueIndex).LowerThan(myIComparable, false))
                {
                    foreach (var aVertexID in aVertexIDSet)
                    {
                        yield return aVertexID;
                    }
                }
            }
            else
            {
                //stupid, but works

                foreach (var aVertexIDSet in myMultipleValueIndex.Where(kv => kv.Key.CompareTo(myIComparable) < 0).Select(kv => kv.Value))
                {
                    foreach (var aVertexID in aVertexIDSet)
                    {
                        yield return aVertexID;
                    }
                }
            }

            yield break;
        }
コード例 #31
0
 /// <summary>
 /// Override to perform the comparison
 /// </summary>
 /// <param name="value"></param>
 /// <param name="valueToCompare"></param>
 /// <returns></returns>
 public abstract bool IsValid(IComparable value, IComparable valueToCompare);
コード例 #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Range"/> class.
 /// Creates an instance of the rule.
 /// </summary>
 /// <param name="primaryProperty">
 /// Property to which the rule applies.
 /// </param>
 /// <param name="min">
 /// Min value.
 /// </param>
 /// <param name="max">
 /// Max value.
 /// </param>
 /// <param name="messageDelegate">
 /// The message delegate.
 /// </param>
 public Range(IPropertyInfo primaryProperty, IComparable min, IComparable max, Func <string> messageDelegate)
     : this(primaryProperty, min, max)
 {
     MessageDelegate = messageDelegate;
 }
コード例 #33
0
ファイル: GuidTests.cs プロジェクト: qianwang09/corefx
        public static void CompareTo_ValueNotGuid_ThrowsArgumentException()
        {
            IComparable comparable = s_testGuid;

            Assert.Throws <ArgumentException>("value", () => comparable.CompareTo("a8a110d5-fc49-43c5-bf46-802db8f843ff")); // Value is not a guid
        }
コード例 #34
0
    public static void TestCompareToObjectInvalid()
    {
        IComparable comparable = (ushort)234;

        Assert.Throws <ArgumentException>(null, () => comparable.CompareTo("a")); //Obj is not a ushort
    }
コード例 #35
0
        public void ConvertValueToCompatibleType()
        {
            IComparable c = (new JValue(1).Value <IComparable>());

            Assert.AreEqual(1L, c);
        }
コード例 #36
0
ファイル: Sort.cs プロジェクト: jmarkova/ITCareer
 // Дали даден елемент е по малък от друг = O(1)
 public static bool IsLess(IComparable first, IComparable second)
 {
     return(first.CompareTo(second) < 0);
 }
コード例 #37
0
 /// <summary>
 /// Returns a constraint that tests whether the actual value falls
 /// within a specified range.
 /// </summary>
 public static RangeConstraint InRange(IComparable from, IComparable to)
 {
     return(new RangeConstraint(from, to));
 }
コード例 #38
0
 /// <summary>
 ///     Updates a data point when its actual dependent value has changed.
 /// </summary>
 /// <param name="dataPoint">The data point.</param>
 /// <param name="oldValue">The old value.</param>
 /// <param name="newValue">The new value.</param>
 protected override void OnDataPointActualDependentValueChanged(DataPoint dataPoint, IComparable oldValue,
                                                                IComparable newValue)
 {
     UpdateDataPoint(dataPoint);
     base.OnDataPointActualDependentValueChanged(dataPoint, oldValue, newValue);
 }
コード例 #39
0
 public MinInclusive(decimal value)
 {
     this._Value = value;
 }
コード例 #40
0
 /// <summary>
 /// </summary>
 /// <param name="value"></param>
 /// <param name="resourceName"></param>
 /// <param name="resourceType"></param>
 protected AbstractComparisonValidator(IComparable value, string resourceName, Type resourceType) : base(resourceName, resourceType)
 {
     value.Guard("value must not be null.");
     ValueToCompare = value;
 }
コード例 #41
0
 public MinInclusive(float value)
 {
     this._Value = value;
 }
コード例 #42
0
 public MinInclusive(IComparable value)
 {
     this._Value = value;
 }
コード例 #43
0
 public MinInclusive(int value)
 {
     this._Value = value;
 }
コード例 #44
0
 public MinInclusive(double value)
 {
     this._Value = value;
 }
コード例 #45
0
        int IComparable <PointedAddress> .CompareTo(PointedAddress obj)
        {
            IComparable <Address> iaddr = this.addr;

            return(iaddr.CompareTo(obj.addr));
        }
コード例 #46
0
 public MinInclusive(long value)
 {
     this._Value = value;
 }
コード例 #47
0
 public OrderedComparable(IComparable innerItem, OrderByEnum orderBy)
 {
     _orderBy   = orderBy;
     _innerItem = innerItem;
 }
コード例 #48
0
ファイル: LineDataPoint.cs プロジェクト: sulerzh/chart
 public LineDataPoint(IComparable xValue, IComparable yValue)
     : base(xValue, yValue)
 {
 }
コード例 #49
0
        public Color? OverrideCellColor(IRenderableSeries rSeries, int xIndex, int yIndex, IComparable zValue, Color cellColor, IPointMetadata metadata)
        {
            if((double)zValue >= ThresholdValue)
            {
                cellColor = _overheatColor;
            }

            return cellColor;
        }
コード例 #50
0
        public static OrderedComparable Asc(IComparable item)
        {
            var ret = new OrderedComparable(item, OrderByEnum.Asc);

            return(ret);
        }
コード例 #51
0
        /// <summary>
        /// Asserts if the two instances are not the same.
        /// </summary>
        /// <param name="expected"></param>
        /// <param name="actual"></param>
        /// <param name="description"></param>
        /// <param name="onlyCompareDataMembers">When true, only data contracts members are compared.</param>
        /// <param name="treatNullSameAsEmptyString">When true, when comparing strings, null and and empty string are considered equivalent.</param>
        /// <param name="ignoreCollectionOrder">When true, expected and actual collections items do not have to be in the same order</param>
        /// <param name="getSortId">Value types and strings are already handled. If handling of more complex types is required, put it here.</param>
        /// <param name="tryConvertMismatchedTypes">if the actual type is not the same as the expected type, try to convert it. This allows a string representation of a Guid, for example, to be considered a match of the corresponding Guid.</param>
        public static void ValidateAreSame(
            object expected,
            object actual,
            string description                   = null,
            bool onlyCompareDataMembers          = true,
            bool treatNullSameAsEmptyString      = false,
            bool ignoreCollectionOrder           = false,
            Func <object, IComparable> getSortId = null,
            bool tryConvertMismatchedTypes       = false)
        {
            if (object.ReferenceEquals(expected, actual))
            {
                // if the two instances are the same, no need to do further validation.
                return;
            }

            // If only one is null, fail.
            if ((expected == null) != (actual == null))
            {
                if (treatNullSameAsEmptyString && (expected is string || actual is string))
                {
                    expected = expected ?? string.Empty;
                    actual   = actual ?? string.Empty;
                }
                Assert.Equal(expected, actual);
                return;
            }

            if (tryConvertMismatchedTypes)
            {
                Common.TryConvertMismatchedTypes(ref expected, ref actual);
            }
            Type itemType   = expected.GetType();
            Type actualType = actual.GetType();

            Assert.Equal(itemType, actualType);

            if ((itemType.IsValueType && !itemType.IsConstructedGenericType) || itemType == typeof(string) || itemType == typeof(JValue))
            {
                Assert.Equal(expected, actual);
            }
            else
            {
                bool        isTypeDataContract   = (itemType.GetCustomAttribute <DataContractAttribute>() != null);
                IDictionary expectedAsDictionary = expected as IDictionary;

                BindingFlags getPropertiesFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty;
                foreach (PropertyInfo property in itemType.GetProperties(getPropertiesFlags))
                {
                    bool isPropertyReadOnly             = false;
                    ReadOnlyAttribute readOnlyAttribute = property.GetCustomAttribute <ReadOnlyAttribute>();
                    if (readOnlyAttribute != null)
                    {
                        isPropertyReadOnly = readOnlyAttribute.IsReadOnly;
                    }
                    string childPropertyName = property.Name;
                    if (!property.GetMethod.GetParameters().Any() &&                                                                       // skip properties that have input parameters, like indexers on collections, dictionaries, etc.
                        !isPropertyReadOnly &&                                                                                             // skip properties that are decorated with the ReadOnlyAttribute. This is used to flag properties that should not be evaluated here, such as properties that are set on the server (like ChangeTag)
                        (!onlyCompareDataMembers || !isTypeDataContract || property.GetCustomAttribute <DataMemberAttribute>() != null) && // skip non-DataMember properties, if required
                        (expectedAsDictionary == null || (childPropertyName != "Keys" && childPropertyName != "Values"))                   // skip dictionary-specific properties that are compared later in an order-insensitive fashion
                        )
                    {
                        object expectedPropertyValue = property.GetValue(expected, null);
                        if (!object.ReferenceEquals(expected, expectedPropertyValue))// Protect against infinite recursion (can happen with the SyncRoot property of arrays)
                        {
                            object actualPropertyValue = property.GetValue(actual, null);
                            Common.ValidateAreSame(expectedPropertyValue, actualPropertyValue, string.Format(CultureInfo.InvariantCulture, "{0}.{1}", description, childPropertyName), onlyCompareDataMembers, treatNullSameAsEmptyString, ignoreCollectionOrder, getSortId, tryConvertMismatchedTypes);
                        }
                    }
                    else
                    {
                        // skipped property
                    }
                }


                var expectedAsEnumerable = expected as IEnumerable;

                if (expectedAsEnumerable != null)
                {
                    if (expectedAsDictionary != null)
                    {
                        Common.ValidateDictionariesItemsAreSame(
                            expectedAsDictionary,
                            (IDictionary)actual,
                            description,
                            onlyCompareDataMembers,
                            treatNullSameAsEmptyString,
                            ignoreCollectionOrder,
                            getSortId,
                            tryConvertMismatchedTypes);
                    }
                    else
                    {
                        var expectedItems = expectedAsEnumerable.Cast <object>().ToList();
                        var actualItems   = ((IEnumerable)actual).Cast <object>().ToList();

                        if (ignoreCollectionOrder)
                        {
                            // Reorder the actual list to be in the same order as the expected list.
                            object firstExpectedItem = expectedItems.FirstOrDefault();
                            if (firstExpectedItem != null)
                            {
                                if (firstExpectedItem.GetType().IsValueType || firstExpectedItem is string || firstExpectedItem is IComparable || firstExpectedItem is byte[])
                                {
                                    var reorderedActualItems = new List <object>();
                                    foreach (object expectedItem in expectedItems)
                                    {
                                        int matchingActualItemIndex;
                                        if (expectedItem == null)
                                        {
                                            matchingActualItemIndex = actualItems.FindIndex(item => item == null);
                                        }
                                        else
                                        {
                                            var expectedBytes = expectedItem as byte[];
                                            if (expectedBytes != null)
                                            {
                                                matchingActualItemIndex = actualItems.FindIndex(item =>
                                                {
                                                    var bytes = item as byte[];
                                                    if (bytes != null && expectedBytes.Length == bytes.Length)
                                                    {
                                                        for (int i = 0; i < bytes.Length; i++)
                                                        {
                                                            if (bytes[i] != expectedBytes[i])
                                                            {
                                                                return(false);
                                                            }
                                                        }
                                                        return(true);
                                                    }
                                                    return(false);
                                                });
                                            }
                                            else
                                            {
                                                matchingActualItemIndex = actualItems.FindIndex(item => expectedItem.Equals(item));
                                            }
                                        }
                                        Assert.True(matchingActualItemIndex >= 0, description + ". Actual collection does not contain a item =" + expectedItem);
                                        reorderedActualItems.Add(actualItems[matchingActualItemIndex]);
                                        actualItems.RemoveAt(matchingActualItemIndex);
                                    }
                                    reorderedActualItems.AddRange(actualItems);
                                    actualItems = reorderedActualItems;
                                }
                                else if (getSortId != null && getSortId(firstExpectedItem) != null) // If the user provided a function to help sort, then use it.
                                {
                                    var reorderedActualItems = new List <object>();
                                    foreach (object expectedItem in expectedItems)
                                    {
                                        IComparable expectedSortId          = getSortId(expectedItem);
                                        int         matchingActualItemIndex = actualItems.FindIndex(item => getSortId(item).Equals(expectedSortId));
                                        Assert.True(matchingActualItemIndex >= 0, description + ". Actual collection does not contain an item with sort id=" + expectedSortId);
                                        reorderedActualItems.Add(actualItems[matchingActualItemIndex]);
                                        actualItems.RemoveAt(matchingActualItemIndex);
                                    }
                                    reorderedActualItems.AddRange(actualItems);
                                    actualItems = reorderedActualItems;
                                }
                            }
                        }

                        Common.ValidateListItemsAreSame(
                            expectedItems,
                            actualItems,
                            description,
                            onlyCompareDataMembers,
                            treatNullSameAsEmptyString,
                            ignoreCollectionOrder,
                            getSortId,
                            tryConvertMismatchedTypes);
                    }
                }
            }
        }
コード例 #52
0
 public GreaterThanOrEqualValidator(IComparable value) :
     base(value, new LanguageStringSource(nameof(GreaterThanOrEqualValidator)))
 {
 }
コード例 #53
0
        private static IComparable GetQueueName(IEventActivity eventActivity)
        {
            IComparable queueName = eventActivity.QueueName;

            return(queueName);
        }
コード例 #54
0
        private void EnqueueProjectEvaluation(IComparable version, IProjectChangeDiff evaluationDifference)
        {
            Assumes.False(_projectEvaluations.Count > 0 && version.IsEarlierThanOrEqualTo(_projectEvaluations.Peek().Version), "Attempted to push a project evaluation that regressed in version.");

            _projectEvaluations.Enqueue(new VersionedProjectChangeDiff(version, evaluationDifference));
        }
コード例 #55
0
    protected void Veriler(int Baslangic, int Bitis, string s, string Kolon, string AscDesc, out IList Sonuc1, out IList Sonuc2)
    {
        #region Çalışan Hali
        using (BaglantiCumlesi SME = new BaglantiCumlesi())
        {
            try
            {
                #region Kolon Sorting Ayarı
                string KolonAdi = null;
                switch (Kolon)
                {
                    #region Admin
                case "ekleyen":
                    Kolon    = "admin_id_ek";
                    KolonAdi = Kolon;
                    break;
                    #endregion

                    #region İşlem
                case "guncelleyen":
                    Kolon    = "admin_id_gun";
                    KolonAdi = Kolon;
                    break;
                    #endregion
                }
                #endregion

                #region İlk SQL - SONUÇ 1

                #region İlk (Ham) SQL
                int DilID = int.Parse(ComboBoxDil.SelectedItem.Value);
                var SQL1  = (from p in SME.tbl_menuler
                             where p.dil_id == DilID
                             select new
                {
                    p.id,
                    p.ad,
                    p.url,
                    p.sira,
                    p.tarih_ek,
                    p.tarih_gun,
                    p.admin_id_ek,
                    p.admin_id_gun,
                    p.dil_id,
                    p.onay
                });
                #endregion

                #region SQL i Cache 'e Atma
                //CachedQueryOptions CQO = new CachedQueryOptions();
                var SQL2 = (CacheOlayi ? SQL1.AsCached(SayfaAdi).AsQueryable().OrderBy(Kolon + " " + AscDesc).ToList() : SQL1.AsQueryable().OrderBy(Kolon + " " + AscDesc).ToList());
                #endregion

                #region Sonuç 1
                Sonuc1 = SQL2;
                #endregion

                #endregion

                #region İlk SQL in Ccount ı Sıfırdan Büyükse Filtreleme Yap
                if (SQL2.Count() > 0)
                {
                    #region Filtreleme
                    if (!string.IsNullOrEmpty(s))
                    {
                        FilterConditions FC = new FilterConditions(s);

                        foreach (FilterCondition FCO in FC.Conditions)
                        {
                            Comparison C  = FCO.Comparison;
                            FilterType FT = FCO.FilterType;

                            #region Kolon Adı Boşsa Değer Ver
                            if (string.IsNullOrEmpty(KolonAdi))
                            {
                                KolonAdi = FCO.Name;
                            }
                            #endregion

                            #region Gelen Değerler
                            object value;
                            #endregion

                            switch (FCO.FilterType)
                            {
                                #region Filtre Tipi Bool İse
                            case FilterType.Boolean:
                                value = FCO.ValueAsBoolean;
                                break;
                                #endregion

                                #region Filtre Tipi Date İse
                            case FilterType.Date:
                                value = FCO.ValueAsDate;
                                break;
                                #endregion

                                #region Filtre Tipi Liste İse
                            case FilterType.List:
                                value = FCO.ValuesList;
                                break;
                                #endregion

                                #region Filtre Tipi Nümerik İse
                            case FilterType.Numeric:
                                if (SQL2.Count() > 0 && (SQL2[0].GetType().GetProperty(KolonAdi).PropertyType == typeof(int) || SQL2[0].GetType().GetProperty(KolonAdi).PropertyType == typeof(Int16) || SQL2[0].GetType().GetProperty(KolonAdi).PropertyType == typeof(Int32) || SQL2[0].GetType().GetProperty(KolonAdi).PropertyType == typeof(Int64) || SQL2[0].GetType().GetProperty(KolonAdi).PropertyType == typeof(Nullable <int>) || SQL2[0].GetType().GetProperty(KolonAdi).PropertyType == typeof(Nullable <Int16>) || SQL2[0].GetType().GetProperty(KolonAdi).PropertyType == typeof(Nullable <Int32>) || SQL2[0].GetType().GetProperty(KolonAdi).PropertyType == typeof(Nullable <Int64>)))
                                {
                                    value = FCO.ValueAsInt;
                                }
                                else
                                {
                                    value = FCO.ValueAsDouble;
                                }
                                break;
                                #endregion

                                #region Filtre Tipi String İse
                            case FilterType.String:
                                value = FCO.Value;
                                break;
                                #endregion

                                #region Switch Default
                            default:
                                throw new ArgumentOutOfRangeException();
                                #endregion
                            }

                            SQL2.RemoveAll(item =>
                            {
                                object o       = item.GetType().GetProperty(KolonAdi).GetValue(item, null);
                                IComparable IC = o as IComparable;

                                switch (C)
                                {
                                case Comparison.Eq:

                                    switch (FT)
                                    {
                                        #region Filtre Tipi Liste İse
                                    case FilterType.List:
                                        return(!(value as ReadOnlyCollection <string>).Contains(o.ToString()));

                                        #endregion

                                        #region Filtre Tipi String İse
                                    case FilterType.String:
                                        return(!o.ToString().StartsWith(value.ToString()));

                                        #endregion

                                        #region Switch Default
                                    default:
                                        return(!IC.Equals(value));

                                        #endregion
                                    }

                                case Comparison.Gt:
                                    return(IC.CompareTo(value) < 1);

                                case Comparison.Lt:
                                    return(IC.CompareTo(value) > -1);

                                    #region Switch Default
                                default:
                                    throw new ArgumentOutOfRangeException();
                                    #endregion
                                }
                            });
                        }
                    }
                    #endregion
                }
                #endregion

                #region SQL İçeriğini Değiştirme
                var SQL3 = SQL2.Skip(Baslangic).Take(Bitis).Select(p => new
                {
                    p.id,
                    p.ad,
                    p.url,
                    p.sira,
                    p.tarih_ek,
                    p.tarih_gun,
                    p.admin_id_ek,
                    p.admin_id_gun,
                    p.dil_id,
                    ekleyen     = (p.admin_id_ek != null ? SME.tbl_adminler.Where(k => k.id == p.admin_id_ek).Select(x => "(" + x.kullanici_adi + ") " + x.ad_soyad).FirstOrDefault() : null),
                    guncelleyen = (p.admin_id_gun != null ? SME.tbl_adminler.Where(k => k.id == p.admin_id_gun).Select(x => "(" + x.kullanici_adi + ") " + x.ad_soyad).FirstOrDefault() : null),
                    dil         = SME.tbl_diller.Where(k => k.id == p.dil_id).Select(x => x.dil).FirstOrDefault(),
                    onay        = (p.onay ? "EVET" : "HAYIR")
                }).AsEnumerable().Cast <object>().ToList();
                #endregion

                #region Sonuç 2
                Sonuc2 = SQL3;
                #endregion
            }
            catch
            {
                #region Boş Değer Döndür
                Sonuc1 = null;
                Sonuc2 = null;
                #endregion
            }
        }

        #endregion
    }
コード例 #56
0
        internal void ReevaluateSubscriptions(ActivityExecutionContext context)
        {
            Dictionary <IComparable, StateMachineSubscription> subscriptions = this.GetSubscriptionsShallowCopy();
            List <IComparable> subscribed = new List <IComparable>();

            StateActivity state = StateMachineHelpers.GetCurrentState(context);

            while (state != null)
            {
                foreach (Activity activity in state.EnabledActivities)
                {
                    EventDrivenActivity eventDriven = activity as EventDrivenActivity;
                    if (eventDriven == null)
                    {
                        continue;
                    }

                    IEventActivity eventActivity = StateMachineHelpers.GetEventActivity(eventDriven);
                    IComparable    queueName     = eventActivity.QueueName;
                    if (queueName == null)
                    {
                        continue;
                    }

                    StateMachineSubscription subscription;
                    subscriptions.TryGetValue(queueName, out subscription);
                    EventActivitySubscription eventActivitySubscription = subscription as EventActivitySubscription;
                    if (eventActivitySubscription != null)
                    {
                        if (eventActivitySubscription.EventDrivenName.Equals(eventDriven.QualifiedName))
                        {
                            // this EventDriven is already subscribed
                            subscribed.Add(queueName);
                            continue;
                        }
                        else
                        {
                            // Check if this state already subscribe to this event
                            // if so, throws, since it is not valid to subscribe to the
                            // same event twice
                            if (eventActivitySubscription.StateName.Equals(state.QualifiedName))
                            {
                                throw new InvalidOperationException(SR.GetStateAlreadySubscribesToThisEvent(state.QualifiedName, queueName));
                            }

                            // some other EventDriven is subscribed, so we need to unsubscribe if
                            // the event driven belongs to one of our parents
                            if (IsParentState(state, eventActivitySubscription.StateName))
                            {
                                UnsubscribeAction unsubscribe = new UnsubscribeAction(eventActivitySubscription.StateName, eventActivitySubscription.EventDrivenName);
                                this.ExecutionState.EnqueueAction(unsubscribe);
                                subscriptions.Remove(queueName);
                            }
                        }
                    }

                    // Tests if a child state already subscribes to this event
                    // is so, skip, since the child takes precedence
                    if (subscribed.Contains(queueName))
                    {
                        continue;
                    }

                    SubscribeAction subscribe = new SubscribeAction(state.QualifiedName, eventDriven.QualifiedName);
                    this.ExecutionState.EnqueueAction(subscribe);
                    subscribed.Add(queueName);
                }

                state = state.Parent as StateActivity;
            }

            StateActivity       currentState  = StateMachineHelpers.GetCurrentState(context);
            DisableQueuesAction disableQueues = new DisableQueuesAction(currentState.QualifiedName);

            this.ExecutionState.EnqueueAction(disableQueues);
        }
コード例 #57
0
ファイル: BooleanTests.cs プロジェクト: zpk513/corefx
 private static void CompareTo_ObjectNotBool_ThrowsArgumentException(IComparable b, object obj)
 {
     AssertExtensions.Throws <ArgumentException>(null, () => b.CompareTo(obj));
 }
コード例 #58
0
        internal static WorkflowQueue GetWorkflowQueue(ActivityExecutionContext context, IComparable queueName)
        {
            WorkflowQueuingService workflowQueuingService = context.GetService <WorkflowQueuingService>();

            if (workflowQueuingService.Exists(queueName))
            {
                WorkflowQueue workflowQueue = workflowQueuingService.GetWorkflowQueue(queueName);
                return(workflowQueue);
            }
            return(null);
        }
コード例 #59
0
ファイル: Program.cs プロジェクト: GabrielDaskalov/Algorithms
 private static bool IsLess(IComparable key, IComparable mid)
 {
     return(key.CompareTo(mid) < 0);
 }
コード例 #60
0
ファイル: TokenPair.cs プロジェクト: ywscr/morestachio
 /// <summary>
 ///		Creates a new Token Pair
 /// </summary>
 /// <param name="type"></param>
 /// <param name="value"></param>
 /// <param name="tokenLocation"></param>
 public TokenPair(IComparable type, string value, CharacterLocation tokenLocation)
 {
     Type          = type;
     Value         = value;
     TokenLocation = tokenLocation;
 }