Esempio n. 1
0
        private static DirSheet getDirSheetCache(string num, string pattern, LRUCache <string, DirSheet> cache)
        {
            DirSheet sheet;

            if (cache.TryGetValue(num, out sheet))
            {
                return(sheet);
            }

            try
            {
                if (System.IO.File.Exists(String.Format(pattern, num)))
                {
                    //read file and read binary data
                    using (FileStream stream = File.OpenRead(String.Format(pattern, num)))
                    {
                        using (BinaryReader reader = new BinaryReader(stream))
                        {
                            sheet = DirSheet.Load(reader);
                            cache.Add(num, sheet);
                            return(sheet);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DiagManager.Instance.LogError(new Exception("Error loading " + String.Format(pattern, num) + "\n", ex));
            }
            DirSheet newSheet = DirSheet.LoadError();

            cache.Add(num, newSheet);
            return(newSheet);
        }
Esempio n. 2
0
        /// <summary>
        /// Loads a vertex and returns true if found.
        /// </summary>
        /// <param name="vertexId"></param>
        /// <param name="latitude"></param>
        /// <param name="longitude"></param>
        /// <returns></returns>
        private bool LoadVertex(uint vertexId, out float latitude, out float longitude)
        {
            uint    blockId = CHBlock.CalculateId(vertexId, _blockSize);
            CHBlock block;

            if (!_blocks.TryGet(blockId, out block))
            { // damn block not cached!
                block = this.DeserializeBlock(blockId);
                if (block == null)
                { // oops even now the block is not found!
                    longitude = 0;
                    latitude  = 0;
                    return(false);
                }
                _blocks.Add(blockId, block);
            }
            uint blockIdx = vertexId - blockId;

            if (block.Vertices != null &&
                blockIdx < block.Vertices.Length)
            { // block is found and the vertex is there!
                latitude  = block.Vertices[blockIdx].Latitude;
                longitude = block.Vertices[blockIdx].Longitude;
                return(true);
            }
            // oops even now the block is not found!
            longitude = 0;
            latitude  = 0;
            return(false);
        }
Esempio n. 3
0
        public void LRUCache_AddItem_Test()
        {
            // Arrange
            var cache = new LRUCache <int, string>(5);

            // Act
            var string1 = "test string 1";

            cache.Add(0, string1);
            var result = cache.TryGetValue(0, out var retrievedValue);

            // Assert
            Assert.IsTrue(result, "Get operation should be successful.");
            Assert.AreEqual(string1, retrievedValue, "Incorrect cached value.");

            // Act
            var string2 = "test string 2";

            cache.Add(0, string2);
            result = cache.TryGetValue(0, out retrievedValue);

            // Assert
            Assert.IsTrue(result, "Get operation should be successful.");
            Assert.AreEqual(1, cache.Count, "There should only be one item in the cache.");
            Assert.AreEqual(string2, retrievedValue, "Incorrect cached value.");
        }
Esempio n. 4
0
        /// <inheritdoc/>
        public void Put(ICmisObject cmisObject, string cacheKey)
        {
            // no object, no id, no cache key - no cache
            if (cmisObject == null || cmisObject.Id == null || cacheKey == null)
            {
                return;
            }

            lock (cacheLock)
            {
                IDictionary <string, ICmisObject> cacheKeyDict = objectCache.Get(cmisObject.Id);
                if (cacheKeyDict == null)
                {
                    cacheKeyDict = new Dictionary <string, ICmisObject>();
                    objectCache.Add(cmisObject.Id, cacheKeyDict);
                }

                cacheKeyDict[cacheKey] = cmisObject;

                // folders may have a path, use it!
                string path = cmisObject.GetPropertyValue(PropertyIds.Path) as string;
                if (path != null)
                {
                    pathToIdCache.Add(path, cmisObject.Id);
                }
            }
        }
Esempio n. 5
0
        public void TestOverflowCacheWithSmallerItem()
        {
            var    cache    = new LRUCache <UUID, String>(10);
            String testData = "Test Data";

            for (int i = 0; i < 10; i++)
            {
                var id = UUID.Random();
                cache.Add(id, testData);
            }

            Assert.AreEqual(10, cache.Count);
            Assert.AreEqual(10, cache.Size);

            UUID   overflowId   = UUID.Random();
            String overflowData = "OverFlow";

            cache.Add(overflowId, overflowData);

            Assert.AreEqual(10, cache.Count);
            Assert.AreEqual(10, cache.Size);

            String lastInsertedValue;

            Assert.IsTrue(cache.TryGetValue(overflowId, out lastInsertedValue));
            Assert.AreEqual(overflowData, lastInsertedValue);
        }
Esempio n. 6
0
        public static AnimSheet GetSpellSheet(SpellAnimType animType, int num)
        {
            AnimSheet cacheSheet = spellCache.Get(animType.ToString() + num);

            if (cacheSheet != null)
            {
                return(cacheSheet);
            }

            if (File.Exists(Paths.EffectsPath + animType.ToString() + "-" + num + ".png"))
            {
                AnimSheet sheet = new AnimSheet();
                sheet.LoadPixelsFromFile32(Paths.EffectsPath + animType.ToString() + "-" + num + ".png");
                sheet.LoadTextureFromPixels32();
                switch (animType)
                {
                case SpellAnimType.Spell:
                    sheet.GenerateDataBuffer(1, 1);
                    break;

                case SpellAnimType.Arrow:
                    sheet.GenerateDataBuffer(8, 1);
                    break;

                case SpellAnimType.Beam:
                    sheet.GenerateDataBuffer(8, 4);
                    break;
                }
                spellCache.Add(animType.ToString() + num, sheet);
                return(sheet);
            }
            spellCache.Add(animType.ToString() + num, ErrorTexture);
            return(ErrorTexture);
        }
Esempio n. 7
0
        public void TestOverflowReplacesFirstEntryAdded()
        {
            var cache = new LRUCache <UUID, String>(10);

            UUID   firstEntryId   = UUID.Random();
            String firstEntryData = "First Entry";

            cache.Add(firstEntryId, firstEntryData);

            String testData = "Test Data";

            for (int i = 0; i < 10; i++)
            {
                var id = UUID.Random();
                cache.Add(id, testData);
            }

            Assert.AreEqual(10, cache.Count);
            Assert.AreEqual(10, cache.Size);

            String lastInsertedValue;

            Assert.IsFalse(cache.TryGetValue(firstEntryId, out lastInsertedValue));
            Assert.IsNull(lastInsertedValue);
        }
Esempio n. 8
0
        public void forwardFrame(IPFrame frame)
        {
            var id       = RandomString(10);
            var udpFrame = (UDPFrame)frame.EncapsulatedFrame;
            var e        = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("192.168.1.220"), udpFrame.DestinationPort);

            logger.Debug("{0} Source Port: {1}", id, udpFrame.SourcePort);
            logger.Debug("{0} Dest Port: {1}", id, udpFrame.DestinationPort);
            ProxySocket socket;
            var         cacheKey = string.Format("{0}:{1}->{2}", udpFrame.SourcePort, udpFrame.DestinationPort, e.ToString());

            if (!natTable.TryGetValue(cacheKey, out socket))
            {
                socket = new ProxySocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                socket.ProxyEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("192.168.1.150"), 1080);
                socket.ProxyType     = ProxyTypes.Socks5;
                socket.Connect(e);
                Task.Run(() =>
                {
                    try
                    {
                        logger.Debug("{0} Create a new UDP Receive Task", id);
                        var buffer = new byte[8192];
                        ProxySocket tmp;
                        while (natTable.TryGetValue(cacheKey, out tmp))
                        {
                            logger.Debug("start receive");
                            var bytesReceived = socket.Receive(buffer);
                            logger.Debug("{0} Received packet", id);
                            natTable.Add(cacheKey, socket);
                            var receivedIPFrame                = new IPv4Frame();
                            receivedIPFrame.SourceAddress      = frame.DestinationAddress;
                            receivedIPFrame.DestinationAddress = frame.SourceAddress;
                            receivedIPFrame.Protocol           = IPProtocol.UDP;
                            var receivedUDPFrame               = new UDPFrame();
                            receivedUDPFrame.SourcePort        = udpFrame.DestinationPort;
                            receivedUDPFrame.DestinationPort   = udpFrame.SourcePort;
                            logger.Debug("{0} RSource Port: {1}", id, receivedUDPFrame.SourcePort);
                            logger.Debug("{0} RDest Port: {1}", id, receivedUDPFrame.DestinationPort);
                            receivedUDPFrame.EncapsulatedFrame = new RawDataFrame(buffer, 0, bytesReceived);
                            receivedIPFrame.EncapsulatedFrame  = receivedUDPFrame;
                            receivedUDPFrame.Checksum          = receivedUDPFrame.CalculateChecksum(receivedIPFrame.GetPseudoHeader());
                            tap.Write(receivedIPFrame.FrameBytes, 0, receivedIPFrame.Length);
                            tap.Flush();
                            logger.Debug("{0} wrote", id);
                        }
                    }
                    catch (SocketException err)
                    {
                        logger.Error(err);
                    }
                });
            }
            natTable.Add(cacheKey, socket);
            socket.BeginSend(udpFrame.EncapsulatedFrame.FrameBytes, 0, udpFrame.EncapsulatedFrame.FrameBytes.Length, 0, ar =>
            {
                socket.EndSend(ar);
                logger.Debug("{0} Sent to Dest", id);
            }, null);
        }
Esempio n. 9
0
        public void TestAgingRemovesEntriesButPreservesReservedEntries()
        {
            var cache = new LRUCache <UUID, String>(10, minSize: 1, maxAge: 1000);

            UUID   firstEntryId   = UUID.Random();
            String firstEntryData = "First Entry";

            cache.Add(firstEntryId, firstEntryData);

            UUID   secondEntryId   = UUID.Random();
            String secondEntryData = "Second Entry";

            cache.Add(secondEntryId, secondEntryData);

            Thread.Sleep(5 * 1000);
            cache.Maintain();

            Assert.AreEqual(1, cache.Count);
            Assert.AreEqual(1, cache.Size);

            String lastInsertedValue;

            Assert.IsFalse(cache.TryGetValue(firstEntryId, out lastInsertedValue));
            Assert.IsNull(lastInsertedValue);

            Assert.IsTrue(cache.TryGetValue(secondEntryId, out lastInsertedValue));
            Assert.AreEqual(secondEntryData, lastInsertedValue);
        }
Esempio n. 10
0
        public static BeamSheet GetBeam(string num)
        {
            IEffectAnim sheet;

            if (vfxCache.TryGetValue("Beam-" + num, out sheet))
            {
                return((BeamSheet)sheet);
            }

            try
            {
                if (System.IO.File.Exists(String.Format(BEAM_PATTERN, num)))
                {
                    using (FileStream stream = File.OpenRead(String.Format(BEAM_PATTERN, num)))
                    {
                        using (BinaryReader reader = new BinaryReader(stream))
                        {
                            sheet = BeamSheet.Load(reader);
                            vfxCache.Add("Beam-" + num, sheet);
                            return((BeamSheet)sheet);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DiagManager.Instance.LogError(new Exception("Error loading " + String.Format(BEAM_PATTERN, num) + "\n", ex));
            }

            BeamSheet newSheet = BeamSheet.LoadError();

            vfxCache.Add("Beam-" + num, newSheet);
            return(newSheet);
        }
Esempio n. 11
0
        public void TestAgingRemovesEntriesUsingBytesForReservedSize()
        {
            UUID   firstEntryId   = UUID.Random();
            String firstEntryData = "First Entry";

            UUID   secondEntryId   = UUID.Random();
            String secondEntryData = "Second Entry";

            var cache = new LRUCache <UUID, String>(capacity: 250, useSizing: true, minSize: secondEntryData.Length, maxAge: 1000);

            cache.Add(firstEntryId, firstEntryData, firstEntryData.Length);
            cache.Add(secondEntryId, secondEntryData, secondEntryData.Length);

            Thread.Sleep(5 * 1000);
            cache.Maintain();

            Assert.AreEqual(1, cache.Count);
            Assert.AreEqual(secondEntryData.Length, cache.Size);

            String lastInsertedValue;

            Assert.IsFalse(cache.TryGetValue(firstEntryId, out lastInsertedValue));
            Assert.IsNull(lastInsertedValue);

            Assert.IsTrue(cache.TryGetValue(secondEntryId, out lastInsertedValue));
            Assert.AreEqual(secondEntryData, lastInsertedValue);
        }
Esempio n. 12
0
 /// <summary>
 /// A simple tester to see if the LRU cache is working correctly
 /// </summary>
 public static void Main()
 {
     LRUCache<int> intCache = new LRUCache<int>() { 1, 2, 3, 4 };
     intCache.Add(5);
     intCache.Remove(2);
     intCache.Add(6);
     Console.WriteLine(intCache);
     Console.ReadLine();
 }
Esempio n. 13
0
        public void Test1()
        {
            var cache = new LRUCache <string, string>(5);

            cache.Add("item1", "1");
            cache.Add("item2", "2");
            cache.Add("item3", "3");
            Assert.True(cache.Contains("item2"));
            Assert.False(cache.Contains("item4"));
        }
Esempio n. 14
0
        public void CacheAssetData(UUID assetId, byte[] data)
        {
            byte[] cacheData = _bufferPool.LeaseBytes(data.Length);

            Buffer.BlockCopy(data, 0, cacheData, 0, data.Length);

            _assetCache.Add(assetId, new CacheEntry {
                Data = cacheData, Size = data.Length
            }, cacheData.Length);
        }
Esempio n. 15
0
        public void Cache_Should_Remove_Last_Used_Item_When_Adding_A_New_One()
        {
            var cache = new LRUCache <string>(5);

            cache.Add(1, "val1");
            cache.Add(2, "val2");
            cache.Add(3, "val3");
            cache.Add(4, "val4");
            cache.Add(5, "val5");
            cache.Add(4, "val5");
            cache.Add(3, "val5");
            cache.Add(2, "val5");

            cache.PrintCache();


            Assert.AreEqual(cache.Size, 5);

            var cachedValue = cache.Get(1);

            Assert.AreEqual(cachedValue, "val1");

            cache.PrintCache();

            cache.Add(6, "val6");

            Assert.AreEqual(cache.Size, 5);

            var removedCachedValue = cache.Get(5);

            Assert.AreEqual(removedCachedValue, null);

            cache.PrintCache();
        }
Esempio n. 16
0
        /// <summary>
        /// Returns the way for the given id.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public override Way GetWay(long id)
        {
            Way way;

            if (!_waysCache.TryGet(id, out way))
            { // cache miss.
                way = _source.GetWay(id);
                _waysCache.Add(id, way);
            }
            return(way);
        }
Esempio n. 17
0
        /// <summary>
        /// Returns the relation with the given id.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public override Relation GetRelation(long id)
        {
            Relation relation;

            if (!_relationsCache.TryGet(id, out relation))
            { // cache miss.
                relation = _source.GetRelation(id);
                _relationsCache.Add(id, relation);
            }
            return(relation);
        }
Esempio n. 18
0
        public bool TryGetHulls(ulong meshHash, out HacdConvexHull[] cachedHulls)
        {
            HacdConvexHull[] memHulls;
            if (_memCache.TryGetValue(meshHash, out memHulls))
            {
                //we must clone here because the hulls will be scaled when they're used which would
                //change the values in this, inmemory, unscaled array
                cachedHulls = HacdConvexHull.CloneHullArray(memHulls);
                return(true);
            }

            const string FIND_QRY = "SELECT hull_data FROM Hulls WHERE hash = @hhash";

            using (SQLiteCommand cmd = new SQLiteCommand(FIND_QRY, _connection))
            {
                SQLiteParameter hashParam = cmd.CreateParameter();
                hashParam.ParameterName = "@hhash";
                hashParam.DbType        = System.Data.DbType.Int64;
                hashParam.Value         = (Int64)meshHash;

                cmd.Parameters.Add(hashParam);

                using (SQLiteDataReader reader = cmd.ExecuteReader())
                {
                    if (!reader.HasRows)
                    {
                        cachedHulls = null;
                        return(false);
                    }

                    List <HacdConvexHull> retHulls = new List <HacdConvexHull>();
                    while (reader.Read())
                    {
                        byte[] buffer = (byte[])reader[0];

                        using (MemoryStream hullStream = new MemoryStream(buffer))
                        {
                            HacdConvexHull hull = ProtoBuf.Serializer.Deserialize <HacdConvexHull>(hullStream);
                            if (hull == null)
                            {
                                throw new Exception("Protobuf deserialization of convex hull failed");
                            }

                            hull.FillVerticesFromRaw();
                            retHulls.Add(hull);
                        }
                    }

                    cachedHulls = retHulls.ToArray();
                    _memCache.Add(meshHash, HacdConvexHull.CloneHullArray(cachedHulls));
                    return(true);
                }
            }
        }
Esempio n. 19
0
        public void TestClear()
        {
            LRUCache <String, String> underTest = new LRUCache <String, String>(666);

            underTest.Add("key1", "value");
            underTest.Add("key2", "value");
            underTest.Add("key3", "value");
            Assert.That(underTest.Count == 3);
            underTest.Clear();
            Assert.That(underTest.Count == 0);
        }
Esempio n. 20
0
        /// <summary>
        /// Returns the node with the given id.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public override Node GetNode(long id)
        {
            Node node;

            if (!_nodesCache.TryGet(id, out node))
            { // cache miss.
                node = _source.GetNode(id);
                _nodesCache.Add(id, node);
            }
            return(node);
        }
Esempio n. 21
0
        public void TestContainsValue()
        {
            LRUCache <String, String> underTest = new LRUCache <String, String>(666);

            underTest.Add("key1", "value1");
            underTest.Add("key2", "value2");
            underTest.Add("key3", "value3");
            Assert.That(underTest.Count == 3);
            Assert.That(underTest.ContainsValue("value1"));
            Assert.That(underTest.ContainsValue("value2"));
            Assert.That(underTest.ContainsValue("value3"));
            Assert.IsFalse(underTest.ContainsValue("value4"));
        }
Esempio n. 22
0
        /// <summary>
        /// Creates a new instance of LRU cache where elements are evicted based on least frequently usage.
        /// </summary>
        static void testLRUCache()
        {
            ComputerInfo computerInfo = new ComputerInfo(); //reference to Microsoft.VisualBasic assembly.

            var lru = new LRUCache <int, Image <Gray, byte> >(
                (currentSize) =>
            {
                var occupied           = computerInfo.TotalPhysicalMemory - computerInfo.AvailablePhysicalMemory;
                var occupiedPercentage = (float)occupied / computerInfo.TotalPhysicalMemory;

                if (occupiedPercentage > 0.85)
                {
                    return(true);
                }

                return(false);
            },
                (img) => (ulong)(img.Stride * img.Height));

            lru.OnRemoveItem += lru_OnRemoveItem;

            /***************** add some elements ****************/
            var image = new Image <Gray, byte>(5 * 1024 * 1024, 1, 0);

            image.SetValue(5 % 256);
            lru.Add(1, image);

            image = new Image <Gray, byte>(5 * 1024 * 1024, 1, 0);
            image.SetValue(5 % 256);
            lru.Add(1, image);
            /***************** add some elements ****************/

            List <Image <Gray, byte> > a = new List <Image <Gray, byte> >();

            Random rand = new Random();

            int i = 0;

            while (i < 10000)
            {
                image = new Image <Gray, byte>(1024 * 1024, 1, 0);
                image.SetValue(i % 256);
                lru.Add(i, image);

                //Thread.Sleep(1);
                Console.WriteLine(computerInfo.AvailablePhysicalMemory / 1024 / 1024);
                i++;
            }

            //discover more properties and methods!
        }
Esempio n. 23
0
        public void LRUCacheTest()
        {
            // create the LRU cache.
            LRUCache <int, int> cache = new LRUCache <int, int>(5);

            // add some stuff.
            cache.Add(0, 1);
            cache.Add(1, 1);
            cache.Add(2, 1);
            cache.Add(3, 1);
            cache.Add(4, 1);
            cache.Add(5, 1);
            cache.Add(6, 1);

            int value;

            Assert.IsTrue(cache.TryPeek(6, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(5, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(4, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(3, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(2, out value));
            Assert.AreEqual(1, value);

            Assert.IsFalse(cache.TryPeek(1, out value)); // not in cache anymore.
            Assert.IsFalse(cache.TryPeek(0, out value)); // not in cache anymore.

            // 'use' 2 and 3.
            Assert.IsTrue(cache.TryGet(3, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryGet(2, out value));
            Assert.AreEqual(1, value);

            // add 7 and 8.
            cache.Add(7, 1);
            cache.Add(8, 1);

            // cache should now contain 2, 3, 7, 8, 6
            Assert.IsTrue(cache.TryPeek(2, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(3, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(7, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(8, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(6, out value));
            Assert.AreEqual(1, value);

            Assert.IsFalse(cache.TryPeek(4, out value)); // not in cache anymore.
            Assert.IsFalse(cache.TryPeek(5, out value)); // not in cache anymore.
        }
Esempio n. 24
0
        public void LRUCacheTest()
        {
            // create the LRU cache.
            LRUCache<int, int> cache = new LRUCache<int, int>(5);

            // add some stuff.
            cache.Add(0, 1);
            cache.Add(1, 1);
            cache.Add(2, 1);
            cache.Add(3, 1);
            cache.Add(4, 1);
            cache.Add(5, 1);
            cache.Add(6, 1);

            int value;
            Assert.IsTrue(cache.TryPeek(6, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(5, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(4, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(3, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(2, out value));
            Assert.AreEqual(1, value);

            Assert.IsFalse(cache.TryPeek(1, out value)); // not in cache anymore.
            Assert.IsFalse(cache.TryPeek(0, out value)); // not in cache anymore.

            // 'use' 2 and 3.
            Assert.IsTrue(cache.TryGet(3, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryGet(2, out value));
            Assert.AreEqual(1, value);

            // add 7 and 8.
            cache.Add(7, 1);
            cache.Add(8, 1);

            // cache should now contain 2, 3, 7, 8, 6
            Assert.IsTrue(cache.TryPeek(2, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(3, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(7, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(8, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(6, out value));
            Assert.AreEqual(1, value);

            Assert.IsFalse(cache.TryPeek(4, out value)); // not in cache anymore.
            Assert.IsFalse(cache.TryPeek(5, out value)); // not in cache anymore.
        }
Esempio n. 25
0
        public void LRUExpirationTime()
        {
            int             cacheCapacity       = 3;
            int             expirationInSeconds = 5;
            LRUCache <int?> cache = new LRUCache <int?>(cacheCapacity, expirationInSeconds);

            cache.Add(1, 1);
            Thread.Sleep(5000);
            Assert.Null(cache.Get(1)); //expired
            cache.Add(1, 1);
            Thread.Sleep(3000);
            cache.Get(1);                  //updated expiration time
            Thread.Sleep(3000);
            Assert.Equal(1, cache.Get(1)); //not yet expired
        }
Esempio n. 26
0
        /// <summary>
        /// 格式 [bundle/]asset
        /// </summary>
        /// <param name="assetPath"></param>
        /// <returns></returns>
        public static AssetId Parse(string assetPath)
        {
            if (_Cache.Contains(assetPath))
            {
                return(_Cache.Get(assetPath));
            }

            if (string.IsNullOrEmpty(assetPath))
            {
                throw new Exception("素材路径为空");
            }

            var lastDiv = assetPath.LastIndexOf('/');

            if (lastDiv == -1)
            {
                throw new Exception($"未指定bundle {assetPath}");
            }

            var result = new AssetId(
                assetPath.Substring(0, lastDiv),
                assetPath.Substring(lastDiv + 1));

            _Cache.Add(assetPath, result);
            return(result);
        }
Esempio n. 27
0
        private async Task <Person> _extractPerson(VkNet.Model.Message msg)
        {
            try
            {
                if (msg.FromId == null || msg.FromId < 1)
                {
                    throw new Exception("Invalid user id");
                }

                var    userId      = (long)msg.FromId;
                string displayName = null;
                if (!DisplayNameCache.TryGetValue(userId, out displayName))
                {
                    var users = await ApiClient.Users.GetAsync(new[] { userId });

                    if (users.Any())
                    {
                        displayName = $"{users.First().FirstName} {users.First().LastName}".Trim();
                        DisplayNameCache.Add(userId, displayName);
                    }
                }

                return(new VkPerson(this, msg.FromId.ToString(), displayName));
            }
            catch (Exception)
            {
                var id = msg.FromId?.ToString() ?? "0";
                return(new VkPerson(this, id, $"[id{id}]"));
            }
        }
Esempio n. 28
0
        int[] implement_LRU_cache(int capacity, int[] query_type, int[] key, int[] value)
        {
            var cache  = new LRUCache(capacity);
            var result = new List <int>();

            var max = long.MinValue;
            var sw  = new Stopwatch();

            sw.Start();
            for (var i = 0; i < query_type.Length; i++)
            {
                if (query_type[i] == 0)
                {
                    result.Add(cache.Get(key[i]));
                }
                else
                {
                    cache.Add(key[i], value[i]);
                }

                max = Math.Max(sw.ElapsedMilliseconds, max);
            }
            sw.Stop();
            Console.WriteLine(max);

            return(result.ToArray());
        }
Esempio n. 29
0
        public double GetElevation(double lat, double lng)
        {
            string cacheKey = GetCacheKey(lat, lng);
            double elevation;

            bool success = Cache.TryGetValue(cacheKey, out elevation);

            if (success)
            {
                _logger.Trace("Got elevation for Lat, Long ({0}, {1}) :: {2}m (CACHED)", lat, lng, elevation);
            }
            else
            {
                elevation = GetElevationFromWebService(lat, lng);
                if (elevation != 0.0)
                {
                    Cache.Add(cacheKey, elevation);
                    _logger.Trace("Got elevation for Lat, Long ({0}, {1}) :: {2}m", lat, lng, elevation);
                }
            }

            // Always return a slightly random elevation.
            if (elevation != 0.0)
            {
                elevation = ApplyRandomness(elevation);
            }

            return(elevation);
        }
Esempio n. 30
0
 private void AddItems(LRUCache <int, string> cache, int numEntryToAdd)
 {
     for (var i = 0; i < numEntryToAdd; i++)
     {
         cache.Add(i, i.ToString());
     }
 }
Esempio n. 31
0
        /// <summary>
        /// Syncs buffer.
        /// </summary>
        private int SyncBuffer(long idx)
        {
            // calculate the buffer position.
            var bufferPosition = idx - (idx % _bufferSize);

            // check buffer.
            if (_cachedBuffer == null ||
                _cachedBuffer.Position != bufferPosition)
            { // not in buffer.
                if (!_cachedBuffers.TryGet(bufferPosition, out _cachedBuffer))
                {
                    var newBuffer = new T[_bufferSize];

                    var arrayIdx      = (long)System.Math.Floor((double)bufferPosition / _accessorSize);
                    var localIdx      = bufferPosition % _accessorSize;
                    var localPosition = localIdx * _accessors[(int)arrayIdx].ElementSize;

                    _accessors[(int)arrayIdx].ReadArray(localPosition, newBuffer, 0, _bufferSize);
                    _cachedBuffer = new CachedBuffer()
                    {
                        Buffer   = newBuffer,
                        IsDirty  = false,
                        Position = bufferPosition
                    };
                    _cachedBuffers.Add(_cachedBuffer.Position, _cachedBuffer);
                }
            }
            return((int)(idx - bufferPosition));
        }
        /// <summary>
        /// Use this to get events for a given user.
        /// </summary>
        /// <param name="limit">Limits the number of events returned (defaults to 500).</param>
        /// <param name="streamType">Restricts the types of events returned: all returns all events; changes returns events that may cause file tree changes such as file updates or collaborations; sync returns events that may cause file tree changes only for synced folders.</param>
        /// <param name="streamPosition">The location in the event stream from which you want to start receiving events. You can specify the special value 'now' to get 0 events and the latest stream_position value. Defaults to 'now'.</param>
        /// <param name="dedupeEvents">Whether or not to automatically de-duplicate events as they are received. Defaults to true.</param>
        /// <returns></returns>
        public async Task <BoxEventCollection <BoxEnterpriseEvent> > UserEventsAsync(int limit = 500,
                                                                                     UserEventsStreamType streamType = UserEventsStreamType.all,
                                                                                     string streamPosition           = "now",
                                                                                     bool dedupeEvents = true)
        {
            BoxRequest request = new BoxRequest(_config.EventsUri)
                                 .Param("stream_type", streamType.ToString())
                                 .Param("limit", limit.ToString())
                                 .Param("stream_position", streamPosition);

            IBoxResponse <BoxEventCollection <BoxEnterpriseEvent> > response = await ToResponseAsync <BoxEventCollection <BoxEnterpriseEvent> >(request).ConfigureAwait(false);

            if (dedupeEvents)
            {
                List <BoxEnterpriseEvent> filteredEvents = new List <BoxEnterpriseEvent>();
                foreach (var e in response.ResponseObject.Entries)
                {
                    bool notUsed = true;
                    if (!USER_EVENTS_DEDUPE_CACHE.TryGetValue(e.EventId, out notUsed))
                    {
                        USER_EVENTS_DEDUPE_CACHE.Add(e.EventId, true);
                        filteredEvents.Add(e);
                    }
                }

                response.ResponseObject.Entries = filteredEvents;
            }

            return(response.ResponseObject);
        }
Esempio n. 33
0
        public void TestRetrieveItemThatDoesntExist()
        {
            var cache = new LRUCache<UUID, String>(MAX_CACHE_SIZE);
            String testData = "Test Data";
            UUID id = UUID.Random();

            cache.Add(id, testData);

            String entry = null;
            Assert.AreEqual(1, cache.Size);
            Assert.AreEqual(1, cache.Count);
            Assert.IsFalse(cache.TryGetValue(UUID.Random(), out entry));
            Assert.IsNull(entry);
        }
Esempio n. 34
0
        public void TestSimpleCacheAndRetrieval()
        {
            var cache = new LRUCache<UUID, String>(MAX_CACHE_SIZE);
            String testData = "Test Data";
            UUID id = UUID.Random();

            cache.Add(id, testData);
            Assert.IsTrue(cache.Contains(id));
            Assert.AreEqual(1, cache.Size);

            String entry;
            Assert.IsTrue(cache.TryGetValue(id, out entry));
            Assert.AreEqual(testData.Length, entry.Length);
            Assert.AreEqual(1, cache.Size);
        }
Esempio n. 35
0
        public void TestAgingRemovesEntriesPastExpirationInterval()
        {
            var cache = new LRUCache<UUID, String>(10, maxAge : 1000);

            UUID firstEntryId = UUID.Random();
            String firstEntryData = "First Entry";
            cache.Add(firstEntryId, firstEntryData);

            Thread.Sleep(2 * 1000);
            cache.Maintain();

            Assert.AreEqual(0, cache.Count);
            Assert.AreEqual(0, cache.Size);

            String lastInsertedValue;
            Assert.IsFalse(cache.TryGetValue(firstEntryId, out lastInsertedValue));
            Assert.IsNull(lastInsertedValue);
        }
Esempio n. 36
0
        public void TestLRUCache()
        {
            var cache = new LRUCache<string, int>(3); // make a tiny cache of three elements

            Assert.IsTrue(cache.Capacity == 3 && cache.Count == 0);

            // add three elements

            Assert.IsFalse(cache.ContainsKey("one"));
            Assert.IsTrue(cache.Get("one") == 0);
            cache.Add("one", 1);
            Assert.IsTrue(cache.ContainsKeyAt("one", 0));
            Assert.IsTrue(cache.Get("one") == 1);
            Assert.IsTrue(cache.Count == 1);

            Assert.IsFalse(cache.ContainsKey("two"));
            Assert.IsTrue(cache.Get("two") == 0);
            cache.Add("two", 2);
            Assert.IsTrue(cache.ContainsKeyAt("two", 1));
            Assert.IsTrue(cache.Get("two") == 2);
            Assert.IsTrue(cache.Count == 2);

            Assert.IsFalse(cache.ContainsKey("three"));
            Assert.IsTrue(cache.Get("three") == 0);
            cache.Add("three", 3);
            Assert.IsTrue(cache.ContainsKeyAt("three", 2));
            Assert.IsTrue(cache.Get("three") == 3);
            Assert.IsTrue(cache.Count == 3);

            // we're at capacity. if we add another element,
            // "one" will get evicted since it's least recently used

            Assert.IsTrue(cache.Count == cache.Capacity);

            cache.Add("four", 4);
            Assert.IsTrue(cache.Get("four") == 4);

            Assert.IsTrue(cache.Count == 3);
            Assert.IsTrue(cache.ContainsKeyAt("four", 2));  // from the youngest
            Assert.IsTrue(cache.ContainsKeyAt("three", 1)); // ...
            Assert.IsTrue(cache.ContainsKeyAt("two", 0));   // to the oldest
            Assert.IsFalse(cache.ContainsKey("one"));

            // now let's touch "two" because that's the least recently used one.
            // by doing that, we demote "three" to be the least recently used one,
            // and adding a new entry will then evict it.

            Assert.IsTrue(cache.Get("two") == 2); // reading the key will touch it
            Assert.IsTrue(cache.ContainsKeyAt("two", 2));   // now two is the youngest
            Assert.IsTrue(cache.ContainsKeyAt("four", 1));  // ...
            Assert.IsTrue(cache.ContainsKeyAt("three", 0)); // and three is the oldest

            Assert.IsTrue(cache.Count == cache.Capacity);

            cache.Add("five", 5);
            Assert.IsTrue(cache.Get("five") == 5);

            Assert.IsTrue(cache.Count == 3);
            Assert.IsTrue(cache.ContainsKeyAt("five", 2)); // youngest
            Assert.IsTrue(cache.ContainsKeyAt("two", 1));  // ...
            Assert.IsTrue(cache.ContainsKeyAt("four", 0)); // oldest
            Assert.IsFalse(cache.ContainsKey("three")); // evicted as lru

            // finally we remove one item, dropping the count.
            // adding another item will not cause evictions

            Assert.IsTrue(cache.Remove("four"));
            Assert.IsFalse(cache.ContainsKey("four"));
            Assert.IsTrue(cache.Get("four") == 0);

            Assert.IsTrue(cache.Count == cache.Capacity - 1);

            cache.Add("six", 6);
            Assert.IsTrue(cache.Get("six") == 6);

            Assert.IsTrue(cache.Count == 3);
            Assert.IsTrue(cache.ContainsKeyAt("six", 2));  // youngest
            Assert.IsTrue(cache.ContainsKeyAt("five", 1)); // ...
            Assert.IsTrue(cache.ContainsKeyAt("two", 0));  // oldest
            Assert.IsFalse(cache.ContainsKey("four"));   // removed manually

            // test clearing

            cache.Clear();
            Assert.IsTrue(cache.Count == 0);
        }
Esempio n. 37
0
        public void LogFunctionNames(bool value)
        {
            if(value)
            {
                var pc_cache = new LRUCache<uint, string>(10000);
                var messageBuilder = new StringBuilder(256);

                SetHookAtBlockBegin((pc, size) =>
                {
                    string name;
                    if(!pc_cache.TryGetValue(pc, out name))
                    {
                        name = Bus.FindSymbolAt(pc);
                        pc_cache.Add(pc, name);
                    }

                    messageBuilder.Clear();
                    this.Log(LogLevel.Info, messageBuilder.Append("Entering function ").Append(name).Append(" at 0x").Append(pc.ToString("X")).ToString());
                });
            }
            else
            {
                SetHookAtBlockBegin(null);
            }
        }
Esempio n. 38
0
        public void TestOverflowCacheWithSmallerItem()
        {
            var cache = new LRUCache<UUID, String>(10);
            String testData = "Test Data";

            for (int i = 0; i < 10; i++)
            {
                var id = UUID.Random();
                cache.Add(id, testData);
            }

            Assert.AreEqual(10, cache.Count);
            Assert.AreEqual(10, cache.Size);

            UUID overflowId = UUID.Random();
            String overflowData = "OverFlow";
            cache.Add(overflowId, overflowData);

            Assert.AreEqual(10, cache.Count);
            Assert.AreEqual(10, cache.Size);

            String lastInsertedValue;
            Assert.IsTrue(cache.TryGetValue(overflowId, out lastInsertedValue));
            Assert.AreEqual(overflowData, lastInsertedValue);
        }
Esempio n. 39
0
        public void TestOverflowReplacesFirstEntryAdded()
        {
            var cache = new LRUCache<UUID, String>(10);

            UUID firstEntryId = UUID.Random();
            String firstEntryData = "First Entry";
            cache.Add(firstEntryId, firstEntryData);

            String testData = "Test Data";
            for (int i = 0; i < 10; i++)
            {
                var id = UUID.Random();
                cache.Add(id, testData);
            }

            Assert.AreEqual(10, cache.Count);
            Assert.AreEqual(10, cache.Size);

            String lastInsertedValue;
            Assert.IsFalse(cache.TryGetValue(firstEntryId, out lastInsertedValue));
            Assert.IsNull(lastInsertedValue);
        }
Esempio n. 40
0
        public void TestAgingRemovesEntriesButPreservesReservedEntries()
        {
            var cache = new LRUCache<UUID, String>(10, minSize : 1, maxAge : 1000);

            UUID firstEntryId = UUID.Random();
            String firstEntryData = "First Entry";
            cache.Add(firstEntryId, firstEntryData);

            UUID secondEntryId = UUID.Random();
            String secondEntryData = "Second Entry";
            cache.Add(secondEntryId, secondEntryData);

            Thread.Sleep(5 * 1000);
            cache.Maintain();

            Assert.AreEqual(1, cache.Count);
            Assert.AreEqual(1, cache.Size);

            String lastInsertedValue;
            Assert.IsFalse(cache.TryGetValue(firstEntryId, out lastInsertedValue));
            Assert.IsNull(lastInsertedValue);

            Assert.IsTrue(cache.TryGetValue(secondEntryId, out lastInsertedValue));
            Assert.AreEqual(secondEntryData, lastInsertedValue);
        }
Esempio n. 41
0
        public void TestAgingRemovesEntriesUsingBytesForReservedSize()
        {
            UUID firstEntryId = UUID.Random();
            String firstEntryData = "First Entry";

            UUID secondEntryId = UUID.Random();
            String secondEntryData = "Second Entry";

            var cache = new LRUCache<UUID, String>(capacity: 250, useSizing: true, minSize: secondEntryData.Length, maxAge: 1000);
            cache.Add(firstEntryId, firstEntryData, firstEntryData.Length);
            cache.Add(secondEntryId, secondEntryData, secondEntryData.Length);

            Thread.Sleep(5 * 1000);
            cache.Maintain();

            Assert.AreEqual(1, cache.Count);
            Assert.AreEqual(secondEntryData.Length, cache.Size);

            String lastInsertedValue;
            Assert.IsFalse(cache.TryGetValue(firstEntryId, out lastInsertedValue));
            Assert.IsNull(lastInsertedValue);

            Assert.IsTrue(cache.TryGetValue(secondEntryId, out lastInsertedValue));
            Assert.AreEqual(secondEntryData, lastInsertedValue);
        }
        /// <summary>
        /// Creates a new instance of LRU cache where elements are evicted based on least frequently usage.
        /// </summary>
        static void testLRUCache()
        {
            ComputerInfo computerInfo = new ComputerInfo(); //reference to Microsoft.VisualBasic assembly.

            var lru = new LRUCache<int, Image<Gray, byte>>(
                                                    (currentSize) =>
                                                    {
                                                        var occupied = computerInfo.TotalPhysicalMemory - computerInfo.AvailablePhysicalMemory;
                                                        var occupiedPercentage = (float)occupied / computerInfo.TotalPhysicalMemory;

                                                        if (occupiedPercentage > 0.85)
                                                            return true;

                                                        return false;
                                                    },
                                                    (img) => (ulong)(img.Stride * img.Height));

            lru.OnRemoveItem += lru_OnRemoveItem;

            /***************** add some elements ****************/
            var image = new Image<Gray, byte>(5 * 1024 * 1024, 1, 0);
            image.SetValue(5 % 256);
            lru.Add(1, image);

            image = new Image<Gray, byte>(5 * 1024 * 1024, 1, 0);
            image.SetValue(5 % 256);
            lru.Add(1, image);
            /***************** add some elements ****************/

            List<Image<Gray, byte>> a = new List<Image<Gray, byte>>();

            Random rand = new Random();

            int i = 0;
            while (i < 10000)
            {
                image = new Image<Gray, byte>(1024 * 1024, 1, 0);
                image.SetValue(i % 256);
                lru.Add(i, image);

                //Thread.Sleep(1);
                Console.WriteLine(computerInfo.AvailablePhysicalMemory / 1024 / 1024);
                i++;
            }

            //discover more properties and methods!
        }
Esempio n. 43
0
        public void TestFillCache()
        {
            var cache = new LRUCache<UUID, String>(10);
            String testData = "Test Data";

            for (int i = 0; i < 10; i++)
            {
                var id = UUID.Random();
                cache.Add(id, testData);
            }

            Assert.AreEqual(10, cache.Count);
            Assert.AreEqual(10, cache.Size);
        }