// Given a sequence of strings, return all non-trivial anagram // classes. Should use a *sequenced* equalityComparer on a TreeBag<char>, // obviously: after all, characters can be sorted by ASCII code. On // 347 000 distinct Danish words this takes 70 cpu seconds, 180 MB // memory, and 263 wall-clock seconds (due to swapping). // Using a TreeBag<char> and a sequenced equalityComparer takes 82 cpu seconds // and 180 MB RAM to find the 26,058 anagram classes among 347,000 // distinct words. // Using an unsequenced equalityComparer on TreeBag<char> or HashBag<char> // makes it criminally slow: at least 1200 cpu seconds. This must // be because many bags get the same hash code, so that there are // many collisions. But exactly how the unsequenced equalityComparer works is // not clear ... or is it because unsequenced equality is slow? public static SCG.IEnumerable<SCG.IEnumerable<String>> AnagramClasses(SCG.IEnumerable<String> ss) { bool unseq = true; IDictionary<TreeBag<char>, TreeSet<String>> classes; if (unseq) { SCG.IEqualityComparer<TreeBag<char>> unsequencedTreeBagEqualityComparer = UnsequencedCollectionEqualityComparer<TreeBag<char>, char>.Default; classes = new HashDictionary<TreeBag<char>, TreeSet<String>>(unsequencedTreeBagEqualityComparer); } else { SCG.IEqualityComparer<TreeBag<char>> sequencedTreeBagEqualityComparer = SequencedCollectionEqualityComparer<TreeBag<char>, char>.Default; classes = new HashDictionary<TreeBag<char>, TreeSet<String>>(sequencedTreeBagEqualityComparer); } foreach (String s in ss) { TreeBag<char> anagram = AnagramClass(s); TreeSet<String> anagramClass; if (!classes.Find(anagram, out anagramClass)) classes[anagram] = anagramClass = new TreeSet<String>(); anagramClass.Add(s); } foreach (TreeSet<String> anagramClass in classes.Values) if (anagramClass.Count > 1) yield return anagramClass; }
static void Main(string[] args) { var table = new HashDictionary<string, int>(); table.Add("P", 2); table.Add("A", 3); table.Add("B", 4); Console.WriteLine(table.ContainsKey("P")); Console.WriteLine(table.ContainsKey("P2")); foreach (var pair in table) { Console.WriteLine(pair.Key + " " + pair.Value); } Console.WriteLine(); //Console.WriteLine(table.Find("B")); //Console.WriteLine(table["P"]); //table["P"] = 5; //Console.WriteLine(table["P"]); //Console.WriteLine(table["D"]); //Console.WriteLine(); Console.WriteLine("!!!!!!!!!!!!!!!!!"); table.Remove("P"); foreach (var pair in table) { Console.WriteLine(pair.Key + " " + pair.Value); } }
CompositeDfaTrans(int s0, IDictionary <int, ArrayList <Transition> > trans) { Set <int> S0 = EpsilonClose(new Set <int>(s0), trans); IQueue <Set <int> > worklist = new CircularQueue <Set <int> >(); worklist.Enqueue(S0); // The transition relation of the DFA IDictionary <Set <int>, IDictionary <String, Set <int> > > res = new HashDictionary <Set <int>, IDictionary <String, Set <int> > >(); while (!worklist.IsEmpty) { Set <int> S = worklist.Dequeue(); if (!res.Contains(S)) { // The S -lab-> T transition relation being constructed for a given S IDictionary <String, Set <int> > STrans = new HashDictionary <String, Set <int> >(); // For all s in S, consider all transitions s -lab-> t foreach (int s in S) { // For all non-epsilon transitions s -lab-> t, add t to T foreach (Transition tr in trans[s]) { if (tr.lab != null) // Non-epsilon transition { Set <int> toState; if (STrans.Contains(tr.lab)) // Already a transition on lab { toState = STrans[tr.lab]; } else // No transitions on lab yet { toState = new Set <int>(); STrans.Add(tr.lab, toState); } toState.Add(tr.target); } } } // Epsilon-close all T such that S -lab-> T, and put on worklist IDictionary <String, Set <int> > STransClosed = new HashDictionary <String, Set <int> >(); foreach (KeyValuePair <String, Set <int> > entry in STrans) { Set <int> Tclose = EpsilonClose(entry.Value, trans); STransClosed.Add(entry.Key, Tclose); worklist.Enqueue(Tclose); } res.Add(S, STransClosed); } } return(res); }
// Compute a renamer, which is a dictionary mapping set of int to int static IDictionary <Set <int>, int> MkRenamer(ICollectionValue <Set <int> > states) { IDictionary <Set <int>, int> renamer = new HashDictionary <Set <int>, int>(); int count = 0; foreach (Set <int> k in states) { renamer.Add(k, count++); } return(renamer); }
public void testGetIndexContents() { var map = new HashDictionary { { "one", 1 }, { "another_one", 1 }, { "one_more", 1 }, { "two", 2 }, { "three", 3 }, { "four", 4 }, { "four_again", 4 }, { "five", 5 }, { "five_a", 5 }, { "five_b", 5 }, { "five_c", 5 }, { "five_d", 5 } }; IValueExtractor extractor = new IdentityExtractor(); IFilter filter = new LessFilter(extractor, 5); ConditionalIndex index = createIndex(map, filter, extractor, true); IDictionary indexContents = index.IndexContents; var setOne = indexContents[1] as HashSet; Assert.IsNotNull(setOne); Assert.AreEqual(3, setOne.Count); Assert.IsTrue(setOne.Contains("one")); Assert.IsTrue(setOne.Contains("another_one")); Assert.IsTrue(setOne.Contains("one_more")); var setTwo = indexContents[2] as HashSet; Assert.IsNotNull(setTwo); Assert.AreEqual(1, setTwo.Count); Assert.IsTrue(setTwo.Contains("two")); var setThree = indexContents[3] as HashSet; Assert.IsNotNull(setThree); Assert.AreEqual(1, setThree.Count); Assert.IsTrue(setThree.Contains("three")); var setFour = indexContents[4] as HashSet; Assert.IsNotNull(setFour); Assert.AreEqual(2, setFour.Count); Assert.IsTrue(setFour.Contains("four")); Assert.IsTrue(setFour.Contains("four_again")); var setFive = indexContents[5] as ICollection; Assert.IsNull(setFive); }
public void ShouldCalculateEffectivenessWhenInvertedIndexIsSortedSet() { IDictionary indexes = new HashDictionary(); indexes[m_extractor] = s_sortedIndex; BetweenFilter filter = new BetweenFilter(m_extractor, 10, 20); var effectiveness = filter.CalculateEffectiveness(indexes, s_setKeys); Assert.AreEqual(31, effectiveness); }
/// <summary> /// Singleton constructor. /// </summary> private ResourceRegistry() { m_resourceHandlers = new HashDictionary(); RegisterHandlerInternal("file", typeof(FileResource)); RegisterHandlerInternal("http", typeof(UrlResource)); RegisterHandlerInternal("https", typeof(UrlResource)); RegisterHandlerInternal("ftp", typeof(UrlResource)); RegisterHandlerInternal("assembly", typeof(EmbeddedResource)); RegisterHandlerInternal("asm", typeof(EmbeddedResource)); RegisterHandlerInternal("web", typeof(WebResource)); }
public LanguageStrings(string fileName) { Language = new C5.HashDictionary <string, string>(); string type, text, line; int pos; foreach (string l in File.ReadAllLines(fileName)) { line = l.Trim(); if (line.StartsWith("#")) { continue; } if (!line.Contains(" ") && !line.Contains("\t")) { continue; } // We need to stop at the first space or \t. for (pos = 0; pos < line.Length; pos++) { if (line[pos] == ' ' || line[pos] == '\t') { break; } } type = line.Substring(0, pos); if (Language.Contains(type)) { continue; } text = line.Substring(pos); text = text.Trim(); text = text.Replace("\\n", "\n"); text = text.Replace("\\t", "\t"); Language.Add(type, text); } if (Language.Contains("Error_No_Local")) { _errorNoLocal = Language["Error_No_Local"]; } if (Language.Contains("Language_Name")) { _languageName = Language["Language_Name"]; } if (Language.Contains("Language_DisplayName")) { _languageDisplayName = Language["Language_DisplayName"]; } }
/// <summary> /// Aggregate the results of the parallel aggregations. /// </summary> /// <param name="results"> /// Results to aggregate. /// </param> /// <returns> /// The aggregation of the parallel aggregation results. /// </returns> public virtual object AggregateResults(ICollection results) { IParallelAwareAggregator aggregator = (IParallelAwareAggregator)m_aggregator; IDictionary dictionaryResult = new HashDictionary(); foreach (IDictionary dictPart in results) { // partial aggregation results are maps with distinct values // as keys and partial aggregation results as values foreach (DictionaryEntry entry in dictPart) { object distinct = entry.Key; object result = entry.Value; // collect all the aggregation results per group ICollection group = (ICollection)dictionaryResult[distinct]; if (group == null) { dictionaryResult.Add(distinct, group = new ArrayList()); } CollectionUtils.Add(group, result); } } IDictionary newResult = new HashDictionary(dictionaryResult); if (dictionaryResult.Count == 0) { // we need to call "AggregateResults" on the underlying // aggregator to fulfill our contract, even though any result // will be discarded aggregator.AggregateResults(NullImplementation.GetCollection()); } else { IFilter filter = m_filter; foreach (DictionaryEntry entry in dictionaryResult) { ICollection group = (ICollection)entry.Value; object result = aggregator.AggregateResults(group); if (filter == null || filter.Evaluate(result)) { newResult[entry.Key] = result; } else { newResult.Remove(entry.Key); } } } return(newResult); }
public static void Main(String[] args) { var list = new HashSet<int> { 2, 3, 5, 7, 11 }; foreach (var x in list) Console.WriteLine(x); var dict = new HashDictionary<int,String> { { 2, "two" }, { 3, "three" } }; foreach (var x in dict) Console.WriteLine(x.Value); }
public void Dispose() { _suffixArray = null; _inverseSuffixArray = null; _longestCommonPrefix = null; _chainHeadsDictionary = null; _chainStack = null; _subChains = null; _inputData = null; }
// Compute a renamer, which is a dictionary mapping set of int to int private static IDictionary <HashSet <int>, int> MkRenamer(ICollectionValue <HashSet <int> > states) { var renamer = new HashDictionary <HashSet <int>, int>(); var count = 0; foreach (var k in states) { renamer.Add(k, count++); } return(renamer); }
public void HashDictionaryTest() { HashDictionary <Types.Transaction> dict = new HashDictionary <Types.Transaction>(); byte[] key1 = Merkle.transactionHasher.Invoke(Util.GetNewTransaction(1)); byte[] key2 = Merkle.transactionHasher.Invoke(Util.GetNewTransaction(1)); dict.Add(key1, Util.GetNewTransaction(1)); Assert.IsTrue(dict.ContainsKey(key1)); Assert.IsTrue(dict.ContainsKey(key2)); }
static void Main(string[] args) { // to use hashmap you have to reference it first in the project // right click references -> add refernces -> projects -> HashDictionary // alternatively use strg + . and select add reference var dict = new HashDictionary <int, string>(); dict[3] = "Willi"; dict[5] = "Andi"; dict.Add(1, "Franz"); // V1 //Console.WriteLine($"[1] = {dict[1]}"); //Console.WriteLine($"[3] = {dict[3]}"); //Console.WriteLine($"[5] = {dict[5]}"); //if (dict.ContainsKey(7)) // Console.WriteLine($"[7] = {dict[7]}"); //else // Console.WriteLine("[7] does not exist"); // V2 string result; if (dict.TryGetValue(7, out result)) { Console.WriteLine($"[7] = {result}"); } else { Console.WriteLine("[7] does not exist"); } // V3 if (dict.TryGetValue(7, out string result2)) { Console.WriteLine($"[7] = {result2}"); } else { Console.WriteLine("[7] does not exist"); } // iterate foreach (KeyValuePair <int, string> pair in dict) { Console.WriteLine(pair); } Console.WriteLine("Press any key to exit...."); Console.ReadLine(); }
public void Keys_returns_GuardedCollectionValue() { var source = new HashDictionary <int, string> { [1] = "one", [2] = "two", [3] = "three" }; var guarded = new GuardedDictionary <int, string>(source); Assert.IsAssignableFrom <GuardedCollectionValue <int> >(guarded.Keys); }
public void Values_returns_Values() { var source = new HashDictionary <int, string> { [1] = "one", [2] = "two", [3] = "three" }; var guarded = new GuardedDictionary <int, string>(source); CollectionAssert.AreEquivalent(new[] { "one", "two", "three" }, guarded.Values); }
/// <summary> /// Get an IDictionary of the available non-partial indexes from the /// given IDictionary of all available indexes. /// </summary> /// <param name="indexes">The available <see cref="ICacheIndex"/> /// objects keyed by the related IValueExtractor; read-only.</param> /// <returns>An IDictionary of the available non-partial /// <see cref="ICacheIndex"/> objects.</returns> protected virtual IDictionary GetNonPartialIndexes(IDictionary indexes) { IDictionary nonPartialIndexes = new HashDictionary(); foreach (DictionaryEntry entry in indexes) { if (!((ICacheIndex)entry.Value).IsPartial) { nonPartialIndexes[entry.Key] = entry.Value; } } return(nonPartialIndexes); }
public void ShouldApplyIndexWhenUnsortedIndexPresent() { IDictionary indexes = new HashDictionary(); ICollection keys = new HashSet(s_setKeys); BetweenFilter filter = new BetweenFilter(m_extractor, 10, 20); indexes[m_extractor] = s_unsortedIndex; var result = filter.ApplyIndex(indexes, keys); Assert.IsNull(result); Assert.IsTrue(s_setKeysTenToTwenty.Equals(keys)); }
private NetworkInterface extractInterface(NodeEntry entry, HashDictionary <Node, NodeEntry> hashedNodes) { for (;;) { NodeEntry previousEntry = entry; Node next = entry.Link.LinkSides[0].ConnectedNode == entry.Node ? entry.Link.LinkSides[1].ConnectedNode : entry.Link.LinkSides[0].ConnectedNode; entry = hashedNodes[next]; if (entry.Node == node) { return(node.NetworkInterfaces.Find(previousEntry.Link)); } } }
/// <summary> /// Return a map of external attributes. /// </summary> /// <returns>External attributes.</returns> public IDictionary GetExternalAttributes() { IDictionary extAttrs = new HashDictionary(); foreach (ExternalAttributeHolder attr in BaseGetAllValues()) { if (attr.External) { extAttrs[attr.Name] = attr.BinaryValue; } } return(extAttrs); }
public static UOResource getResource(TextureImageInfo tileartTextureInfo, ShaderTypes stype) { //FAST search if (textures.ContainsKey(tileartTextureInfo.textureIDX)) { //TODO: references++ return(textures[tileartTextureInfo.textureIDX]); } //Get the string from stringDictionary if (tileartTextureInfo.textureIDX >= stringDictionary.count) { UOConsole.Fatal("String {0} not found in dictionary.", tileartTextureInfo.textureIDX); return(null); } string tga = stringDictionary.values[tileartTextureInfo.textureIDX]; //Replace extension int start = (tga.LastIndexOf("\\") == -1) ? 0 : (tga.LastIndexOf("\\") + 1); int end = tga.IndexOf("_"); if (end == -1) { UOConsole.Fatal("no descr in: {0} .. trying with extension", tga); tga = tga.Replace(".tga", ""); end = tga.Length; } //UOConsole.Fatal("{0} {1} {2}", tga, start, end); string toHash = tga.Substring(start, end - start) + ".dds"; toHash = toHash.ToLower(); toHash = "build/worldart/" + toHash; //Get the file from Texture.uop ulong tehHash = HashDictionary.HashFileName(toHash); if (!uopHashes.textureHashes.ContainsKey(tehHash)) { UOConsole.Fatal("string {0} not found in textureHashes - tga: {1}", toHash, tga); return(null); } uopMapping_t map = uopHashes.textureHashes[tehHash]; MythicPackage tex = new MythicPackage(fileDirectory + "texture.uop"); byte[] raw = tex.Blocks[map.block].Files[map.file].Unpack(tex.FileInfo.FullName); UOResource res = new UOResource(raw, stype); textures.Add(tileartTextureInfo.textureIDX, res); return(res); }
/// <summary> /// Get all the specified keys, if they are in the cache. /// </summary> /// <remarks> /// For each key that is in the cache, that key and its corresponding /// value will be placed in the dictionary that is returned by this /// method. The absence of a key in the returned dictionary indicates /// that it was not in the cache, which may imply (for caches that /// can load behind the scenes) that the requested data could not be /// loaded. /// </remarks> /// <param name="keys"> /// A collection of keys that may be in the named cache. /// </param> /// <returns> /// An <b>IDictionary</b> of keys to values for the specified keys /// passed in <paramref name="keys"/>. /// </returns> public virtual IDictionary GetAll(ICollection keys) { IDictionary dictionary = new HashDictionary(); foreach (object key in keys) { object value = this[key]; if (value != null || Contains(key)) { dictionary[key] = value; } } return(dictionary); }
/// <summary> /// Return the values associated with each the specified keys in /// the passed collection. /// </summary> /// <remarks> /// If a key does not have an associated value in the underlying /// store, then the return dictionary will not have an entry for /// that key. /// </remarks> /// <param name="keys"> /// A collection of keys to load. /// </param> /// <returns> /// A dictionary of keys to associated values for the specified /// keys. /// </returns> public IDictionary LoadAll(ICollection keys) { IDictionary dictionary = new HashDictionary(); foreach (object key in keys) { object value = Load(key); if (value != null) { dictionary[key] = value; } } return(dictionary); }
public MYPHandler(string filename, del_FileTableEventHandler eventHandler_FileTable, del_FileEventHandler eventHandler_Extraction, HashDictionary hashDic) { // Try to set ramCounter to the performance counter but if it fails set it to null to default getUsedRAM() to 0 try { ramCounter = new PerformanceCounter("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName); } catch { ramCounter = null; } this.hashDictionary = hashDic; if (eventHandler_Extraction != null) { this.event_Extraction += eventHandler_Extraction; } if (eventHandler_FileTable != null) { this.event_FileTable += eventHandler_FileTable; } this.currentMypFileName = filename.Substring(filename.LastIndexOf('\\') + 1, filename.Length - filename.LastIndexOf('\\') - 1); this.currentMypFileName = this.currentMypFileName.Split('.')[0]; this.fullMypFileName = filename; this.mypPath = filename.LastIndexOf('\\') < 0 ? "" : filename.Substring(0, filename.LastIndexOf('\\')); this.pattern = "*"; this.unCompressedSize = 0L; this.numberOfFileNamesFound = 0L; this.totalNumberOfFiles = 0L; this.numberOfFilesFound = 0L; this.error_FileEntryNumber = 0L; this.error_ExtractionNumber = 0L; this.archiveStream = new FileStream(filename, FileMode.Open, FileAccess.Read); this.archiveStream.Seek(12L, SeekOrigin.Begin); byte[] numArray = new byte[8]; this.archiveStream.Read(numArray, 0, numArray.Length); this.tableStart = (long)FileInArchiveDescriptor.convertLittleEndianBufferToInt(numArray, 0L); this.tableStart += (long)FileInArchiveDescriptor.convertLittleEndianBufferToInt(numArray, 4L) << 32; this.GetFileNumber(); this.oSearcher = new ManagementObjectSearcher(this.oMs, this.oQuery); this.oReturnCollection = this.oSearcher.Get(); foreach (ManagementBaseObject oReturn in this.oReturnCollection) { this.totalMemory += Convert.ToDouble(oReturn["Capacity"]); } if (this.totalMemory > this.programMemory) { return; } this.programMemory = this.totalMemory / 2.0; }
private static void addNodeToMap(Node node) { //implement Dijkstra alghoritm: IntervalHeap <NodeEntry> sortedNodes = new IntervalHeap <NodeEntry>(); HashDictionary <Node, NodeEntry> hashedNodes = new HashDictionary <Node, NodeEntry>(); NodeEntry thisNode = new NodeEntry(); thisNode.Node = node; bool firstAdded = sortedNodes.Add(ref thisNode.Handle, thisNode); Debug.Assert(firstAdded); hashedNodes.Add(node, thisNode); while (sortedNodes.Count != 0) { NodeEntry currentNode = sortedNodes.DeleteMin(); foreach (Link link in currentNode.Node.NetworkInterfaces.Interfaces.Keys) { //get the node from the second side of link Node secondNode = (link.LinkSides[0].ConnectedNode == currentNode.Node) ? link.LinkSides[1].ConnectedNode : link.LinkSides[0].ConnectedNode; double distance = link.Metric + currentNode.Distance; if (hashedNodes.Contains(secondNode)) { NodeEntry entry = hashedNodes[secondNode]; if (entry.Distance > distance) { entry.Distance = distance; sortedNodes.Replace(entry.Handle, entry); } } else { NodeEntry newEntry = new NodeEntry(); newEntry.Node = secondNode; newEntry.Distance = distance; hashedNodes.Add(secondNode, newEntry); bool added = sortedNodes.Add(ref newEntry.Handle, newEntry); Debug.Assert(added); } } } //hashedNodes.Remove(node); HashDictionary <Node, double> finalDistances = new HashDictionary <Node, double>(); foreach (NodeEntry entry in hashedNodes.Values) { finalDistances.Add(entry.Node, entry.Distance); } distances.Add(node, finalDistances); }
void UpdateMempool(TransactionContext dbTx, HashDictionary <TransactionValidation.PointedTransaction> confirmedTxs, HashDictionary <Types.Transaction> unconfirmedTxs) { lock (memPool) { dbTx.Commit(); var activeContracts = new HashSet(); foreach (var item in ActiveContractSet.All(dbTx)) { activeContracts.Add(item.Item1); } foreach (var item in memPool.ContractPool) { activeContracts.Add(item.Key); } RemoveConfirmedTxsFromMempool(confirmedTxs); MakeOrphan(dbTx); memPool.TxPool.MoveToICTxPool(activeContracts); RemoveInvalidAutoTxs(dbTx); foreach (var t in unconfirmedTxs) { new HandleTransactionAction { Tx = t.Value, CheckInDb = false }.Publish(); } memPool.ICTxPool.Where(t => { byte[] contractHash; IsContractGeneratedTx(t.Value, out contractHash); return(activeContracts.Contains(contractHash)); }) .ToList().ForEach(t => { memPool.ICTxPool.Remove(t.Key); new HandleTransactionAction { Tx = TransactionValidation.unpoint(t.Value), CheckInDb = false }.Publish(); }); } }
//Land tiles does not have tileart TEXTURES section.. we need to extract them from terrain definition public static TextureImageInfo getLandtileTextureID(uint legacyLandtileID) { //Fast search if (landtiles.ContainsKey(legacyLandtileID)) { return(landtiles[legacyLandtileID]); } //Translate the legacy ID to the new pair newID-subtype using legacyterrainMap if (!legacyTerrainMap.ContainsKey(legacyLandtileID)) { UOConsole.Fatal("Cannot find {0} in legacyTerrainMap", legacyLandtileID); return(null); } legacyTerrainMap_t landtileID = legacyTerrainMap[legacyLandtileID]; //Get the file from terrain definition using the newID ulong hash = HashDictionary.HashFileName(string.Format("build/terraindefinition/{0}.bin", landtileID.newID)); if (!uopHashes.terrainHashes.ContainsKey(hash)) { UOConsole.Fatal("Cannot find {0} in terrainHashes", landtileID.newID); return(null); } uopMapping_t pos = uopHashes.terrainHashes[hash]; MythicPackage _uop = new MythicPackage(fileDirectory + "TerrainDefinition.uop"); byte[] raw = _uop.Blocks[pos.block].Files[pos.file].Unpack(_uop.FileInfo.FullName); //Read the loaded terrainDefinition file. TerrainDefinition td; using (MemoryStream ms = new MemoryStream(raw)) { using (BinaryReader r = new BinaryReader(ms)) { td = TerrainDefinition.readTerrainDefinition(r); } } if (td == null) { UOConsole.Fatal("Cannot read terrainDefinition file"); return(null); } landtiles[legacyLandtileID] = td.textures.texturesArray[landtileID.newSubtype]; //Returns the texture according to subtype return(td.textures.texturesArray[landtileID.newSubtype]); }
//HELPERS private static void prepareMap() { if (distances != null) //already prepared { return; } distances = new HashDictionary <Node, HashDictionary <Node, double> >(); foreach (Identificable identificable in Network.Identificables) { if (identificable is Node) { addNodeToMap((Node)identificable); } } }
public HashDictionary <ACSItem> GetExpiringList(TransactionContext dbTx, uint blockNumber) { #if TRACE All(dbTx).Where(t => t.Item2.LastBlock == blockNumber).ToList().ForEach(t => BlockChainTrace.Information($"contract due to expire at {blockNumber}", t.Item1)); #endif var values = new HashDictionary <ACSItem>(); foreach (var contract in All(dbTx).Where(t => t.Item2.LastBlock <= blockNumber)) { values[contract.Item1] = contract.Item2; } return(values); }
public void Keys_works_multiple_times(MemoryType memoryType, int numberOfIterations, int expectedResult) { var dictionary = new HashDictionary<int, string>(memoryType) { { 1, "One" }, { 2, "Two" }, { 3, "Three" }, { 4, "Four" } }; var sum = 0; for (var i = 0; i < numberOfIterations; i++) { foreach (var value in dictionary.Keys) { sum += value; } } Assert.AreEqual(expectedResult, sum); }
/// <summary> /// Creates a new myp worker /// </summary> /// <param name="filename">the name of the file to work with</param> /// <param name="event_FileTable">method to treat events return when reading the file table</param> /// <param name="event_Extraction">method to treat events return when extracting files</param> /// <param name="hasher">the dictionnary</param> public MYPHandler(string filename , del_FileTableEventHandler eventHandler_FileTable , del_FileEventHandler eventHandler_Extraction , HashDictionary hashDic) { this.hashDictionary = hashDic; if (eventHandler_Extraction != null) { this.event_Extraction += eventHandler_Extraction; } if (eventHandler_FileTable != null) { this.event_FileTable += eventHandler_FileTable; } //parse the filename to get the path this.currentMypFileName = filename.Substring(filename.LastIndexOf('\\') + 1, filename.Length - filename.LastIndexOf('\\') - 1); this.currentMypFileName = currentMypFileName.Split('.')[0]; this.fullMypFileName = filename; if (filename.LastIndexOf('\\') >= 0) { this.mypPath = filename.Substring(0, filename.LastIndexOf('\\')); } else { this.mypPath = ""; } //Initialize some data pattern = "*"; unCompressedSize = 0; numberOfFileNamesFound = 0; totalNumberOfFiles = 0; numberOfFilesFound = 0; error_FileEntryNumber = 0; error_ExtractionNumber = 0; //open the archive file archiveStream = new FileStream(filename, FileMode.Open, FileAccess.Read); //read the position of the starting file table archiveStream.Seek(0x0C, SeekOrigin.Begin); byte[] buffer = new byte[8]; archiveStream.Read(buffer, 0, buffer.Length); tableStart = FileInArchiveDescriptor.convertLittleEndianBufferToInt(buffer, 0); tableStart += ((long)FileInArchiveDescriptor.convertLittleEndianBufferToInt(buffer, 4)) << 32; GetFileNumber(); }
// Given a sequence of strings, return all non-trivial anagram // classes. // Using HashBag<char> and an unsequenced equalityComparer, this performs as // follows on 1600 MHz Mobile P4 and .Net 2.0 beta 1 (wall-clock // time): // 50 000 words 2 822 classes 2.0 sec // 100 000 words 5 593 classes 4.3 sec // 200 000 words 11 705 classes 8.8 sec // 300 000 words 20 396 classes 52.0 sec includes swapping // 347 165 words 24 428 classes 146.0 sec includes swapping // The maximal memory consumption is less than 180 MB. public static SCG.IEnumerable<SCG.IEnumerable<String>> AnagramClasses(SCG.IEnumerable<String> ss) { IDictionary<HashBag<char>, TreeSet<String>> classes = new HashDictionary<HashBag<char>, TreeSet<String>>(); foreach (String s in ss) { HashBag<char> anagram = AnagramClass(s); TreeSet<String> anagramClass; if (!classes.Find(ref anagram, out anagramClass)) classes[anagram] = anagramClass = new TreeSet<String>(); anagramClass.Add(s); } foreach (TreeSet<String> anagramClass in classes.Values) if (anagramClass.Count > 1) yield return anagramClass; }
public static void Init(int backlogLength = 500) { _varables = new HashDictionary <string, ConsoleVarable>(); _functions = new HashDictionary <string, ConsoleFunction>(); _consoleBacklog = new LimitedList <string>(backlogLength, string.Empty); _backlogLine = ""; ConsoleFunction ConsoleHelp = new ConsoleFunction() { Function = ConsoleHelpFunc, HelpInfo = DefaultLanguage.Strings.GetString("Console_Help_Help"), TabFunction = ConsoleHelpTab }; SetFunc("help", ConsoleHelp); }
private void CheckName() { if (m_File != null) { if (m_File.FileHash == HashDictionary.HashMeGently(FileName.Text.ToLower())) { m_File.FileName = FileName.Text.ToLower(); HashDictionary.Set(m_File.FileHash, m_File.FileName); Close(); } else { Status.Text = "Wrong file name!"; } } }
// Using a renamer (a dictionary mapping set of int to int), replace // composite (set of int) states with simple (int) states in the // transition relation trans, which is a dictionary mapping set of // int to a dictionary mapping from string to set of int. The // result is a dictionary mapping from int to a dictionary mapping // from string to int. private static IDictionary <int, IDictionary <string, int> > Rename(IDictionary <HashSet <int>, int> renamer, IDictionary <HashSet <int>, IDictionary <string, HashSet <int> > > trans) { var newtrans = new HashDictionary <int, IDictionary <string, int> >(); foreach (var entry in trans) { var k = entry.Key; var newktrans = new HashDictionary <string, int>(); foreach (var tr in entry.Value) { newktrans.Add(tr.Key, renamer[tr.Value]); } newtrans.Add(renamer[k], newktrans); } return(newtrans); }
public void KeyValuePairs_works_multiple_times(MemoryType memoryType, int numberOfIterations, int expectedResult) { var dictionary = new HashDictionary<int, int>(memoryType) { { 1, -1 }, { 2, -2 }, { 3, -3 }, { 4, -4 } }; var keys = 0; var values = 0; for (var i = 0; i < numberOfIterations; i++) { foreach (var kv in dictionary) { keys += kv.Key; values += kv.Value; } } Assert.AreEqual(expectedResult, keys); Assert.AreEqual(-expectedResult, values); }
public static void Main() { // var p1 = new KeyValuePair<int, int>(1, 3); // var p2 = new KeyValuePair<int, int>(1, 2); // Console.WriteLine(p1.Equals(p2)); // int[] values = { 1, 2, 4, 5 }; // var cachedValues = values; // values = new int[]{ 5, 6, 7, 8 }; // Console.WriteLine(string.Join(", ", cachedValues)); var table = new HashDictionary<string, int>(); table.Add("Pesho", 5); table.Add("Gosho", 5); //table.Add("Pesho", 5); //table.Add("Pesho", 5); Console.WriteLine(table.ContainsKey("Pesho")); Console.WriteLine(table.ContainsKey("Pesho2")); //foreach (var pair in table) //{ // Console.WriteLine(pair.Key + " -> " + pair.Value); //} }
public void Values_works_multiple_times(MemoryType memoryType, int numberOfIterations, int expectedResult) { var dictionary = new HashDictionary<string, int>(memoryType) { { "One", 1 }, { "Two", 2 }, { "Three", 3 }, { "Four", 4 } }; var sum = 0; for (var i = 0; i < numberOfIterations; i++) { foreach (var value in dictionary.Values) { sum += value; } } Assert.AreEqual(expectedResult, sum); }