public void Sort(int[][] array, Compare comparer) { if (comparer == null || array == null) throw new ArgumentNullException("Arguments can't be null."); QuickSort(array, 0, array.GetLength(0) - 1, comparer); }
public static int BinarySearch(Array items, object item, Compare compare) { int low = 0; int high = items.Length - 1; int test; int comparison; while (low <= high) { test = (low + high) >> 1; comparison = compare(items[test], item); if (comparison == 0) { return test; } if (comparison < 0) { low = test + 1; } else { high = test - 1; } } return -1; }
private int Partition(int[][] array, int leftBorder, int rightBorder, Compare comparer) { int pivotIndex = leftBorder + (rightBorder - leftBorder) / 2; int[] pivotValue = array[pivotIndex]; array[pivotIndex] = array[leftBorder]; int i = leftBorder + 1; int j = rightBorder; while (true) { while ((i < j) && (comparer(pivotValue, array[i]) > 0)) i++; while ((j >= i) && (comparer(array[j], pivotValue) > 0)) j--; if (i >= j) break; Swap(array, i, j); j--; i++; } array[leftBorder] = array[j]; array[j] = pivotValue; return j; }
public RamSearchEngine(Settings settings, Compare compareTo, long? compareValue, int? differentBy) : this(settings) { _compareTo = compareTo; _differentBy = differentBy; _compareValue = compareValue; }
private string BuildComparison(Compare comparison) { switch (comparison) { case Compare.Equals: return "="; case Compare.NotEquals: return "!="; case Compare.Like: return " LIKE "; case Compare.NotLike: return " NOT LIKE "; case Compare.GreaterThan: return ">"; case Compare.GreaterOrEquals: return ">="; case Compare.LessThan: return "<"; case Compare.LessOrEquals: return "<="; case Compare.In: return " IN "; case Compare.NotIn: return " NOT IN "; case Compare.Between: return " BETWEEN "; case Compare.IsNull: return " IS NULL"; case Compare.IsNotNull: return " IS NOT NULL"; default: throw new QueryBuilderException("Unknown comparison"); } }
public Condition(string field, Compare comparison, object argument) { Children = new List<Condition>(0); Concat = LogicOperator.And; Field = field; Comparison = comparison; Argument = argument; }
public static void Sort(this int[][] array, ISorter sorter, Compare comparator) { if (array == null) throw new NullReferenceException(); if (sorter == null || comparator == null) throw new ArgumentNullException(); sorter.Sort(array, comparator); }
public SortedSet(Compare compare, Array items, bool alreadySorted) { if (compare == null) throw new Exception("compare must be provided"); _compare = compare; _items = items ?? new Array(); if (!alreadySorted) _items.Sort((CompareCallback)(object)_compare); }
public OverwritePropertyRule(int propertyId, Compare compareOperator, OverwriteDialogResult result) { if (((result == OverwriteDialogResult.None) || (result == OverwriteDialogResult.Abort)) || (result == OverwriteDialogResult.Rename)) { throw new ArgumentException(); } this.PropertyId = propertyId; this.CompareOperator = compareOperator; this.OverwriteResult = result; }
private void QuickSort(Znak[] a, int L, int R, Compare w) { //метод сортування int i = L; int j = R;//ліва та права межі while (w(a[i], a[(L + R) / 2]) < 0) i++; while (w(a[j], a[(L + R) / 2]) > 0) j--; if (i <= j) { if (i < j) Swap(ref a[i], ref a[j]); i++; j--; } if (R > i) QuickSort(a, i, R, w); if (L < j) QuickSort(a, L, j, w); }
public static void BubbleSorter(int[] array, Compare comp) { for (int i = 0; i < array.Length; ++i) { for (int j = i + 1; j < array.Length; ++j) { if (comp(array[j], array[i])) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } } } }
private void QuickSort(int[][] array, int leftBorder, int rightBorder, Compare comparer) { while (leftBorder < rightBorder) { int m = Partition(array, leftBorder, rightBorder, comparer); if (m - leftBorder <= rightBorder - m) { QuickSort(array, leftBorder, m - 1, comparer); leftBorder = m + 1; } else { QuickSort(array, m + 1, rightBorder, comparer); rightBorder = m - 1; } } }
//метод Sort сортирует массив строк str в указанном порядке sorttype public static void Sort(string[] str, Compare sorttype) { int i, j, min; string buff; for (i = 0; i < str.Length - 1; i++) { min = i; for (j = i + 1; j < str.Length; j++) if (sorttype(str[min], str[j]) == 1) min = j; if (min != i) { buff = str[min]; str[min] = str[i]; str[i] = buff; } } }
public static void InsertionSortUp(int[][] arr, Compare compare) { int i, j; for (j = 1; j < arr.Length; j++) { int[] tempA = arr[j]; i = j; while ((i > 0) && (compare(arr[i - 1], tempA) == 1)) { arr[i] = arr[i - 1]; --i; } arr[i] = tempA; } }
/// <summary> /// Sort array by Shell alhoritm /// </summary> /// <param name="array">array of object for sorting</param> /// <param name="cmp">function for compare two elements</param> public static void Sort(Object[] array, Compare cmp) { int len = array.Length; int shift = 0; //count of steps in Shell alhoritm int steps = 4; //current step in Shell alhoritm int step = 1; //calculate initial shift shift = (int)Math.Pow(2, steps - 1); while (shift > 0) { for (int i = shift; i < len; i++) { Object temp = array[i]; int j; for (j = i - shift; (j >= 0) && cmp(array[j], temp) > 0; j -= shift) { //need to 'change' elements. Send event if (ElementsReplacing != null) { ReplaceEventArgs evArgs = new ReplaceEventArgs(); evArgs.left = array[j]; evArgs.right = array[j + shift]; ElementsReplacing(null, evArgs); } array[j + shift] = array[j]; } array[j + shift] = temp; } // Current step was finised. Send event. if (PartiallyDone != null) { PartialEventArgs evArgs = new PartialEventArgs(); evArgs.done = 100 * step / steps; PartiallyDone(null, evArgs); } step++; shift = shift >> 1; } }
public static ZCompareFunction MapFrom(Compare compare) { switch (compare) { case Compare.Always: return ZCompareFunction.Always; case Compare.GreaterEqual: return ZCompareFunction.GreaterEqual; case Compare.NotEqual: return ZCompareFunction.NotEqual; case Compare.Greater: return ZCompareFunction.Greater; case Compare.LessEqual: return ZCompareFunction.LessEqual; case Compare.Equal: return ZCompareFunction.Equal; case Compare.Less: return ZCompareFunction.Less; case Compare.Never: return ZCompareFunction.Never; default: throw new ArgumentOutOfRangeException("compare"); } }
public void Sort(T[] arr, Compare compare) { Array.Sort(arr, new Comparer(compare)); }
public static bool IsInBetween(Point2D point, Point2D point1, Point2D point2) => Compare.IsInBetween(point.X, point1.X, point2.X) && Compare.IsInBetween(point.Y, point1.Y, point2.Y);
public void SetUp() { _uut = new Compare(); }
public async Task <ActionResult <Basket> > UpdateBasket(Compare compare) { var updateBasket = await _compareRepository.UpdateCompare(compare); return(Ok(updateBasket)); }
public static void RegisterComparer(string extension, Compare compare) { Guard.AgainstNull(compare, nameof(compare)); Guard.AgainstBadExtension(extension, nameof(extension)); comparers[extension] = compare; }
/// <summary> /// This method executes a multi channel test. /// <see cref="ExecuteTest"/> /// </summary> /// <param name="channelContext">This parameter stores the channel related data.</param> /// <param name="testCaseContext">This parameter stores the test case parameter values.</param> /// <param name="testCase">This parameter stores the test case related data.</param> /// <param name="iteration">This parameter stores the current iteration number.</param> /// <remarks> /// The test parameters required for this test case are of the /// following types: /// <list type="bullet"> /// <item>MaxStringLength <see cref="TestCaseContext.MaxStringLength"/></item> /// <item>ChannelsPerServer <see cref="TestCaseContext.ChannelsPerServer"/></item> /// <item>ServerDetails <see cref="TestCaseContext.ServerDetails"/></item> /// </list> /// </remarks> private void ExecuteTest_MultipleChannels(ChannelContext channelContext, TestCaseContext testCaseContext, TestCase testCase, int iteration) { bool isSetupStep = TestUtils.IsSetupIteration(iteration); if (!isSetupStep) { channelContext.EventLogger.LogStartEvent(testCase, iteration); } else { channelContext.ClientSession.OperationTimeout = 30000; } RequestHeader requestHeader = new RequestHeader(); requestHeader.Timestamp = DateTime.UtcNow; requestHeader.ReturnDiagnostics = (uint)DiagnosticsMasks.All; Variant input; Variant output; Variant expectedOutput; ResponseHeader responseHeader; if (isSetupStep) { input = Variant.Null; responseHeader = channelContext.ClientSession.TestStack( requestHeader, testCase.TestId, iteration, input, out output); } else { channelContext.Random.Start( (int)(testCase.Seed + iteration), (int)m_sequenceToExecute.RandomDataStepSize, testCaseContext); input = channelContext.Random.GetScalarVariant(false); responseHeader = channelContext.ClientSession.TestStack( requestHeader, testCase.TestId, iteration, input, out output); channelContext.Random.Start( (int)(testCase.ResponseSeed + iteration), (int)m_sequenceToExecute.RandomDataStepSize, testCaseContext); expectedOutput = channelContext.Random.GetScalarVariant(false); if (!Compare.CompareVariant(output, expectedOutput)) { throw new ServiceResultException( StatusCodes.BadInvalidState, Utils.Format("'{0}' is not equal to '{1}'.", output, expectedOutput)); } } if (!isSetupStep) { channelContext.EventLogger.LogCompleteEvent(testCase, iteration); } }
internal TpItem Find(Compare function) { return items.FirstOrDefault(item => function(item)); }
/// <summary>Sorts an entire array in non-decreasing order using the quick sort algorithm.</summary> /// <typeparam name="T">The type of objects stored within the array.</typeparam> /// <param name="compare">The method of compare to be sorted by.</param> /// <param name="get">Delegate for getting a value at a specified index.</param> /// <param name="set">Delegate for setting a value at a specified index.</param> /// <param name="start">The starting index of the sort.</param> /// <param name="end">The ending index of the sort.</param> /// <remarks>Runtime: Omega(n*ln(n)), average(n*ln(n)), O(n^2). Memory: ln(n). Stablity: no.</remarks> public static void Quick <T>(Compare <T> compare, GetIndex <T> get, SetIndex <T> set, int start, int end) { Quick_Recursive(compare, get, set, start, end - start + 1); }
/// <summary>Sorts up to an array in non-decreasing order using the merge sort algorithm.</summary> /// <typeparam name="T">The type of objects stored within the array.</typeparam> /// <param name="compare">Returns zero or negative if the left is less than or equal to the right.</param> /// <param name="array">The array to be sorted</param> /// <remarks>Runtime: Omega(n*ln(n)), average(n*ln(n)), O(n*ln(n)). Memory: n. Stablity: yes.</remarks> public static void Merge <T>(Compare <T> compare, T[] array) { Merge(compare, array, 0, array.Length); }
public WorkQueue(Compare compare) : base(compare) {}
private TpItem Find(Compare function) { return _innerList.Find(function); }
public Skill_data(int anim_index, float anim_duration, float recording_duration, string anim_name, string display_name, string description_trial, Compare.Utilities.Properties.Activity compare_activity, Camera_view camera_view, Sport target_sport) { _anim_index = anim_index; _anim_duration = anim_duration; _recording_duration = recording_duration; _anim_name = anim_name; _display_name = display_name; _description_trial = description_trial; _compare_activity = compare_activity; _camera_view = camera_view; _target_sport = target_sport; _score = 0.0f; }
public void SelectItem(Compare function) { TpItem item = Find(function); if (item != null) { SelectItem(item, false); } }
public void Sort(Compare w, Znak[] mass)//метод який доступній зовні { this.QuickSort(mass, 0, mass.Length - 1, w);//сотрування }
/// <summary> /// Appends a new LEFT OUTER JOIN between this table and the specified table matching between this tables parentfield and the other tables child field /// </summary> /// <param name="tbl"></param> /// <param name="parent"></param> /// <param name="comp"></param> /// <param name="child"></param> /// <returns></returns> public DBJoin LeftJoin(DBTable tbl, DBClause parent, Compare comp, DBClause child) { DBComparison c = DBComparison.Compare(parent, comp, child); return(LeftJoin(tbl, c)); }
/// <summary>Sorts up to an array in non-decreasing order using the merge sort algorithm.</summary> /// <typeparam name="T">The type of objects stored within the array.</typeparam> /// <param name="compare">Returns zero or negative if the left is less than or equal to the right.</param> /// <param name="get">Delegate for getting a value at a specified index.</param> /// <param name="set">Delegate for setting a value at a specified index.</param> /// <param name="start">The starting index of the sort.</param> /// <param name="end">The ending index of the sort.</param> /// <remarks>Runtime: Omega(n*ln(n)), average(n*ln(n)), O(n*ln(n)). Memory: n. Stablity: yes.</remarks> public static void Merge <T>(Compare <T> compare, GetIndex <T> get, SetIndex <T> set, int start, int end) { Merge_Recursive(compare, get, set, start, end - start); }
private void AreEqual(float expected, float actual) => Assert.IsTrue( Compare.AlmostEqual(expected, actual), $"Expected {expected}, Actual {actual}");
/// <summary>Sorts an entire array in non-decreasing order using the heap sort algorithm.</summary> /// <typeparam name="T">The type of objects stored within the array.</typeparam> /// <param name="compare">The method of compare for the sort.</param> /// <param name="array">The array to be sorted</param> /// <remarks>Runtime: Omega(n*ln(n)), average(n*ln(n)), O(n^2). Memory: in place. Stablity: no.</remarks> public static void Heap <T>(Compare <T> compare, T[] array) { Heap(compare, array, 0, array.Length); }
public PriorityQueue(Compare comparer) { this.compare = comparer; }
/// <summary>Sorts an entire array in non-decreasing order using the odd-even sort algorithm.</summary> /// <typeparam name="T">The type of objects stored within the array.</typeparam> /// <param name="compare">The method of compare for the sort.</param> /// <param name="array">The array to be sorted</param> /// <remarks>Runtime: Omega(n), average(n^2), O(n^2). Memory: in place. Stablity: yes.</remarks> public static void OddEven <T>(Compare <T> compare, T[] array) { OddEven(compare, array, 0, array.Length); }
/// <summary> /// Decrypts a message /// </summary> /// /// <param name="Input">The message to decrypt</param> /// /// <returns>The decrypted message</returns> /// /// <exception cref="NTRUException">If not initialized, the specified hash algorithm is invalid, the encrypted data is invalid, or <c>MaxLenBytes</c> is greater than 255</exception> public byte[] Decrypt(byte[] Input) { if (!_isInitialized) { throw new NTRUException("NTRUEncrypt:Decrypt", "The cipher has not been initialized!", new InvalidOperationException()); } IPolynomial priv_t = ((NTRUPrivateKey)_keyPair.PrivateKey).T; IntegerPolynomial priv_fp = ((NTRUPrivateKey)_keyPair.PrivateKey).FP; IntegerPolynomial pub = ((NTRUPublicKey)_keyPair.PublicKey).H; int N = _encParams.N; int q = _encParams.Q; int db = _encParams.Db; int maxMsgLenBytes = _encParams.MaxMsgLenBytes; int dm0 = _encParams.Dm0; int maxM1 = _encParams.MaxM1; int minCallsMask = _encParams.MinMGFHashCalls; bool hashSeed = _encParams.HashSeed; int bLen = db / 8; IntegerPolynomial e = IntegerPolynomial.FromBinary(Input, N, q); IntegerPolynomial ci = Decrypt(e, priv_t, priv_fp); if (ci.Count(-1) < dm0) { throw new NTRUException("NTRUEncrypt:Decrypt", "Less than dm0 coefficients equal -1", new InvalidDataException()); } if (ci.Count(0) < dm0) { throw new NTRUException("NTRUEncrypt:Decrypt", "Less than dm0 coefficients equal 0", new InvalidDataException()); } if (ci.Count(1) < dm0) { throw new NTRUException("NTRUEncrypt:Decrypt", "Less than dm0 coefficients equal 1", new InvalidDataException()); } //if (maxMsgLenBytes > 255) // throw new NTRUException("NTRUEncrypt:Decrypt", "maxMsgLenBytes values bigger than 255 are not supported", new ArgumentOutOfRangeException()); IntegerPolynomial cR = e; cR.Subtract(ci); cR.ModPositive(q); byte[] coR4 = cR.ToBinary4(); IntegerPolynomial mask = MGF(coR4, N, minCallsMask, hashSeed); IntegerPolynomial cMTrin = ci; cMTrin.Subtract(mask); cMTrin.Mod3(); byte[] cb, p0, cm; using (BinaryReader reader = new BinaryReader(new MemoryStream(cMTrin.ToBinary3Sves(maxM1 > 0)))) { cb = new byte[bLen]; reader.Read(cb, 0, cb.Length); // llen=1, so read one byte int cl = reader.ReadByte() & 0xFF; if (cl > maxMsgLenBytes) { throw new NTRUException("NTRUEncrypt:Decrypt", string.Format("Message too long: {0} > {1}!", cl, maxMsgLenBytes), new InvalidDataException()); } cm = new byte[cl]; reader.Read(cm, 0, cm.Length); p0 = new byte[reader.BaseStream.Length - reader.BaseStream.Position]; reader.Read(p0, 0, p0.Length); } if (!Compare.AreEqual(p0, new byte[p0.Length])) { throw new NTRUException("NTRUEncrypt:Decrypt", "The message is not followed by zeroes!", new InvalidDataException()); } byte[] sData = GetSeed(cm, pub, cb); IPolynomial cr = GenerateBlindingPoly(sData); IntegerPolynomial cRPrime = cr.Multiply(pub); cRPrime.ModPositive(q); if (!cRPrime.Equals(cR)) { throw new NTRUException("NTRUEncrypt:Decrypt", "Invalid message encoding!", new InvalidDataException()); } return(cm); }
/// <summary>Sorts an entire array in non-decreasing order using the slow sort algorithm.</summary> /// <typeparam name="T">The type of objects stored within the array.</typeparam> /// <param name="compare">The method of compare for the sort.</param> /// <param name="array">The array to be sorted.</param> /// <remarks>Runtime: Omega(n), average(n*n!), O(infinity). Memory: in place. Stablity: no.</remarks> public static void Bogo <T>(Compare <T> compare, T[] array) { Bogo(compare, array, 0, array.Length - 1); }
public AddItemData AddItemToDB(AddItem ItemAddItemData) { Object PlayerObjectData; TransactionData Tran; AddItemData Result; Result = new AddItemData() { Status = false }; var _db = new PangyaEntities(); var additem = _db.ProcAddItem((int)UID, (int)ItemAddItemData.ItemIffId, (int)ItemAddItemData.Quantity, Compare.IfCompare <byte>(IFFEntry.GetIff.IsSelfDesign(ItemAddItemData.ItemIffId), 1, 0), IFFEntry.GetIff.GetItemTimeFlag(ItemAddItemData.ItemIffId, ItemAddItemData.Day), (int)ItemAddItemData.Day).ToList(); if (additem.Count > 0) { var dbdata = additem.FirstOrDefault(); Tran = new TransactionData() { Types = 2, Index = (uint)dbdata.IDX, TypeID = (uint)dbdata.iffTypeId, PreviousQuan = 0, NewQuan = (uint)dbdata.Quantity, UCC = dbdata.UCC_KEY }; ItemTransaction.Add(Tran); try { switch (ItemAddItemData.ItemIffId.GetItemGroup()) { case IffGroupFlag.ITEM_TYPE_CHARACTER: { PlayerObjectData = new CharacterData(); ((CharacterData)(PlayerObjectData)).Index = (uint)dbdata.IDX; ((CharacterData)(PlayerObjectData)).TypeID = (uint)dbdata.iffTypeId; ((CharacterData)(PlayerObjectData)).HairColour = 0; ((CharacterData)(PlayerObjectData)).GiftFlag = 0; ItemCharacter.CharacterAdd((CharacterData)(PlayerObjectData)); CharacterIndex = (uint)dbdata.IDX; Result = new AddItemData() { Status = true, ItemIndex = ((CharacterData)(PlayerObjectData)).Index, ItemTypeID = ((CharacterData)(PlayerObjectData)).TypeID, ItemOldQty = 1, ItemNewQty = 1, ItemUCCKey = string.Empty, ItemFlag = 0, ItemEndDate = DateTime.MinValue, }; } break; case IffGroupFlag.ITEM_TYPE_AUX: case IffGroupFlag.ITEM_TYPE_PART: case IffGroupFlag.ITEM_TYPE_CLUB: case IffGroupFlag.ITEM_TYPE_BALL: case IffGroupFlag.ITEM_TYPE_USE: case IffGroupFlag.ITEM_TYPE_SKIN: { PlayerObjectData = new WarehouseData(); ((WarehouseData)(PlayerObjectData)).ItemIndex = (uint)dbdata.IDX; ((WarehouseData)(PlayerObjectData)).ItemTypeID = (uint)dbdata.iffTypeId; ((WarehouseData)(PlayerObjectData)).ItemC0 = (ushort)dbdata.Quantity; ((WarehouseData)(PlayerObjectData)).ItemUCCUnique = dbdata.UCC_KEY; ((WarehouseData)(PlayerObjectData)).CreateNewItem(); // Add to inventory list ItemWarehouse.ItemAdd((WarehouseData)(PlayerObjectData)); // Set the result data Result = new AddItemData() { Status = true, ItemIndex = ((WarehouseData)(PlayerObjectData)).ItemIndex, ItemTypeID = ((WarehouseData)(PlayerObjectData)).ItemTypeID, ItemOldQty = 0, ItemNewQty = ItemAddItemData.Quantity, ItemUCCKey = ((WarehouseData)(PlayerObjectData)).ItemUCCUnique, ItemFlag = 0, ItemEndDate = null, }; } break; case IffGroupFlag.ITEM_TYPE_CADDIE: { PlayerObjectData = new CaddieData(); ((CaddieData)(PlayerObjectData)).CaddieIdx = (uint)dbdata.IDX; ((CaddieData)(PlayerObjectData)).CaddieTypeId = (uint)dbdata.iffTypeId; ((CaddieData)(PlayerObjectData)).CaddieDateEnd = (DateTime)dbdata.END_DATE; ((CaddieData)(PlayerObjectData)).CaddieAutoPay = 0; ((CaddieData)(PlayerObjectData)).CaddieType = (byte)dbdata.Flag; // Add caddie to inventory list ItemCaddie.CadieAdd((CaddieData)(PlayerObjectData)); // set the result data Result = new AddItemData() { Status = true, ItemIndex = ((CaddieData)(PlayerObjectData)).CaddieIdx, ItemTypeID = ((CaddieData)(PlayerObjectData)).CaddieTypeId, ItemOldQty = 0, ItemNewQty = 1, ItemUCCKey = string.Empty, ItemFlag = ((CaddieData)(PlayerObjectData)).CaddieType, ItemEndDate = null, }; } break; case IffGroupFlag.ITEM_TYPE_CARD: { PlayerObjectData = new CardData(); ((CardData)(PlayerObjectData)).CardIndex = (uint)dbdata.IDX; ((CardData)(PlayerObjectData)).CardTypeID = (uint)dbdata.iffTypeId; ((CardData)(PlayerObjectData)).CardQuantity = ItemAddItemData.Quantity; ((CardData)(PlayerObjectData)).CardIsValid = 1; ((CardData)(PlayerObjectData)).CardNeedUpdate = false; // ## add to card ItemCard.CardAdd((CardData)(PlayerObjectData)); // set the result data Result = new AddItemData() { Status = true, ItemIndex = ((CardData)(PlayerObjectData)).CardIndex, ItemTypeID = ((CardData)(PlayerObjectData)).CardTypeID, ItemOldQty = 0, ItemNewQty = ((CardData)(PlayerObjectData)).CardQuantity, ItemUCCKey = string.Empty, ItemFlag = 0, ItemEndDate = null, }; } break; case IffGroupFlag.ITEM_TYPE_MASCOT: { PlayerObjectData = new MascotData(); ((MascotData)(PlayerObjectData)).MascotIndex = (uint)dbdata.IDX; ((MascotData)(PlayerObjectData)).MascotTypeID = (uint)dbdata.iffTypeId; ((MascotData)(PlayerObjectData)).MascotMessage = "Pangya !"; ((MascotData)(PlayerObjectData)).MascotIsValid = 1; ((MascotData)(PlayerObjectData)).MascotNeedUpdate = false; ((MascotData)(PlayerObjectData)).MascotEndDate = (DateTime)dbdata.END_DATE; ((MascotData)(PlayerObjectData)).MascotDayToEnd = (ushort)dbdata.END_DATE.DaysBetween(DateTime.Now); // ## add to card ItemMascot.MascotAdd((MascotData)(PlayerObjectData)); // set the result data Result = new AddItemData() { Status = true, ItemIndex = ((MascotData)(PlayerObjectData)).MascotIndex, ItemTypeID = ((MascotData)(PlayerObjectData)).MascotTypeID, ItemOldQty = 0, ItemNewQty = 1, ItemUCCKey = string.Empty, ItemFlag = 4, ItemEndDate = DateTime.Now.AddDays(ItemAddItemData.Day + 1), }; } break; } } catch { } } // ## resulted return(Result); }
/// <summary>Sorts an entire array in non-decreasing order using the selection sort algoritm.</summary> /// <typeparam name="T">The type of objects stored within the array.</typeparam> /// <param name="compare">Returns negative if the left is less than the right.</param> /// <param name="array">the array to be sorted</param> /// <remarks>Runtime: Omega(n^2), average(n^2), O(n^2). Memory: in place. Stablity: no.</remarks> public static void Selection <T>(Compare <T> compare, T[] array) { Selection(compare, array, 0, array.Length - 1); }
public static void Main(string[] args) { DicConsole.WriteLineEvent += System.Console.WriteLine; DicConsole.WriteEvent += System.Console.Write; DicConsole.ErrorWriteLineEvent += System.Console.Error.WriteLine; Settings.Settings.LoadSettings(); if (Settings.Settings.Current.GdprCompliance < DicSettings.GdprLevel) { Configure.DoConfigure(true); } Statistics.LoadStats(); if (Settings.Settings.Current.Stats != null && Settings.Settings.Current.Stats.ShareStats) { Statistics.SubmitStats(); } Parser.Default.ParseArguments(args, typeof(AnalyzeOptions), typeof(BenchmarkOptions), typeof(ChecksumOptions), typeof(CompareOptions), typeof(ConfigureOptions), typeof(ConvertImageOptions), typeof(CreateSidecarOptions), typeof(DecodeOptions), typeof(DeviceInfoOptions), typeof(DeviceReportOptions), typeof(DumpMediaOptions), typeof(EntropyOptions), typeof(ExtractFilesOptions), typeof(FormatsOptions), typeof(ImageInfoOptions), typeof(ListDevicesOptions), typeof(ListEncodingsOptions), typeof(ListOptionsOptions), typeof(LsOptions), typeof(MediaInfoOptions), typeof(MediaScanOptions), typeof(PrintHexOptions), typeof(StatsOptions), typeof(VerifyOptions), typeof(GuiOptions)) .WithParsed <AnalyzeOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Analyze.DoAnalyze(opts); }).WithParsed <CompareOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Compare.DoCompare(opts); }).WithParsed <ChecksumOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Checksum.DoChecksum(opts); }).WithParsed <EntropyOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Entropy.DoEntropy(opts); }).WithParsed <VerifyOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Verify.DoVerify(opts); }).WithParsed <PrintHexOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Commands.PrintHex.DoPrintHex(opts); }).WithParsed <DecodeOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Decode.DoDecode(opts); }).WithParsed <DeviceInfoOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); DeviceInfo.DoDeviceInfo(opts); }).WithParsed <MediaInfoOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); MediaInfo.DoMediaInfo(opts); }).WithParsed <MediaScanOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); MediaScan.DoMediaScan(opts); }).WithParsed <FormatsOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Formats.ListFormats(opts); }).WithParsed <BenchmarkOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Benchmark.DoBenchmark(opts); }).WithParsed <CreateSidecarOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); CreateSidecar.DoSidecar(opts); }).WithParsed <DumpMediaOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); DumpMedia.DoDumpMedia(opts); }).WithParsed <DeviceReportOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); DeviceReport.DoDeviceReport(opts); }).WithParsed <LsOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Ls.DoLs(opts); }).WithParsed <ExtractFilesOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); ExtractFiles.DoExtractFiles(opts); }).WithParsed <ListDevicesOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); ListDevices.DoListDevices(opts); }).WithParsed <ListEncodingsOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); ListEncodings.DoList(); }).WithParsed <ListOptionsOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); ListOptions.DoList(); }).WithParsed <ConvertImageOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); ConvertImage.DoConvert(opts); }).WithParsed <ImageInfoOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); ImageInfo.GetImageInfo(opts); }).WithParsed <ConfigureOptions>(opts => { PrintCopyright(); Configure.DoConfigure(false); }).WithParsed <StatsOptions>(opts => { PrintCopyright(); Commands.Statistics.ShowStats(); }).WithParsed <GuiOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } new Application(Platform.Detect).Run(new frmMain(opts.Debug, opts.Verbose)); }).WithNotParsed(errs => Environment.Exit(1)); Statistics.SaveStats(); }
static void Main(string[] args) { Object[] array; int arraySize = 100; array = new Object[arraySize]; Console.WriteLine("Original array"); //fill array for (int i = 0; i < arraySize; i++) { array[i] = new Hardware(); Console.WriteLine(array[i]); } //preparing to sorting Compare cmp = new Compare(HardwareCompare); ShellSort.PartiallyDone += PartiallyDone; ShellSort.ElementsReplacing += ElementReplacing; //sort it ShellSort.Sort(array, cmp); //Print results Console.WriteLine("\nSorted array"); for (int i = 0; i < arraySize; i++) { Console.WriteLine(array[i]); } Console.WriteLine("{0} replacing were made", replacingCount); }
/// <summary> /// Inputs and parses the variable of type T. /// </summary> /// <returns>Variable of type T.</returns> /// <param name="input">Input.</param> /// <param name="minValue">Minimum value.</param> /// <param name="maxValue">Maximum value.</param> /// <param name="compMin">Comparator for minValue.</param> /// <param name="compMax">Comparator for maxValue.</param> static T InputVar <T>(string input, T minValue, T maxValue, Compare <T> compMin, Compare <T> compMax) { Console.WriteLine($"Enter {input}:"); T result; while (!ParseInput(Console.ReadLine(), out result) || compMin(result, minValue) || compMax(result, maxValue)) { Console.WriteLine("Invalid input format! Try again!"); Console.WriteLine($"Enter {input}:"); } return(result); }
public DBUpdateQuery WhereField(string field, Compare op, DBClause value) { DBField fld = DBField.Field(field); return(Where(fld, op, value)); }
public Comparer(Compare compare) { this.compare = compare; }
public DBUpdateQuery WhereField(string fieldOwner, string fieldTable, string fieldName, Compare op, DBClause value) { DBField fld = DBField.Field(fieldOwner, fieldTable, fieldName); return(Where(fld, op, value)); }
public CompareResult Do(int a, int b) => Compare.Wrap(a.CompareTo(b));
public ISelectWhere Where(string field, Compare comparison, object argument) { var cnd = new Condition(field, comparison, argument); return ((ISelectFrom)this).Where(cnd); }
public static IEnumerable <T> DistinctBy <T, TIdentity>(this IEnumerable <T> source, Func <T, TIdentity> identitySelector) { return(source.Distinct(Compare.By(identitySelector))); }
private bool CanDoCompareType(Compare compareType) { switch (_settings.Mode) { default: case Settings.SearchMode.Detailed: return true; case Settings.SearchMode.Fast: return compareType != Compare.Changes; } }
/// <summary> /// This method executes a multi channel test. /// </summary> /// <param name="testCaseContext">This parameter stores the test case parameter values.</param> /// <param name="testCase">This parameter stores the test case related data.</param> /// <param name="iteration">This parameter stores the current iteration number.</param> /// <param name="input">Input value.</param> /// <returns>Input variant.</returns> /// <remarks> /// The test parameters required for this test case are of the /// following types: /// <list type="bullet"> /// <item>MaxStringLength <see cref="TestCaseContext.MaxStringLength"/></item> /// <item>ChannelsPerServer <see cref="TestCaseContext.ChannelsPerServer"/></item> /// <item>ServerDetails <see cref="TestCaseContext.ServerDetails"/></item> /// </list> /// </remarks> private Variant ExecuteTest_MultipleChannels(TestCaseContext testCaseContext, TestCase testCase, int iteration, Variant input) { bool isSetupStep = TestUtils.IsSetupIteration(iteration); if (!isSetupStep) { m_logger.LogStartEvent(testCase, iteration); } try { if (isSetupStep) { // No verification for the input is required. return(Variant.Null); } else { Variant expectedInput; lock (m_random) { m_random.Start( (int)(testCase.Seed + iteration), (int)m_sequenceToExecute.RandomDataStepSize, testCaseContext); expectedInput = m_random.GetScalarVariant(false); } try { if (!Compare.CompareVariant(input, expectedInput)) { throw new ServiceResultException( StatusCodes.BadInvalidState, Utils.Format("'{0}' is not equal to '{1}'.", input, expectedInput)); } } catch (Exception e) { throw ServiceResultException.Create( StatusCodes.BadInvalidState, e, "'{0}' is not equal to '{1}'.", input, expectedInput); } lock (m_random) { m_random.Start((int)( testCase.ResponseSeed + iteration), (int)m_sequenceToExecute.RandomDataStepSize, testCaseContext); return(m_random.GetScalarVariant(false)); } } } finally { if (!isSetupStep) { m_logger.LogCompleteEvent(testCase, iteration); } } }
internal void LoadTextures( Device device ) { string path = GetTextureFileName( baseTextureName ); if( path != null ) { try { ImageInformation info = new ImageInformation(); diffuse = TextureLoader.FromFile( device, path, 0, 0, 0, Usage.None, Format.Unknown, Pool.Managed, Filter.Triangle, Filter.Triangle, 0, ref info ); switch( info.Format ) { case Format.A8R8G8B8: case Format.A8B8G8R8: alphaTest = Compare.Greater; alphaRef = 127; cullMode = Cull.None; break; } } catch( IOException ) { return; } } string normPath = GetTextureFileName( Path.ChangeExtension( baseTextureName, null ) + "_n.tga" ); if( normPath != null ) { try { normal = TextureLoader.FromFile( device, normPath, 0, 0, 0, Usage.None, Format.A8B8G8R8, Pool.Managed, Filter.Triangle, Filter.None, 0 ); Helpers.GenerateNormalMapMips( normal ); } catch( IOException ) { } } }
public void Sort(Compare w, Znak[] mass) //метод який доступній зовні { this.QuickSort(mass, 0, mass.Length - 1, w); //сотрування }
static RangeCollection() { _comparer = new Compare(); }
private static void RunQuery(ClarizenUtils utils, string csvReadFile, string targetType) { using (var csv = new CsvParser(new StreamReader(csvReadFile))) { int rowIndex = 0; while (csv.ReadNextRecord()) { var conditions = new List<Compare>(); foreach (string field in csv.HeaderFields) { if (string.IsNullOrEmpty(csv.CurrentDic[field])) continue; var condition = new Compare { LeftExpression = new FieldExpression {FieldName = field}, Operator = Operator.Equal, RightExpression = new ConstantExpression { Value = ParseValue(csv.CurrentDic[field], field) } }; conditions.Add(condition); } var qry = new EntityQuery { TypeName = targetType, Where = GetWhereCondition(conditions), Fields = GetFieldsNames(utils.GetMetaDataFields(targetType).Fields) }; QueryResult queryResult = utils.RunQuery(qry); if (!queryResult.Success) continue; string dir = Path.GetDirectoryName(csvReadFile); if (dir == null) throw new ArgumentNullException("csvReadFile"); dir = Path.Combine(dir, "Handled"); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); string resultFileName = Path.Combine(dir, string.Format("{0}_Result_{1}.csv", Path.GetFileNameWithoutExtension(csvReadFile), rowIndex)); string heder = string.Empty; string result = string.Empty; string combineText; if (queryResult.Entities.Length == 0) { combineText = "No Results"; } else { for (int i = 0; i < queryResult.Entities.Length; i++) { foreach (FieldValue val in ((GenericEntity) queryResult.Entities[i]).Values) { if (i == 0) heder += val.FieldName + ","; if (val.Value == null || val.Value.GetType() == typeof (GenericEntity)) result += ","; else if (val.Value.GetType() == typeof (Money)) result += ((Money) val.Value).Value + " (" + ((Money) val.Value).Currency + "),"; else if (val.Value.GetType() == typeof (Duration)) result += ((Duration) val.Value).Value + " (" + ((Duration) val.Value).Unit + "),"; else result += ClearNewLine(val.Value.ToString()) + ","; } if ((i + 1) < queryResult.Entities.Length) result += "\r\n"; } combineText = heder + "\r\n" + result; } File.WriteAllText(resultFileName, combineText); rowIndex++; } } string p = Path.GetDirectoryName(csvReadFile); string d = Path.GetFileName(csvReadFile); if (p != null) { if (d != null) { string destFileName = Path.Combine(Path.Combine(p, "Handled"), d); if (File.Exists(destFileName)) File.Delete(destFileName); File.Move(csvReadFile, destFileName); } } }
public void Sort(int[][] array, Compare comparator) { BubbleSort(array); }
private string Write197_Compare(Compare v) { switch (v) { case Compare.Always: return "Always"; case Compare.Equal: return "Equal"; case Compare.Greater: return "Greater"; case Compare.GreaterEqual: return "GreaterEqual"; case Compare.Less: return "Less"; case Compare.LessEqual: return "LessEqual"; case Compare.Never: return "Never"; case Compare.NotEqual: return "NotEqual"; } long num = (long) v; throw base.CreateInvalidEnumValueException(num.ToString(CultureInfo.InvariantCulture), "Nomad.Workers.Compare"); }
static async Task <CompareResult> DoCompare(VerifySettings settings, string first, string second, Compare compare) { #if NETSTANDARD2_1 await using var fs1 = FileHelpers.OpenRead(first); await using var fs2 = FileHelpers.OpenRead(second); #else using var fs1 = FileHelpers.OpenRead(first); using var fs2 = FileHelpers.OpenRead(second); #endif return(await compare(settings, fs1, fs2)); }
/// <summary> /// Authentication tests; specific target domain or identity, passphrase, /// and export permissions within the PackageKey key policy settings are checked /// </summary> /// /// <returns>Authorized to use this key</returns> public KeyScope Authenticate() { try { // get the key headers m_keyPackage = GetPackage(); // store the master policy flag KeyPolicy = m_keyPackage.KeyPolicy; // did we create this key IsCreator = Compare.IsEqual(m_keyOwner.OriginId, m_keyPackage.Authority.OriginId); // key made by master auth, valid only if authenticated by PackageAuth, IdentityRestrict or DomainRestrict if (PackageKey.KeyHasPolicy(KeyPolicy, (long)KeyPolicies.MasterAuth)) { if (Compare.IsEqual(m_keyOwner.DomainId, m_keyPackage.Authority.DomainId)) { LastError = ""; return(KeyScope.Creator); } else if (Compare.IsEqual(m_keyOwner.PackageId, m_keyPackage.Authority.PackageId)) { LastError = ""; return(KeyScope.Creator); } else if (Compare.IsEqual(m_keyOwner.TargetId, m_keyPackage.Authority.TargetId)) { LastError = ""; return(KeyScope.Creator); } } // the key targets a specific installation identity if (PackageKey.KeyHasPolicy(KeyPolicy, (long)KeyPolicies.IdentityRestrict)) { // test only if not creator if (!Compare.IsEqual(m_keyOwner.OriginId, m_keyPackage.Authority.OriginId)) { // owner target field is set as a target OriginId hash if (!Compare.IsEqual(m_keyOwner.TargetId, m_keyPackage.Authority.TargetId)) { LastError = "You are not the intendant recipient of this key! Access is denied."; return(KeyScope.NoAccess); } } } if (PackageKey.KeyHasPolicy(KeyPolicy, (long)KeyPolicies.DomainRestrict)) { // the key is domain restricted if (!Compare.IsEqual(m_keyOwner.DomainId, m_keyPackage.Authority.DomainId)) { LastError = "Domain identification check has failed! You must be a member of the same Domain as the Creator of this key."; return(KeyScope.NoAccess); } } // the key package id is an authentication passphrase hash if (PackageKey.KeyHasPolicy(KeyPolicy, (long)KeyPolicies.PackageAuth)) { if (!Compare.IsEqual(m_keyOwner.PackageId, m_keyPackage.Authority.PackageId)) { LastError = "Key Package authentication has failed! Access is denied."; return(KeyScope.NoAccess); } } // test for volatile flag if (PackageKey.KeyHasPolicy(KeyPolicy, (long)KeyPolicies.Volatile)) { if (m_keyPackage.Authority.OptionFlag != 0 && m_keyPackage.Authority.OptionFlag < DateTime.Now.Ticks) { LastError = "This key has expired and can no longer be used! Access is denied."; return(KeyScope.NoAccess); } } // only the key creator is allowed access if (PackageKey.KeyHasPolicy(KeyPolicy, (long)KeyPolicies.NoExport)) { if (!Compare.IsEqual(m_keyOwner.OriginId, m_keyPackage.Authority.OriginId)) { LastError = "Only the Creator of this key is authorized! Access is denied."; return(KeyScope.NoAccess); } } LastError = ""; return(IsCreator ? KeyScope.Creator : KeyScope.Operator); } catch (Exception Ex) { LastError = Ex.Message; return(KeyScope.NoAccess); } }
private TpItem Find(Compare function) { return(_innerList.Find(function)); }