internal void MergeDictionaries <K, V, NV>(Reducer <K, V, NV> reducer, IDictionary from) { if (from.GetType() != ReduceResult.GetType()) { return; } IDictionary <K, NV> fromtyped = ((IDictionary <K, NV>)from); foreach (var kv in fromtyped) { if (kv.Value is IEnumerable) { foreach (var subitem in kv.Value as IEnumerable) { int pos = ((CustomDictionary <K, NV>)ReduceResult).InitOrGetPosition((K)kv.Key); NV value = ((CustomDictionary <K, NV>)ReduceResult).GetAtPosition(pos); NV newvalue = reducer.Reduce((K)kv.Key, (V)subitem, value); ((CustomDictionary <K, NV>)ReduceResult).StoreAtPosition(pos, newvalue); } } else { int pos = ((CustomDictionary <K, NV>)ReduceResult).InitOrGetPosition((K)kv.Key); NV value = ((CustomDictionary <K, NV>)ReduceResult).GetAtPosition(pos); NV newvalue = reducer.Reduce(kv.Key, (V)(object)kv.Value, value); ((CustomDictionary <K, NV>)ReduceResult).StoreAtPosition(pos, newvalue); } } from.Clear(); }
internal void MergeDictionaries <TK, TV, TNv>(Reducer <TK, TV, TNv> reducer, IDictionary from) { if (from.GetType() != ReduceResult.GetType()) { return; } var fromtyped = ((IDictionary <TK, TNv>)from); foreach (var kv in fromtyped) { if (kv.Value is IEnumerable) { foreach (var subitem in kv.Value as IEnumerable) { var pos = ((CustomDictionary <TK, TNv>)ReduceResult).InitOrGetPosition((TK)kv.Key); var value = ((CustomDictionary <TK, TNv>)ReduceResult).GetAtPosition(pos); var newvalue = reducer.Reduce((TK)kv.Key, (TV)subitem, value); ((CustomDictionary <TK, TNv>)ReduceResult).StoreAtPosition(pos, newvalue); } } else { var pos = ((CustomDictionary <TK, TNv>)ReduceResult).InitOrGetPosition((TK)kv.Key); var value = ((CustomDictionary <TK, TNv>)ReduceResult).GetAtPosition(pos); var newvalue = reducer.Reduce(kv.Key, (TV)(object)kv.Value, value); ((CustomDictionary <TK, TNv>)ReduceResult).StoreAtPosition(pos, newvalue); } } from.Clear(); }
public JpegReduceResult(ReduceResult baseResult) { inputPath = baseResult.inputPath; outputPath = baseResult.outputPath; isErrorEncountered = baseResult.isErrorEncountered; remarks = baseResult.remarks; jpegQualityFactor = _jpegQualityFactor; transformMode = _transformMode; }
private void Aggregate(ReduceResult result) { foreach (var key in result.Result.Keys) { if (totalResult.Result.ContainsKey(key)) { totalResult.Result[key] += result.Result[key]; } else { totalResult.Result[key] = result.Result[key]; } } Console.WriteLine("Aggregator: {0}", totalResult); // simulate some runtime... // Thread.Sleep(50); Sender.Tell(totalResult); }
/// <summary>Reduces hidden singles.</summary> /// <remarks> /// Very frequently, there is only one candidate for a given row, column or /// sub square, but it is hidden among other candidates. /// </remarks> private ReduceResult ReduceHiddenSingles(ReduceResult result, SudokuState state) { if (SkipMethod(SudokuSolverMethods.HiddenSingles, result)) { return result; } foreach (var region in Puzzle.Regions) { foreach (var singleValue in Puzzle.SingleValues) { var cnt = 0; var found = -1; foreach (var index in region) { var val = state[index]; if ((val & singleValue) != SudokuPuzzle.Invalid) { unchecked { cnt++; } if (state.IsKnown(index)) { found = -1; break; } else if (cnt == 1) { found = index; } } } if (cnt == 1 && found != -1) { result |= state.AndMask(found, singleValue); } else if (cnt == 0) { return ReduceResult.Inconsistend; } } } return result; }
private void Reduce(MapResult mapResult) { var reduceResult = new ReduceResult(); foreach (var count in mapResult.Counts) { if (reduceResult.Result.ContainsKey(count.Key)) { reduceResult.Result[count.Key] += count.Count; } else { reduceResult.Result[count.Key] = count.Count; } } Console.WriteLine("Reducer [{0}/{1}]: {2}", Self.Path.Name, Thread.CurrentThread.ManagedThreadId, reduceResult); // simulate some runtime... Thread.Sleep(50); Sender.Tell(reduceResult); }
/// <summary>Returns true if the result is inconsistent.</summary> public static bool IsInconsistent(this ReduceResult result) => (result & ReduceResult.Inconsistent) != 0;
/// <summary> /// <para>从指定的表标识对应的实体开始进行路径展开。</para> /// <para>注:展开过程包括对父实体的属性集的搜索。</para> /// </summary> /// <param name="table">指定的进行展开的起点。</param> /// <param name="path">指定要展开的成员路径,支持多级导航属性路径。</param> /// <param name="step">指定路径中每个属性的展开回调函数。</param> /// <returns>返回找到的结果。</returns> public static ReduceResult Reduce(this TableIdentifier table, string path, Func <ReduceContext, ISource> step = null) { if (table == null) { throw new ArgumentNullException(nameof(table)); } if (table.Entity == null) { throw new DataException($"The '{table}' table cannot be expanded."); } if (string.IsNullOrEmpty(path)) { return(ReduceResult.Failure(table)); } ICollection <IEntityMetadata> ancestors = null; IEntityPropertyMetadata property = null; ISource token = table; var parts = path.Split('.'); var properties = table.Entity.Properties; for (int i = 0; i < parts.Length; i++) { if (properties == null) { return(ReduceResult.Failure(token)); } //如果当前属性集合中不包含指定的属性,则尝试从父实体中查找 if (!properties.TryGet(parts[i], out property)) { //尝试从父实体中查找指定的属性 property = FindBaseProperty(ref properties, parts[i], ref ancestors); //如果父实体中也不含指定的属性则返回失败 if (property == null) { return(ReduceResult.Failure(token)); } } //如果回调函数不为空,则调用匹配回调函数 //注意:将回调函数返回的结果作为下一次的用户数据保存起来 if (step != null) { token = step(new ReduceContext(string.Join(".", parts, 0, i), token, property, ancestors)); } //清空继承实体链 if (ancestors != null) { ancestors.Clear(); } if (property.IsSimplex) { break; } else { properties = GetAssociatedProperties((IEntityComplexPropertyMetadata)property, ref ancestors); } } //返回查找到的结果 return(new ReduceResult(token, property)); }
/// <summary>Reduces options that should be in the intersection.</summary> private ReduceResult ReduceLockedCandidates(ReduceResult result, SudokuState state) { if (SkipMethod(SudokuSolverMethods.LockedCandidates, result)) { return result; } foreach (var region in Puzzle.Regions) { foreach (var other in region.Intersected) { ulong combined = 0; foreach (var index in region) { if (!other.Contains(index)) { combined |= state[index]; } } // There are options that should be in the intersection. if (combined != Puzzle.Unknown) { foreach (var index in other) { if (!region.Contains(index)) { var val = state[index]; var nw = val & combined; result |= state.AndMask(index, nw); } } } } } return result; }
/// <summary>Reduces naked triples.</summary> private ReduceResult ReduceNakedTriples(ReduceResult result, SudokuState state) { if (SkipMethod(SudokuSolverMethods.NakedTriples, result)) { return result; } foreach (var singleValue in Puzzle.SingleValues) { foreach (var region in Puzzle.Regions) { var index0 = -1; var index1 = -1; var index2 = -1; var match = singleValue; foreach (var index in region) { var value = state[index]; if (!state.IsKnown(index) && (value & match) != SudokuPuzzle.Invalid) { match |= value; /**/ if (index0 == -1) { index0 = index; } else if (index1 == -1) { index1 = index; } else if (index2 == -1) { index2 = index; } else { index2 = -1; break; } } } // We found 3 cells. if (index2 != -1 && SudokuCell.Count(match) == 3) { foreach (var index in region) { if (index != index0 && index != index1 && index != index2) { result |= state.AndMask(index, ~match); } } } } } return result; }
private void backgroundWorker_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e) { // Interpret results ReduceResult latestResult = (ReduceResult)e.UserState; long inputFileLength = 0; if (File.Exists(latestResult.inputPath)) { inputFileLength = new FileInfo(latestResult.inputPath).Length; } long outputFileLength = 0; if (File.Exists(latestResult.outputPath)) { outputFileLength = new FileInfo(latestResult.outputPath).Length; } long savingsBytes = 0; if (0 != inputFileLength && 0 != outputFileLength) { savingsBytes = inputFileLength - outputFileLength; } double savingsPercentage = 0; if (0 != inputFileLength) { savingsPercentage = (double)savingsBytes / inputFileLength; } String savingsPercentageString = String.Format("{1} ({0:0 %})", savingsPercentage, DisplayFileSize(savingsBytes)); String outputFileLengthString = DisplayFileSize(outputFileLength); Color reductionColor = Color.FromArgb(255, 0, 232, 0); Color growthColor = Color.Red; try { listView.SuspendLayout(); foreach (ListViewItem item in listView.Items.Find(latestResult.inputPath, true)) { // Update list view details // Note: For convenience, the path to the reduced image will be carried // in the Tag property of the file name column. item.SubItems[COLUMN_FILENAME].Tag = latestResult.outputPath; item.SubItems[COLUMN_REDUCEDSIZE].Text = outputFileLengthString; item.SubItems[COLUMN_SAVINGSSIZE].Text = savingsPercentageString; item.SubItems[COLUMN_REMARKS].Text = latestResult.remarks; if (savingsPercentage > 0) { item.SubItems[COLUMN_SAVINGSSIZE].BackColor = reductionColor; } else if (savingsPercentage < 0) { item.SubItems[COLUMN_SAVINGSSIZE].BackColor = growthColor; } // Refresh previously selected row if (item.Selected) { refreshSideBySideComparison(item); } } } finally { listView.ResumeLayout(); } // Report Progress to user Text = String.Format("{0}% - {1}", new object[] { e.ProgressPercentage, TITLE }); }
private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { List <ReduceOptions> optionsList = (List <ReduceOptions>)e.Argument; Int32 remaining = optionsList.Count; foreach (ReduceOptions options in optionsList) { if (backgroundWorker.CancellationPending) { break; } // Prepare to save reduced image: // - Delete the target file if it already exists // - Ensure the host directory exists. deleteFileWhenExists(options.outputPath); Directory.CreateDirectory(Path.GetDirectoryName(options.outputPath)); JpegReduceOptions jpegReduceOptions = new JpegReduceOptions(); JpegReduceResult jpegLatestResult = new JpegReduceResult(); ReduceResult latestResult = new ReduceResult(); // Perform reduction and prepare to report results latestResult.inputPath = options.inputPath; latestResult.outputPath = options.outputPath; latestResult.isErrorEncountered = false; latestResult.remarks = String.Empty; bool areOptionsForJpeg = (options is JpegReduceOptions) ? true : false; if (areOptionsForJpeg) { jpegReduceOptions = options as JpegReduceOptions; jpegLatestResult = new JpegReduceResult(latestResult); jpegLatestResult.jpegQualityFactor = jpegReduceOptions.jpegQualityFactor; jpegLatestResult.transformMode = jpegReduceOptions.transformMode; } try { if (areOptionsForJpeg) { Accusoft.ImagXpressSdk.ImageReduce.JpegReduce(imagXpress1, jpegReduceOptions.inputPath, jpegReduceOptions.outputPath, jpegReduceOptions.jpegQualityFactor); } else { Accusoft.ImagXpressSdk.ImageReduce.PngReduce(imagXpress1, options.inputPath, options.outputPath); } } catch (ImagXpressException ex) { latestResult.isErrorEncountered = true; latestResult.remarks = ex.Message; } catch (Exception ex) { latestResult.isErrorEncountered = true; latestResult.remarks = ex.ToString(); } // Notify UI of a progress update int percentComplete = (int)((float)(optionsList.Count - remaining) / optionsList.Count * 100); if (areOptionsForJpeg) { backgroundWorker.ReportProgress(percentComplete, jpegLatestResult); } else { backgroundWorker.ReportProgress(percentComplete, latestResult); } remaining--; } }
public static bool FoundValue(this ReduceResult result) => (result & ReduceResult.Found) != 0;
public static bool HasBeenReduced(this ReduceResult result) => (result & ReduceResult.Reduced) != 0;
/// <summary>Returns true if the result is final.</summary> public static bool IsFinal(this ReduceResult result) => (result & ReduceResult.Final) != 0;
/// <summary>Returns false if the result is solved or the method is disabled.</summary> private bool SkipMethod(SudokuSolverMethods method, ReduceResult result) { return (Methods & method) == SudokuSolverMethods.None || (result & (ReduceResult.Solved | ReduceResult.Inconsistend)) != ReduceResult.None; }
/// <summary>Reduces singles.</summary> /// <remarks> /// Any cells which have only one candidate can safely be assigned that value. /// /// It is very important whenever a value is assigned to a cell, that this /// value is also excluded as a candidate from all other blank cells sharing /// the same row, column and sub square. /// </remarks> private ReduceResult ReduceSingles(ReduceResult result, SudokuState state) { if (SkipMethod(SudokuSolverMethods.Singles, result)) { return result; } result = ReduceResult.Reduced; while (result == ReduceResult.Reduced) { result = ReduceResult.None; for (var index1 = 0; index1 <= Puzzle.MaximumIndex; index1++) { if (state.IsKnown(index1)) { foreach (var group in Puzzle.Lookup[index1]) { foreach (var index0 in group) { if (index0 != index1) { result |= state.Exclude(index0, index1); } } } } } } return result; }