Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
You can't really distinguish between a writeback cache and a write-through cache with this procedure. Consider: If you're using a writeback cache, it takes X time to execute the instructions in the loop, and Y time to write it back. Y is not measured by your code (you don't have any timing around an explicit cache flush or similar). When you loop N times, it takes N * X time, plus Y after your code is done executing to flush the cache. With a write-through cache, X is higher, and Y is zero. But the ratio of the single loop to many loops is the same. Thus, you can't tell the difference with this procedure. That said, there are ways you can detect this. The key is to force the cache to flush its cache lines while you're timing. Try comparing how long it takes to write various sizes of arrays. Between writes ensure that any writeback cache is flushed by reading a lot of unrelated data (note: don't just allocate a large array and read from it without writing to it ever - write to it once at program startup, then read the whole thing between timing runs. Otherwise all the pages in the array might point to the same zeroed-out page in physical memory, depending on your OS). You could also try seeing when writing lots of data influences the speeds of reads. In a write-through cache, reads should never take longer just because you wrote data recently. In a write-back cache, reads may have to wait for cache flushes - so timing reads on their own vs immediately after writes may give you some interesting results as well.
How do I determine by testing writes to cache the type of cache (write back/through)? I could use a similar method as I did to determine the levels and size of cache by recording the time to modify cache, but I will need to compare with something. eg. if the time is significantly shorter that a known L1 write through cache, I can say its write back. However, I will need a base line to compare with won't I? Heres my attempt at GitHub The main idea is: if its write through, time taken to write x vs x * 100 times is approximately 100 times if its write back, time will be about the same? So the time the loop for WRITES_BASE times vs time for WRITES times minus of their respective times to execute loops only (no memory access), and compare them ... this gives me the impression that my Core i3 2100 has all write through caches ... 16, 0.03, 1.04 (31.28) 128, 0.07, 2.31 (31.78) 2048, 0.10, 3.19 (31.74) The above values are: test size (KB), time for WRITES_BASE, time for WRITES (t(WRITES)/t(WRITES_BASE)) I am guessing the problem with my experiment is I haven't eliminated the time difference that I am running WRITES more times... UPDATE An oddity I noticed is if I keep my WRITES = 64 * WRITES_BASE, then if I have my WRITES_BASE = 4 million. 16, 0.01, 0.13 (17.16) 128, 0.01, 0.29 (31.60) 2048, 0.01, 0.41 (30.53) If I increase x * 1000 x * 1001 Notice, when x * 1002 is smaller, the difference between the times are less, perhaps telling me L1 is a write back cache. However, since its not always true, eg. when I increase WRITES_BASE, I wonder if I am having some logic error?
Determine if cache is write back or through
How you store the data on the client side doesn't matter very much. I'd look into IsolatedStorage for your purposes, though. What might be more difficult is to tell when the cache turns stale. This is actually what System.Runtime.Caching is good at. Does the server data change at all, or only after a new release of the application? If the data changes only after a new release, you might want to include it as resources into the application setup. If not, you'd have to have some timeout or signal which tells the client that it is time to check for changed data on the server. Have you already considered lazy loading of the data? That way, the delay would probably not occur all at application startup and would be less noticable, and probably you wouldn't even have to load the complete data into the client. Regarding Timeouts: in our application, we have a fixed timeout which is set to each reference list when it is first loaded, and every time it is requested from the cache, that timeout is checked. If it has expired, the cache is transparently refreshed before the list is returned. This is a tradeoff, because the data on the client side could be stale for some time. We accept this, because it isn't critical in our case, and that way every list is responsible for itself and we don't need a central registry keeping track of each list's state in order to set the timeout from outside.
My wpf client is loading a lot of standing data at startup from the server. So, I want to implement a caching strategy at client side. I know about the new System.Runtime.Caching namespace in the .NET framework 4. Unfortunately, there is only a memory caching. I don't want to load the huge amount of data at each startup of the client. So I'm searching for a persistent client caching. What do you think about it? Another idea was I use an OODB (like db4o or VelocityDB) for client caching. Is this a bad idea? I haven't any experience in client caching. Thanks for your answers and suggestions. Kind regards, pro
Clientside Caching C#
2 +25 Guy, I would turn on Dyna cache trace to see why this error occurs Trace String: com.ibm.ws.cache.=all:com.ibm.ws.drs.=all This should give us clues on what is happening and depending on what we see from the trace would provide us info on what to do next. HTH Share Improve this answer Follow answered Oct 4, 2012 at 6:36 MangluManglu 11k1212 gold badges4646 silver badges5858 bronze badges 0 Add a comment  | 
I'm trying to implement a Dynacache CacheProvider and having problems. Here is what I've done: I've got my Dynacache CacheProvider implementation jar under D:\IBM\WebSphere85\AppServer\lib I have com.ibm.ws.cache.CacheConfig.cacheProviderName configured as JVM custom property with the correct CacheProvider implementation class. Created cacheinstance.properties located under D:\IBM\WebSphere85\AppServer\properties with the relevant settings including the com.ibm.ws.cache.CacheConfig.cacheProviderName right class name value. I have the cacheinstance.properties also part of the Dynacache CacheProvider implementation jar. I have the Object cache Instance configured to have a new dyna cache. This also have the com.ibm.ws.cache.CacheConfig.cacheProviderName as a custom system property. My application using the following to access the cache: code: Properties props = new Properties(); props.put("com.ibm.ws.cache.CacheConfig.cacheProviderName","com.myCacheProvider"); map = (DistributedObjectCache)DistributedObjectCacheFactory.getMap("mycache",props); I'm getting the following when the application trying to access DynaCache: [9/18/12 10:10:52:917 EDT] 00000050 ServerCache E DYNA1066E: Unable to initialize the cache provider "com.myCacheProvider". The Dynamic cache will be used to create the cache instance "default" instead of the configured cache provider. [9/18/12 10:10:52:919 EDT] 00000050 ServerCache E ENGLISH ONLY MESSAGE: cacheProvider is null. Check for the cache provider libraries [9/18/12 10:10:52:920 EDT] 00000050 ServerCache I DYNA1001I: WebSphere Dynamic Cache instance named default initialized successfully. I'm using WAS 8.5. Any ideas what is going on and how to debug this?
How to configure Dynacache CacheProvider?
A few things to note : You can use the EXISTS to check if the key already exists. This is better because you can now cache users that actually have 0 transactions. INCR and INCRBY commands will create the key if it doesn't already exists So, in pseudo code, here's what you should do - if EXISTS user:<userid>:transcount return GET user:<userid>:transcount else int transCountFromDB = readFromDB(); INCRBY user:<userid>:transcount transCountFromDB return transCountFromDB You may also want to execute an EXPIRE command on the key right after you do INCRBY, so that you only cache records for an acceptable time.
I am using ServiceStacks CacheClient and Redis libraries. I want to cache counts of the number of certain transactions that users perform. I am using the following to GET the cached value or create it from the DB if the key does not exist: public int GetTransactionCountForUser(int userID) { int count; //get count cached in redis... count = cacheClient.Get<int>("user:" + userID.ToString() + ":transCount"); if (count == 0) { //if it doent exists get count from db and cache value in redis var result = transactionRepository.GetQueryable(); result = result.Where(x => x.UserID == userID); count = result.Count(); //cache in redis for next time... cacheClient.Increment("user:" + userID.ToString() + ":transCount", Convert.ToUInt32(count)); } return count; } Now, in another operation(when the transaction occurs) I will add a row to the DB and I would like to increment my Redis counter by 1. Do I first need to check to see if the particular key exists before incrementing? I know that the Increment method of cache client will create the record if it does not exists, but in this case the counter would start at 0 even if there are transaction records in the DB. What is the proper way to handle this situation? Get key, if null, query db to get count and create the key with this number?
How to use ServiceStack CacheClient and Redis to increment or create counters
2 I suggest you using base64 embed images in your webview. it will cause the webview to load the image like text almost immediately. Take a look at the link below for converting your image to Base64: http://www.dailycoding.com/Utils/Converter/ImageToBase64.aspx and for using it in your html: http://danielmclaren.com/2008/03/embedding-base64-image-data-into-a-webpage Hope it helps. :) Share Improve this answer Follow answered Sep 23, 2012 at 22:51 ShahinShahin 88566 silver badges2121 bronze badges 2 Thanks for the tip Shahin! I'll investigate this option. – Tetyana Sep 24, 2012 at 14:44 You are so welcome Tetyana. Hope it help solving your problem :) – Shahin Oct 13, 2012 at 21:33 Add a comment  | 
I'm an appreneur creating iPhone apps, doing everything but coding which is outsourced. I'd appreciate some technical guidance on the following iOS 5 implementation of a simple utility app. There is a custom-built rich text field where users can input images (stored locally, small size: 40x44 points) and text. This is implemented as UIWebView. With the current implementation, each time after an image is tapped, it appears after 1.5-2 sec delay (too long). After it's entered once, it's cached and next time it appears almost immediately. Is it reasonable that such small images would take up to 2 sec to appear? Are there any efficient ways of reducing this time lag for non-cached images? Any tips would be very welcome. If there is any smart way of implementing this other than using UIWebView, it would also help. Thanks in advance.
Time lag of loading local images in UIWebView
Many sites use "infinite" scrolling where many, many images are allowed to be loaded at once. I believe most browsers manage memory based on what is actually being displayed. Having "infinite" scrolling can be more user friendly than doing pagination in some situations. You can have a "last modified" tag on a thread - then when you check for normal updates from the site you can compare the last modified with the stored date in the html. If the change is recent then get and update the latest versions of the posts. Honestly it's probably not worth worrying about - people are used to reloading their browser to check for changes.
In an attempt to improve responsiveness, I'm figuring that it would be a good idea to preload paginated data. The reasoning goes like this: When a user reads through paginated data, they are most likely to go through the pages in order. Therefore, it would make sense to spend the time taken for the user to read the current page, loading the following page into memory (AJAX call, save the resulting HTML, and then just having the "next page" link replace the content's innerHTML instead of loading a new page). Similarly, I can keep previously loaded pages in memory so that, if the user goes back, the page can reappear instantly without having to make another roundtrip to the server. My main concern is the impact this may have on the browser's RAM usage. I mean, all of a sudden I'm having it hold several pages instead of just one. That said I've been on webpages that are a good hundred times bigger than a single page of my layout and they worked just fine, so am I overthinking this? My other concern is that the data may change (I'm currently thinking of the forums, where a user may edit a post or (in the case of the last page) a new post may be made. I guess I could avoid storing the last page in memory, but is there any way I can go about checking for modified posts without defeating the purpose of the whole cache system? The best I can come up with is similar to static resource caching, where a request can be made but the server can respond with Not Modified if that's the case. But then again there's likely to be a whole lot more viewing of pages than editing them, so almost all of the requests would be Not Modified. I'm just not sure how to go about doing all this, or if it's just not worth worrying about.
Preloading pages, various questions about it
2 SharePoint Client Object Model will not support Object Cache w.r.t the Client objects. That is the limitation in Client Object Model. Share Improve this answer Follow answered Aug 14, 2012 at 15:15 imSantoshKumarimSantoshKumar 19477 bronze badges 2 1 Actually using ObjectCache i tried caching ClientContext and It worked fine for me. But my problem is I need it in Distributed Cache like AppFabric – user1597990 Aug 14, 2012 at 15:36 1 @user1597990, could you share your experience about caching the ClientContext on local machine? We are looking for similar solution: social.msdn.microsoft.com/Forums/sharepoint/en-US/… – windfly2006 Aug 13, 2014 at 16:58 Add a comment  | 
I need to Cache certain objects which are based on SharePoint Managed Client Object Model like ClientContext, GroupCollection, User , List etc. Initially I tried using Appfabric cache but it gives some issues like "cannot be serialized" . Here my question is "Is it possible to serialize SharePoint Managed Client Object Model based Objects?" . Next I tried with .NET ObjectCache which actually caches the SP's Managed Client Objects but problem over here is I need a distributed / unified caching technique. As per my knowledge we cant make ObjectCache distributed over multiple hosting servers. Can anyone suggest me a solution or show me light to proceed. Thanks in advance.
How to Cache Sharepoint Managed Client Object Model based objects?
It is one of the known issues in Zend Framework community. It even was reported as an improvement for 1.0.3 release (http://framework.zend.com/issues/browse/ZF-2311). You fix make sense for Magento where a lot of calls to Zend_Currency is performed and connection to memcached having some limitations or slow enough. For instance on most of the projects we are using memcached and haven't experienced too big loss in page load time with this calls. However you can fix it in Magento to make a workaround with ZF: Rewrite core/locale model in your module Override currency() method public function currency($currency) { if (!isset(self::$_currencyCache[$this->getLocaleCode()][$currency])) { $currencyObject = parent::currency($currency); $currencyObject->setFormat(array( 'format' => Zend_Locale_Data::getContent($this->getLocale(), 'currencynumber') )); return $currencyObject; } return parent::currency($currency); }
today I realized that the Magento doest a lot of same requests to my memcached server, it's requesting the key Zend_LocaleC_en_GB_currencynumber_ . Do you anyone know where is it generated and how can I improve it? It's probably somehow related to rendering of price box but I dont see reason why it's 50 times in a page. Thanks, Jaro. Edited: So far I did quick fix Zend_Cache_Backend_Memcached::load public function load($id, $doNotTestCacheValidity = false) { if ( isset($GLOBALS[$id]) ) { return $GLOBALS[$id]; } $tmp = $this->_memcache->get($id); if (is_array($tmp) && isset($tmp[0])) { $GLOBALS[$id] = $tmp[0]; return $tmp[0]; } return false; } It's not nice but seems to be working. At least many of requests agains memcached server disappeared. Jaro.
Magento - many of same cache requests
2 There are a couple different options. If the etag is generated based on the content (a bad idea), then it's more difficult. In our solution, we generated a different tag (a ptag) that we updated when properties changed, and you could query it with a PROPFIND, and we returned it as an X-PTag header on the response. If the etag is generated randomly on a PUT, then you could PUT the same data again, and it would give you a new etag. Share Improve this answer Follow answered Sep 5, 2012 at 17:31 KylarKylar 9,1061010 gold badges4242 silver badges7575 bronze badges Add a comment  | 
I'm using WebDav to put metadata on the files and folders of a server, along with a cache to avoid unnecessary requests to the server, based on the ETag property of the files. Basically, I send a HEAD request and check whether the ETag matches the one I have in local. If it doesn't, then I send a larger, slower PROPFIND method to retrieve the other properties. I built this cache on the idea that the ETag was changed every time the file was modified, including when metadata were modified, added or deleted. However, I've recently discovered that it is not the case : Because clients may be forced to prompt users or throw away changed content if the ETag changes, a WebDAV server should not change the ETag (or the Last-Modified time) for a resource that has an unchanged body and location. The ETag represents the state of the body or contents of the resource. There is no similar way to tell if properties have changed. (RFC 4918, http://www.webdav.org/specs/rfc4918.html#etag, emphasis mine) Since invalidating the cache whenever properties are changed is important to me, I was wondering: is there a way to manually instruct the web server to renew the ETag ?
Renewing a HTTP ETag
Different browsers acknowledge different values in the Cache-Control Header. As far as I know (though I can't cite any great source right now) to make sure no caching is performed in any browser the Cache-Control Header can be set to "max-age=0, private, no-store, no-cache, must-revalidate".
I have a web application that uses the same Twitter authentication code as the Sinatra app imonaplane. The homepage is either showing "Sign in with Twitter" or personalized content. After signing in, you're redirected (via HTTP 302) to the homepage: get '/session_auth' do if params[:oauth_verifier] access_token = twitter_client.authorize( session[:request_token], session[:request_token_secret], oauth_verifier: params[:oauth_verifier]) if twitter_client.authorized? user = db.load(User.to_id(twitter_client.info['screen_name'])) || User.new(login: twitter_client.info['screen_name'], twitter_access_token: access_token.token, twitter_secret_token: access_token.secret) db.save! user session[:user_id] = user.id end end redirect '/' end This works fine in Firefox 14.0.1 and Safari 5.1.7 and the iOS simulator. However, it seems as if Mobile Safari on iOS 5.1.1 is caching the generalized homepage. This gives the impression that you're not logged in because it's still showing "Sign in with Twitter." Reload will show the personalized content. This is running on Heroku, Cedar stack. No HTTP cache headers are used. What's the problem here? Should I tell the browser explicitly to not cache the homepage, possibly with a Cache-Control: private header?
How do I keep Mobile Safari from caching a personalized homepage?
I don't think that it gets removed, but there is auto-failover provided if you have multiple nodes added. You can configure that failover behaviour here: http://php.net/manual/en/memcache.ini.php Here is a quote from the documentation: Failover may occur at any stage in any of the methods, as long as other servers are available the request the user won't notice. Any kind of socket or Memcached server level errors (except out-of-memory) may trigger the failover. Normal client errors such as adding an existing key will not trigger a failover. Of course, this assumes that all data is mirrored on those nodes, because you have to implement sharding/clustering on your application side.
I am using Memcache (Not memcacheD) . If I have 10 memcache servers and 1 of it fails does that get removed from pool automatically ? I mean when my application tries to make a request for cache will it ever try to get key data from that 1 failed server ?
Memcache Failover
There is a potential inconsistent in your code that DateTime.Today.AddHours(6) that will not work. you should use DateTime.Now.AddHours(6) DateTime.Today is current day starting 12:00 AM , if you code runs after 6:00 AM obviously the httpruntime cache isn't available.
I have a thread running behind my ASP.Net. In this thread I put data in the cache like this: HttpRuntime.Cache.Insert("test", "test", null, DateTime.Today.AddHours(6), Cache.NoSlidingExpiration); On the other thread(the webpage) I first check if the cache contains any data, and then try to get the object from the cache, like this: if (HttpRuntime.Cache.Count > 0) { var test = (string)HttpRuntime.Cache["test"]; } Edit: Everytime when I'm trying to do var test = (string)HttpRuntime.Cache["test"];the cache will go empty(or will delete the object, haven't tested multiple objects in cache) plus the var test is also null. This is ofcourse when HttpRuntime.Cache.Count is bigger than 0 Oh and it gives no exceptions or anything
Accessing HttpRuntime.Cache from other Thread
There are no changes in the object size. Its the same - 8MB serialized. Thanks!
Is there a limit to a single item (object) size in Azure Cache Preview? I know that Azure Shared Cache has that limitation (8MB serialized) but I can not find that kind of information for the new Cache.
Azure Cache (Preview) item size limit
1 pass a parameter to on the script source which will force a reload of the script... in fact you could do it by version or similiar <script src="/test/script/myawesomescript.js?ver=1.0&pwn=yes" ...> that would work and be seemless to the other users... when you feel like it has been long enough go back to the old way. but this will work if you want to force a refresh from users. This method is utilized to prevent caching of webpages by some frameworks. Let me know if you were successful http://css-tricks.com/can-we-prevent-css-caching/ -- here is a link to the concept for css (should work in js too) -- the biggest difference is you dont want it to never cache, so dont use a time stamp, use my style like from above :) enjoy! Share Improve this answer Follow answered Jun 12, 2012 at 19:30 RyanRyan 2,7651717 silver badges3030 bronze badges Add a comment  | 
I've recently added HTTP headers to my site to inform the browser to check with the server every time it comes across a given JS/CSS URL. I've tested it and it works perfectly; all browsers now make conditional GET requests. Here's the problem though -- people still have the old headers cached; headers which more or less told the browser "cache this forever; don't bother asking for an update!". This can be busted with a hard refresh. I don't want to have to communicate to everyone to please hit F5 on any buggy pages after we push out code. Are there any HTTP header(s)/HTML meta tag(s) I could put on the HTML document itself to say "Browser, ignore the headers you have on the JS/CSS files and download the latest version of all the included files on this page"? Eventually this problem will work itself out as more and more people clear their cache or learn to refresh on their own. But, I'd rather fix it now. Then in a month or so, I'll remove the HTML-level headers to get caching where I want -- on a per resource basis. EDIT: I do not want to rename the resources or add on query parameters. That's what we used to use (?v=18, ?v=19, etc.) and it was a chore to increment that number every time we updated resources. Even doing that programmatically isn't the ideal solution; especially now that our server is configured correctly. It makes more sense to do it on the HTTP level so it works regardless of how you're accessing it -- included on a page, directly from the address bar, or otherwise.
HTTP Headers - Hard refresh JavaScript/CSS
The headers are fine. Cache-Control: public and future Expires should do the job. It seems like it's the browser's decision not to store the cache permanently (that kind of paranoia about HTTPS data is typical), and I don't think you can do anything about that.
I'm having some problems with caching images on my web app. The images are cached after refreshing, but when I reopen the browser it's not cached anymore. I'm using HTTPS, but I'm not sure it's the problem. This is the response from the server: Response Headers Accept-Ranges: bytes Cache-Control: public Connection: close Content-Length: 3711 Content-Type: image/png Date: Mon, 21 May 2012 14:08:46 GMT ETag: "446b5-e7f-4c0559b8c1c9f" Expires: Wed, 20 Jun 2012 14:08:46 GMT Last-Modified: Fri, 18 May 2012 20:43:41 GMT Server: Apache/2.2.22 (Amazon) And our httpd.conf NameVirtualHost *:80 NameVirtualHost *:443 <VirtualHost *:80> ServerName [REMOVED] RewriteEngine on ReWriteCond %{SERVER_PORT} !^443$ RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R,L] </VirtualHost> <VirtualHost *:443> ServerName [REMOVED] #Force image type AddType image/png .png AddType image/jpeg jpeg jpg jpe AddType font/x-woff .woff #Cache ExpiresActive On ExpiresDefault A0 <FilesMatch "\.(png|jpg|jpeg|gif)$"> ExpiresDefault "access plus 1 month" Header set Cache-Control "public" </FilesMatch> #Logs ErrorLog logs/ssl_error_log TransferLog logs/ssl_access_log LogLevel warn #SSL SSLEngine on SSLProtocol all -SSLv2 SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW SSLCertificateFile [REMOVED] SSLCertificateKeyFile [REMOVED] SSLCertificateChainFile [REMOVED] SetEnvIf User-Agent ".*MSIE.*" \ nokeepalive ssl-unclean-shutdown \ downgrade-1.0 force-response-1.0 CustomLog logs/ssl_request_log \ "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b" #Proxy DocumentRoot [REMOVED] ProxyPreserveHost On ProxyRequests Off ProxyPass [REMOVED] http://localhost:8081/[REMOVED] ProxyPassReverse [REMOVED] http://localhost:8081/[REMOVED] ProxyPassReverseCookiePath [REMOVED] / Alias [REMOVED] [REMOVED] </VirtualHost> Any clue? Thanks!
HTTPS images not caching
You can try to use the flag when connecting: INTERNET_FLAG_DONT_CACHE = 0x04000000 Does not add the returned entity to the cache. This is identical to the preferred value, INTERNET_FLAG_NO_CACHE_WRITE. Or you can take a look at the DeleteUrlCacheEntry from the WinInet documentation here I beleave this should do the trick. --UPDATE From this doc I've seen that there is an better flag to use it, look at the: INTERNET_FLAG_PRAGMA_NOCACHE Forces the request to be resolved by the origin server, even if a cached copy exists on the proxy. --UPDATE As tested by @Pradeep you can change this registry keys to work it: HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\DnsCacheEnabled ServerInfoTimeOut and DnsCacheTimeout to 0.
WinINet library caches IP address for any URL accessed over it. Because of this, when IP address for that URL gets changed then also WinInet library's HttpSendRequest goes to older IP address. And, if older IP is responding, then WinINet will send all http request to older IP only. Is there any way to force clean DNS cache of WinInet? Or Is there any way to force WinINet to send HTTP request to specified IP address (as we are able to get newer IP using gethostbyname())? Note : gethostbyname is giving me newer IP address, So this behaviour is happening of WinINet's caching. I have tried "method 2" suggested in this MS article, but it didn't help Sample code
Clear WinInet DNS cache programmatically
2 Try to put the google map JavaScript files into your cache manifest file. let's say your files source are <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3.3&libraries=geometry&sensor=true"></script> <script type="text/javascript" src="https://www.google.com/jsapi"></script> Put the source values of your Google map apis into your cache manifest file and than check your application again, it might help you to zooming the map faster. Put your own api's which you used. Share Improve this answer Follow answered May 7, 2012 at 7:57 TalhaTalha 19k88 gold badges5050 silver badges6666 bronze badges Add a comment  | 
I'm currently developing a mobile application using html5 + phonegap, and everything is working well.. The only issue I'm having is that scrolling through a map on a phonegap made native app it's sluggish and slow, zooming on the map is quite slow as well. Is there any way to increase map rendering speed / tile loading using html5 and / or cache manifest file? I was reading around and saw something about using cache manifest to combat these quirks? I haven't found any good documentation on it so I figured I would ask here? Any help in speeding up map loading is greatly appreciated!
How do I leverage HTML5 Cache Manifest with Google Maps Javascript API V3 for a faster experience
Probably the problem is that settings are read from the database just when the application starts...then probably they are stored in a static variable or in the application state dictionary. If this is the case, you may solve it by writing an admin page that after having changed the settings, forces to reload the settings from the database.
I have an Email-listening application that handles incoming mails, depending on the "Bucket" (or Queue) the emails are in. One of the settings for each bucket is "AutoRespond". If AutoRespond is true, I send a confirmation email back to the sender. However, when I change the AutoRespond setting, it doesn't seem to be taking effect. I'm familiar w/ setting OutputCache on a controller, but this logic below is from my Email-listening service cs file. if (myObject.Bucket.AutoRespond) { SendEmailConfirmation(someArgs); } This if statement is still evaluating as True, even though I can see it set to False in the database. If I restart my Email-listening service, all is well, and this if statement evaluates correctly. Any ideas?
Why is my MVC app caching this setting?
I would go with Cache the approach. Some of the reasons being: You can control for how long an object will be held in Cache before the memory is released. Under heavy load this could allow the server to respond better. If it's worth the effort, I may even go further and use some sort of distributed Cache so that it survives app pool recycling. Memcache and NCache come to mind. I dislike the Singleton approach. It seems to me that you'll be reinventing the wheel when you can perfectly use Cache for this. Concurrency will be as much an issue as will be with Cache and you lose the flexibility of using a distributed Cache. Whatever approach you take, I'd create a wrapper class to store and retrieve objects from Cache that would allow you to easily change from the traditional Cache to a distributed Cache in the future seamlessly.
I am writing a control that displays a list of items on the page. The database holds (lets say) 50,000 items which are related (many to many) with (lets say) 1000 pages. Instead of writing a stored procedure to return a set of complete items for a given page from the database (i.e. all columns, in order to hydrate a list of item objects), I am thinking of doing the following to render a list: on application startup, caching all listing items getting the SP to return just the key value for the items looping through the list of keys & retrieving the matching object from cache Preliminary tests indicate this performs faster than hydrating a list from the DB for each page request. It also seems to cause less overall memory consumption, as each page request would just look up existing objects, as opposed to each request making a private list (when traffic is high and large pages are requested memory consumption gets very high). So now I am debating with fellow developers how to implement the cache. We have come up with several options, and this is where I would appreciate your opinions: Use the ASP.NET HttpContext.Current.Cache Use static/singleton objects Within each of these there is also a choice whether to: Cache each item object individually Build a dictionary (or similar list) containing all item objects then cache the dictionary Read performance is the main concern. Maintenance is a secondary concern - we would write our GetItems methods defensively to check if each item is in the cache and if not, retrieve it from the DB and insert it into the cache. I know there is no right answer ... there are pros & cons for everything. I am just looking to see if people have pitfalls they can share about any of the above, or if any approach stands out as being by far the best performing, or is particularly hard to merge new data into. Thanks
Approaches to caching large number of objects (ASP.NET cache vs static objects & caching objects individually vs as dictionary)
You can manually "clear" the facebook cache by using the Debugger. Just go there, enter the url you changed and click "debug", that will cause the facebook bot to request the data from your servers even if it was already fetched and cached, and the new data will replace the old. Edit 800k of pages is a lot, no doubt. According to the Like Button doc: Facebook scrapes your page every 24 hours to ensure the properties are up to date. The page is also scraped when an admin for the Open Graph page clicks the Like button and when the URL is entered into the Facebook URL Linter. Facebook observes cache headers on your URLs - it will look at "Expires" and "Cache-Control" in order of preference. However, even if you specify a longer time, Facebook will scrape your page every 24 hours. (The URL Linter is the Debugger) But from my experience it's not always the case, I haven't found any pattern to it, but I came across data that was months old and the cache was not clear until i manually used the debugger to extract the new data. If you still want to manually refresh the data fb has, you can probably write a script that posts the url to the same form action in the Debugger page, I don't think they are using a csrf protection. In that way you can automate this action for all your pages, it might take a while, but nothing too serious.
How long is the timeout for facebook share cache. I edited all of my pages and changes must be reflected. If timeout is unlimited, i have to debug all pages via curl etc. Thanks.
Share Cache Timeout
What you're saying sounds like it'll work. You'll have to build your framework and then inject some dummy game data to see how it responds. One nice thing about gaming is that you can get away numerous loading screens/bars, so take advantage of that. :)
I'm making an engine/CMS for story-based web browser games. I have quite a bit of data: characters, items, and the bits of story that the player will interact with. The intention behind this project is that writers don't have to be programmers in order to create a narratively-driven web game. It would only require basic knowledge of FTP and website management in order to start creating content. The problem is that I think the database is going to bog these games down. Each character can have a lot to them, and the stories are going to be extensive. Each bit of story will have its own written text, which could be 100 characters or 500 characters. There's no way I could cache that all with memcached or something similar! Thankfully, each state of the game is "pushed" through a deploy, meaning you don't just add a character and they appear in the world; you have to add them, and then push a build of the game. I believe I can use this to my advantage. My working notion right now is: There will be three databases total. One will be the 'working' content DB, another the 'live' content DB, and then finally the DB that holds all user data. (where they are in the story, items they've obtained, etc.) My idea is that I'll push with the working DB, completely destroy the live, and rebuild the live based on what's in the working DB at the time of the push. The live DB will then benefit from read-only abilities: such as the ARCHIVE storage engine and quite a bit of indexing. This sounds pretty solid, but I'm not experienced enough to be confident that this is the best way to go about my business. I'd love to know if anyone has any suggestions for a new model, or even a suggestion to my current model.
Caching large amounts of content with PHP + MySQL
eAccelerator should have made a measurable difference, so are you sure it was installed correctly? You should have seen an eaccelerator section in phpinfo() showing that the cache was full. You may also have ahd the cache set too small etc. Alternatively, try APC instead. If neither show any performance improvement, you may have a server issue. In any case, 40 seconds is crazy slow for anything. Are you sure this is PHP and not poorly optimised SQL queries?
I am installing a pre-build php-based web application for a client. Unfortunately the application performs very slowly because it compiles lots of data. Page load times go up to 40 sec. I know about ob_caching but I don't want to mess with the application unless it is absolutely necessary. Are there any tools/scripts/apache modules to cache the entire output of the application statically one the server and update it on a regular basis. I am just looking for a middleware or something which build regular static html pages form the php application. (BTW: I tried eaccelerator, but it didn't improve the situation.) I would appreciate any tips. Thanks in advance.
Static caching for PHP (Apache)?
Disclaimer - I work for Oracle on Coherence. Assuming that the CPU load is going to XML marshaling, you should see reduced CPU consumption by placing the resulting objects in a cache. You'll still pay CPU for serialization, but object serialization takes much less CPU - and if you use POF for serialization you'll see even better performance. If there is any affinity to where the objects are being used, you can take advantage of near caching to avoid going to the network to retrieve cached objects. This will only help if you do more reads than writes. With Coherence you don't need to throw away your ORM - you can write a CacheStore (or use the JPA CacheStore we ship with OOTB) to transparently read from the database upon cache misses and update the database when the cache is updated. This works best if you're retrieving your ORM objects via primary key. Without more details on what exactly is taking up CPU (thread dumps are a good low tech way to diagnose this) it's hard to say how much caching will help.
We started implementing Coherence in our application to improve performance and reduce load on the DB server and reduce web service calls. We usually experience high CPU usage ( weblogic App server's JVM) during high load, DB servers are usually not an issue. Other than response time improvement, How would oracle Coherence improve application server's CPU and Heap usage during high load. 1) reduce XML processing as we will start retrieving Java Objects from the cache that are ready to be used rather than having to unmarshall the XMLs. 2) reduce ORM mapping overhead as we won't be mapping table rows to objects for cached data.... 3) What else? Thanks a lot
Oracle Coherence Caching and application server's CPU usage
Do you really need the subqueries? How about this: SELECT `l`.`status`, `l`.`acquired_by`, COALESCE(`a`.`name`, 'Unassigned') AS 'acquired_by_name', `l`.`researcher`, COALESCE(`r`.`name`, 'Unassigned') AS 'researcher_name', `l`.`surveyor`, COALESCE(`s`.`name`, 'Unassigned') AS 'surveyor_name' FROM `leads` `l` LEFT JOIN `web_users` `r` ON `r`.`id` = `l`.`researcher` LEFT JOIN `web_users` `s` ON `s`.`id` = `l`.`surveyor` LEFT JOIN `web_users` `a` ON `a`.`id` = `l`.`acquired_by` WHERE `l`.`id` = 566
I have the following MySQL query, which produces the result I want: SELECT `l`.`status`, `l`.`acquired_by`, `a`.`name` AS 'acquired_by_name', `l`.`researcher`, `r`.`name` AS 'researcher_name', `l`.`surveyor`, `s`.`name` AS 'surveyor_name' FROM `leads` `l` LEFT JOIN ( SELECT '0' AS 'id', 'Unassigned' AS 'name' UNION ALL SELECT `id`, `name` FROM `web_users` ) `r` ON `r`.`id` = `l`.`researcher` LEFT JOIN ( SELECT '0' AS 'id', 'Unassigned' AS 'name' UNION ALL SELECT `id`, `name` FROM `web_users` ) `s` ON `s`.`id` = `l`.`surveyor` LEFT JOIN ( SELECT '0' AS 'id', 'Unassigned' AS 'name' UNION ALL SELECT `id`, `name` FROM `web_users` ) `a` ON `a`.`id` = `l`.`acquired_by` WHERE `l`.`id` = 566 But as you can see, it has the same sub-query in it three times. Is there any way to execute this query once and store the result, so I can LEFT JOIN with the cached results instead of executing the same query three times? I have tried storing it in a variable: SET @usercache = ( SELECT '0' AS 'id', 'Unassigned' AS 'name' UNION ALL SELECT `id`, `name` FROM `web_users` ) ...but this gives me an error: 1241 - Operand should contain 1 column(s) ...and some Googling on this error has left me none the wiser. Does anyone know how I can make this query more efficient? Or am I just worrying about something that doesn't matter anyway? I am using PHP/MySQLi if it makes any difference.
Store the results of a sub-query for use in multiple joins
Issue solved: the browser was retrieving the elements from it's own cache and wasn't updating the Expires entry. After not using the project for couple of hours and without any changes, it worked. Oh, well...
I'm trying to set a future Expires Cache on public assets as per YSlow guidelines, to enable loading from cache and improve performance a bit. As per documentation (see Cache-Control at the bottom) this should work: "assets.cache./public/javascripts/bootstrap.min.js"="max-age=315360000" But it doesn't, when I check the Response I get: Data Size 82002 Device disk Expires Thu Jan 01 1970 01:00:00 GMT+0100 (IST) Fetch Count 220 Last Fetched Sat Feb 25 2012 15:04:04 GMT+0000 (GMT) Last Modified Sat Feb 25 2012 15:04:04 GMT+0000 (GMT) My file is stored under /public/javascripts/bootstrap.min.js My routes entry is the default one: # Map static resources from the /public folder to the /assets URL path GET /assets/*file controllers.Assets.at(path="/public", file) It seems that the config should work if I read the source code for assets. Any idea on what I'm missing or how to make it work?
How to set a future Cache-Control Expires on Assets in Play 2.0
Warming a server's cache may fall outside of the realm of your application logic. I have implemented a cache warming system before using a rake task that wrapped the curl command and looped through all the areas in the website. # lib/tasks/curl.rake desc "curl" task :curl do paths.each do |path| `curl #{path}` end end You can call this task by issuing "rake curl" from inside your Rails project root. Alternately, you could invoke this rake task (which wraps curl) from inside your sweeper method after you expire the cache. Check out the Railscast Ryan Bates did on invoking rake tasks in the background from inside your Rails application code: http://railscasts.com/episodes/127-rake-in-background More information on curl here: http://curl.haxx.se/docs/manpage.html
I have an application that uses caches_page for certain controllers/actions. To expire the cache, I use a sweeper. All in all, it's a standard solution. However, because some changes may cause a bit of a rush of requests on the server (because push notifications are sent out and may trigger client devices to fetch new data), I'd like to be able to pre-render the cache, so it's ready before the requests roll in. I could just wait for the first request to automatically write the cache, of course, but in this case, I know that the requests will come, that there might be many, and that they may be near-simultaneous. So I'd like to have the cache ready. To add some complexity, the updates are done via a normal web page and handled in a standard, mostly scaffolded controller, while the "page" I want to cache is the JSON response for an entirely different controller that serves as an API. So, how do I, from a sweeper (or from the controller handling the cache-expiring update) trigger a new page cache to be written immediately? Another way to put it might be: How do I make an internal request from one controller to another? Edit: Ended up doing something like what you see below. It's not terribly elegant, but it is effective class ModelSweeper < ActionController::Caching::Sweeper observe Model def after_create(model) expire_pages_for(model) end def after_update(model) expire_pages_for(model) end def after_destroy(model) expire_pages_for(model) end protected def expire_pages_for(model) # expire index page expire_and_bake(models_url) # expire show page expire_and_bake(model_url(model)) end def expire_and_bake(url) # extract the path from the URL path = url.sub(%r{\Ahttp://[^/]+}, "") # expire the cache expire_page(path) # request the url (writes a new cache) system "curl '#{url}' &> /dev/null &" end end
Rails 3.2: Pre-render (bake) a new page cache immediately after expiry?
It may not be possible for all provided content on your HTTP server, but you can simply change the name of the file to update a file on the client side from the server. At that point, the browser will download the new content. Sometimes, for websites with less traffic it is far more functional to set the cache to a much lower value. An expiration of 365 days should always be used with caution, and the fact that you can set an expiration of 1 year does not mean you always have to do it. In other words, do not fall prey to premature optimization. A good example of setting cache expiration to 1 year are countries' flags, which are not likely to change. Also, be aware that with a simple browser refresh of a page, the client can discard the local cache and download the content again from the origin. A good and easy way of testing all this is to use Firefox with Firebug. With this extension, you can analyze requests and responses. Here you can find the RFC specifications.
I am learning about apache and its various modules, currently i am confused about mod_expires. What i read so far is that using this module we can set future expiry header for static files so that browser need not to request them each time. I am confused about the fact that if some one change css/js or any image file in between, how will browser come to know about it since we have already told the browser that this is not going to change say for next 1 year. Thanks in advance
mod_expires in apache htaccess
You may take a look at the following presentation which explains the pre-.NET 4.0 state of caching and what .NET 4.0 brings in this respect. In .NET 4.0 the caching has been completely reworked into a separate assembly (System.Runtime.Caching) and rendered extensible. That's true for both object caching and page output caching. Unfortunately if you have current code that relies on the old Cache class this has to be changed as this class works with in-memory objects only.
Is there a way in .Net to switch out the Cache provider just like I would a membership provider, or role provider? I would like to keep the code untouched but switch to using a distributed cache like memcached or AppFabric. All I am finding is how to switch out the output cache provider. This might be necessary, but it doesn't solve the issue of when Cache is called directly from within my code. I've found many libraries and they abstract Cache behind an interface, but this would mean I have to go to every spot in my code and inject the new abstraction. Also I am using PLINQO, which internally uses Cache. Is OutputCache the only thing I can switch out through configuration? Thank you in advance.
Can I switch out .Net cache provider through configuration
I don't know of any option to control the cache key, and the implementation in Django doesn't suggest there is any. The code to generate the cache key for a request through the cache middleware lives in django.utils.cache.get_cache_key (to know where to fetch from the cache) and learn_cache_key (to know where to set the cache). You could monkey-patch these functions not to take headers into account like this: from django.utils import cache from django.conf import settings def get_path_cache_key(request, key_prefix=None): if key_prefix is None: key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX return cache._generate_cache_key(request, [], key_prefix) # passing an empty headerlist so only request.path is taken into account cache.get_cache_key = get_path_cache_key cache.learn_cache_key = get_path_cache_key This will internally take an MD5 hash of the path, add a potential prefix, and also take the current locale (language) into account. You could further change it to omit the prefix and the language. I would not recommend using the plain path without hashing it, as memcached does not allow keys longer than 250 characters or containing whitespaces, according to the documentation. This should not be a problem because you can just apply get_path_cache_key to the URL from get_absolute_url() as well and clear that page.
I’ve developed a Django site. There’s pretty much a 1-to-1 relationship between model instances in the dabatase, and pages on the site. I’d like to cache each page on the site (using memcached as the cache back-end). The site isn’t too big — according to a back-of-an-envelope calculation, the whole thing should fit into a fairly small amount of RAM — and the data doesn’t change particularly frequently, so the entire site could effectively live in the cache. However, when the data does change, I want the cache to reflect that immediately, so ideally I’d like each model instance to be able to clear its own page from the cache when saved. The way I imagined I’d do that is to cache pages with their URL as the key. Then each model instance can use its URL (which it knows via get_absolue_url()) to clear its page from the cache. Can I make Django’s per site caching mechanism use page URLs as the cache key?
Can I force Django’s per-site cache to use only each page’s path as its key?
Cache option in $.ajax puts a timestamp in a GET parameter. However, you could put Cache-Control: no-cache in the request headers when you are calling the send() method.
I can't find the way to turn off browser (and sometimes server "304") cache in GCL AJAX calls, like I've done in jQuery. $.ajax({ url: "test.html", cache: false, }); Maybe I can control headers somehow? I do not appreciate answers like adding a random string to a GET paramether manually. Like: requestObject.send("/feed/get?id=" + id + '&nocache=' + new Date().getTime());
Preventing AJAX calls to be cached in Google Closure Library
You can allocate more memory in the ndk. You'd have to write native code to manipulate the images, or you'd have to figure out a way to allocate the image memory in native, then pass it back to Java. Bitmap/Canvas use and the NDK Another option might be to load a single image into memory, and break it up into chunks for processing. Save those chunks out to the file system. So, say you 2 large images. You load the first image, break it into 4 parts, save them, load the second, break it into 4 parts, save those, then load part #1 for each image, and do your thing. That implies you know that neither individual image is larger than the heap max, and that what you need to do is (basically) pixel level and doesn't need access to surrounding pixel data (you'll run into trouble at the edges if you need neighbor pixel info). Without downsampling, splitting, or ndk, I don't know how you'd get more image data into memory. Perhaps lowering the color info. We do this in a product. Represent each pixel as 16 bits rather than 24 or 32. Our product is functional rather than "pretty", so the loss of color info wasn't a big deal.
I am manipulating relative large images, about 5MP and sometimes even more. I need two copies of the images in memory for manipulation. Now, the loaded images consume a lot of memory, more than available by the default Android heap which is 16MB respectively 24MB which results in the following error: 11-20 18:02:28.984: E/AndroidRuntime(7334): java.lang.OutOfMemoryError: bitmap size exceeds VM budget I need full resolution, thus downscaling while loading the images does not help. What's the best solution to get over this problem? Are there built-in methods to dynamically load only chunks of bitmaps from storage? And can someone give me some hints how I can overcome the memory problem, e.g. by using specific caching strategies? Regards,
Android VM heap strategies for big images
I rolled my own solution for monitoring files in Azure storage. Full details on my blog.
Has anyone got any examples of creating a custom ChangeMonitor? I was hoping to implement a ChangeMonitor for Azure blob storage but there is very little documentation out there.
Custom System.Runtime.Caching ChangeMonitor
If conflicts are few-and-far-between then why not just WATCH the key again, generate the cache data again, and try populating Redis again. Just keep repeating this process until your EXEC finally comes back clean. You could set a max number of retries to something sane, and if that is ever exceeded just invalidate the cache and notify your admins. The notification step seems important because if your optimistic lock fails more than something like 5 times then there is probably something weird going on and you should take a closer look.
We currently have a read-through cache that uses optimistic concurrency control when filling the cache on cache misses. We don't anticipate many conflicts, so we chose to use optimistic concurrency control. I'm a bit unsure what to do when we actually have a conflict though. If we have a cache miss, we pull the relevant row from the database, and then put it into the cache for future reference. Before we put it in the cache, we ensure that the value of the cache key has not changed since our initial database read. If it has, I'm currently leaning towards invalidating the cache entry, just to be on the safe side, but this seems a bit inefficient. Are there any better alternatives, that are still safe? For the record, we are using Redis for our cache-layer and MySQL for our backing-store.
How to resolve a conflict in a read-through cache using optimistic concurrency control?
The problem was coming from the fact I have been using EhCacheRegionFactory in my hibernate bindings (the particular cache wasn't related to Hibernate at all, but was defined on the same file). I have switched to SingletonEhCacheRegionFactory and the problem went away.
I wanted to use Ehcache's disk persistence with the ability to keep the data between restarts. My configuration looks like this: <ehcache> <diskStore path="/tmp/blah"/> <defaultCache eternal="true" maxElementsInMemory="500" overflowToDisk="false" memoryStoreEvictionPolicy="LRU" statistics="true"/> <cache name="myCache" eternal="true" maxElementsInMemory="10" maxElementsOnDisk="10000" overflowToDisk="true" diskPersistent="true" memoryStoreEvictionPolicy="LRU" statistics="true"/> </ehcache> Using the above, I have noticed that not only /tmp/blah/myCache.data gets created but also /tmp/blah/ehcache_auto_created_<timestamp>/myCache.data. Persisted data goes into timestamped folder and the problem is that cached data can't be reused across restarts. Also I see no point in general to have timestamped directory at all. After few hours of debugging, I have found out that this comes from CacheManager.detectAndFixDiskStorePathConflict method. This method loops over ALL_CACHE_MANAGERS and checks if diskStorePath matches across. This results true (although there's only one CacheManager in ALL_CACHE_MANAGERS in my case) and diskStorePath gets awkwardly renamed. The log warning suggests to consider singleton CacheManager. My knowledge about cache managers isn't deep but I have no intention of using more than one (especially with different settings). The only way I access /tmp/blah/myCache.data0 is via /tmp/blah/myCache.data1, as suggested in the documentation. Can anyone shed some light here? Is this a bug? I am using Ehcache version 2.4.4. Full stack trace: /tmp/blah/myCache.data2 Thanks in advance.
Ehcache is creating unnecessary timestamped directories for disk persistence
1 You can set appropriate HTTP headers to prevent caching (I do not know how to do this in ASP.NET, but I imagine it would be something like HTTP.Response.setHeader("foo", "bar"): "Pragma-directive: no-cache" "Cache-directive: no-cache" "Cache-control: no-cache" "Pragma: no-cache" "Expires: 0" or use the current timestamp if you don't like the random number solution: image.src = baseUrl + params + '&t=' + new Date().getTime(); Share Improve this answer Follow edited Aug 31, 2011 at 13:24 answered Aug 31, 2011 at 13:13 karim79karim79 341k6767 gold badges416416 silver badges406406 bronze badges 1 It should be image.src = baseUrl + params + "&ts=" + new Date().getTime(); If the & is left off the time value would append to the last value in the querystring. – epascarello Aug 31, 2011 at 13:26 Add a comment  | 
I'm returning an image (png) from a call to an action method and I'd like to stop the image being cached by the browser. return File(reply, "image/png", "{0}_Graph".FormatWith(ciName)); I've tried all the usual things, appending an array of different headers to the file output response and none of them seem to be working for me. Basically my action method returns a graph that's generated on the server and could be different from moment to moment. I use Javascripts Image object on the client side and set its src to my action method. var image = new Image(); image.src = baseUrl + params; Each time the same URL is requested, the server is not hit. I can append a random number etc to the querystring however I'm wondering if there's a better approach.
FileContentResult - prevent browser caching image
I'm using fragment caching this way: #helper def cache_unless(condition, name = {}, &block) unless condition cache(name, &block) else yield end end #view <% cache_unless has_permission?, :action => :index, :folder => @folder, :user_id => @user.id do %> ... <% end %>
Using Rails 3, is it possible to detect to see inside of the layout or a before_filter to see if an action is going to be cached and if there is a cache hit for that action? caches_index :something, :layout => false So for example (inside application.html.erb) <%= yield %> <% @is_cached == ... %> Is it possible to do it before and/or after yield call to the item?
Possible way to detect if an action is being cached in Rails?
2 take a look at the local.xml.additional in the same folder hints on how to configure it properly. also, http://www.fabrizio-branca.de/magento-caching-internals.html gives a good overview about the magento caches. Share Improve this answer Follow answered Aug 10, 2011 at 9:27 Marco BamertMarco Bamert 19611 bronze badge Add a comment  | 
Heard some talk about this being something that can be set in apt/etc/local.xml but I didnt see any of it there by default.. Maybe you can add it? Anyway. It was described to me that the fast_backend gets some of the magento stuff while the slow_backend get the other stuff and if fast_backend fails, then it will failover to slow_backend. Where do I set these options? What is stored in fast_backend? What is stored in slow_backend? What is the option "backend" for and what is stored there?
magento: fast_backend vs slow_backend vs backend - What is going on here?
Even I don't answer your raw question, this link should answer your goal as a whole. In a nutshell: Reload Rails code in development mode only when change is detected
I'm trying to speed up my web fronted by caching classes in development, My::Application.configure do config.cache_classes = true end but I would like to manually reload classes using guard if a file in my model or lib changes. So the question is this: without restarting my local server, how can i manually trigger a class cache refresh? Update You can use reload! don't know why i didn't think of that sooner
Manually Reload Rails classes that have been 'cached' by enabling cache_classes = true
make sure that it actually not the result cache by looking at the execution plan with trace (you should see that it accessing the Result cache and 0 consistent gets) you can find more info here http://www.oracle-developer.net/display.php?id=503 What is the size of the result set? you can see it by CTS or in the "bytes sent via SQL*Net to client" execution plan property make sure you don't have any one of limitations according to the document ion: It is not defined in a module that has invoker's rights or in an anonymous block. It is not a pipelined table function. It has no OUT or IN OUT parameters. has one of the following types, BLOB, CLOB, NCLOB, REF CURSOR, Collection,
I want to do JDBC Caching, I am using Oracle 11 as database. Using result_cache hint can help me here. But I have found it is not working with big resultset (around few thousand records) even though I have set result_cache_max_size tor 100mb and result_cache_max_result to 60%. Please help me here ??
JDBC Caching using result_cache hint
Finally turned out to be a known issue with the sendfile support of both Apache and Lighttpd. It can be fixed with EnableSendfile off ...on Apache and server.network-backend = "writev" ...on Lighttpd. Both worked.
I have a very strange problem. I have a Fedora 14 installed on a Virtualbox machine and I use it as a working copy server on my Windows 7 host. It has a webserver installed (first Apache, then I changed to lighttpd to see if ot solves the problem) and I am editing files on a shared folder, and then load them in the W7 host via the webserver. The weird thing is, that there is some kind of caching issue, because whenever I edit a static file, the older version is served, except that is is cropped to the size of the new file, of it the new file got bigger, it is padded with 0 bytes to have the size of the new. I tried to change webservers, disable caching, everything, it just does not work (even in different browsers). When I open the files on the Linux server, they look all right. Do you have any clue what this could be?
Changed static files are cropped/padded to the new size and served the old - Fedora
Maybe try localstorage any IPad should support it. http://diveintohtml5.ep.io/storage.html The user should never lose the data unless they clear browser cache or you as a programmer overwrites it. It is stored by domain.
Hi I'm designed a web app to be used offline at my company. People will be walking around the warehouse with iPads offline enter some pretty simple form data, usually 15-20 char id codes and quantities associated with them. What is a good way to store this info while offline and then upload to db when connected? I was thinking using JavaScript to check for a connection. If none, then append data to an array. If there is a connection, append then upload whole array then clear it. Can you give me some ideas for best practices, like how to not lose data, prevent data loss should the web app be accidentally closed, etc.? Thanks
Html5 offline cache form data
Your missing the parameter for the cache option they are as follows The cache_option attribute can take one of three values: No - Disable applet installation. Always download the file from the web server. Browser - Run applets from the browser cache (default). Plugin - Run applets from the new Java Plug-in cache. By defaulting to browser you would have to clear the browser cache for the updated values to take effect. Use plugin to take full advantage of the versioning you want to implement.
I am trying to update the cache for an applet. The applet properly caches, but afterwards, no matter how stale the cache is, it won't update. If I manually delete the cache, a new one will be created upon the next page load, and all changes to the .jar file I am trying to cache take effect. Having to do this, though, is not acceptable. I have tried using cache_archive in conjunction with cache_version in my index file like so: if (navigator.appVersion.indexOf("Win")!=-1){ var attributes = { id:'manager', code:'HardwareManagerApplet_FileWriter', width:1, height:1} ; var parameters = {jnlp_href: '/java/HardwareManagerApplet.jnlp', codebase: '/java/hardwaremanager.jar', cache_archive:'hardwaremanager.jar', cache_version:'0.0.0.7'}; check = deployJava.runApplet(attributes, parameters, '1.6'); hardware_enabled = true console.log("Applet started") } This is having no effect. I have tried moving cache_archive and cache_version to attributes and as various permutations between to no avail. I have tried enabling cache_option set to first browser, then tried again setting it to plugin. No dice. I've looked into ETags, and I'm not confident that will be the best solution. I've also looked into last-Modified, but A) I'm not sure how to implement it into the http so the cache will update and B) that will open a whole new can if I have to go that route. Is there any other reasonable alternative? Better yet, am I simply implementing cache_archive et al incorrectly? And actually, even if I can get it to cache every single time the page loads, I will be satisfied. Thanks for all and any help! Edit: The block of code about is the ONLY implementation I've made of cache_archive etc. Do I need to put in a couple lines elsewhere? As far as Oracle's documentation went, I didn't find that to be very clear.
How do I update the cache for an applet?
1000 is not a large amount of data; that will work fine, but you will need to think about synchronization if this data is shared between requests. In reality a lock to make access to a Dictionary<string,string> is probably fine, although you can be more fine-grained if you need. However, the inbuilt web cache (HttpContext.Cache) will also approach this same problem, and has all the thread-safety built in. Don't use SortedDictionary<,> unless you have a care that the data is sorted. I don't think you do. As numbers get larger, I'd be more inclined to think about stores such as redis / memcached, with local memory as a local shortcut.
In an ASP.NET 2.0 site on IIS6 I would like to store Key / Value pairs in the Application Cache. Each Key will always be a string with a 5 character length and each Value a string of 15 - 250 characters length. The usage scenario is that the Cache will be queried once per webpage request, if the Key exists use the Value otherwise query a database and either add a new Key / Value to the Cache or replace an existing entry based upon some application logic. In this scenario I envisage / require the Cache size to reach circa 1000 entries at which size it will become stable and will rarely (if at all) be changed as described above. Before I just "performance test it myself" does anyone have any experience of large amounts of Cached data as to whether it is preferable for Performance to: (1) Use 1 Cache object containing a SortedDictionary<string, string> or (2) allow the creation of 1,000 Cache objects and the use the Cache itself as a dictionary or (3) It just doesn't matter for the amount of data in question. In which case would your answer change if the number of entries increased to 10,000 or 100,000? Many Thanks.
IIS6 ASP.NET 2.0 Application Cache - data storage options and performance for large amounts of data
The simplest and most accurate solution is to check the size of the persistent store directly. Use -[NSFileManager attributesOfItemAtPath:error:] and then the fileSize key of the returned dictionary.
My app is caching content so that user can read it when offline. I wrote everything of the cache into a database file (using CoreData) in iPhone. However, the storage size is limited in iphone. So I would like to control the disk size my app is using. How can I check the disk size I am using? thanks
iphone - how to know the storage size an app used?
You could disable caching in your config/environments/*.rb files with: config.action_controller.perform_caching = false ian.
Rails automatically adds etag to all responses. How can I change this behaviour? I found some examples for rails 2.x, but it doesn't work.
Disable automatic etag header in Rails 3
2 If you are using automatic transactions, I think you need to commit the transaction to force SQLAlchemy to refresh the results. Try this: while True: new_payments = session.query(PayPalPayments) \ .filter_by(status='new') \ .order_by(PayPalPayments.payment_id) \ .all() process_payments(new_payments) session.commit() time.sleep(30) Share Improve this answer Follow answered Jun 20, 2011 at 16:10 ptalladaptallada 2122 bronze badges 0 Add a comment  | 
I have basically the following code (I simplified it a bunch): while True: new_payments = session.query(PayPalPayments) \ .filter_by(status='new') \ .order_by(PayPalPayments.payment_id) \ .all() process_payments(new_payments) time.sleep(30) For some reason only the first time I run the program the query returns new_payments. If a new payment comes in while the program is time.sleep(30) sleeping, then the query doesn't return any new results. Are the query results cached for the same query in SqlAlchemy? Any ideas how to make each query to really query the database and return new rows?
Do SqlAlchemy query results get cached?
From what I've read and experienced first hand, the SQL transferred over the wire to your DBMS will always be logged regardless of whether ColdFusion ORM (Hibernate) is generating it JIT, or pulling it from cache. If anything, you could run a few benchmarks to quickly identify whether cache actually being used, or not.
Ive been playing with ORM caching in the past few days and one thing that is confusing me a lot is the SQL is still logged (when I have logSQL = true) to the console even with caching enabled. This makes me think that caching is not working, I would think that hibernate doesnt create the sql since it sees the object in cache, but maybe hibernate generates the sql even before checking ehcache. My code is below just incase someone picks up something I missed. Application.cfc this.ormSettings.secondarycacheenabled = "true"; this.ormSettings.cacheprovider="ehcache"; this.ormSettings.logSQL=true; then my Books cfc component persistent="true" entityname="Books" table="db_books" cacheuse="transactional" lazy="true" and lastly the code im using to call. a = entityloadbypk("Books","1"); writeoutput(a.getName());
ColdFusion ORM Caching and LogSQL
Not sure the language you are using to code with, but regardless I am sure the strategy will work across the board. I pass an arbitrary value in the query string, something like a GUID or the datetime stamp. This will force a fresh load as the URL will be unique. I use ASP.NET MVC which I then set a optional parameter in my route, which the controller method ignores. I then set my URL via JavaScript: d = new Date(); $('.thumbnail').attr('src', $('.thumbnail').attr('src') + d.getTime()); The solution I needed was unique, so this is probably not similar to what you are trying to resolve. However, it should get the point across.
I'm having some trouble with the firefox and ie cache, on my website the user can make a query with a form, and this query returns a picture, but depending on which radio button is selected, it'll return a different picture, and it works just like that on chrome, but in IE and firefox, the same image is always returned, it only changes when i reopen the browser, can you guys give me some light on how to make this work? Thanks to everyone, i solved my problem by putting and unique url each time i made the ajax call. <?php $date = date("H:i:s"); echo '<a href="web/WEB-INF/classes/lineChart.php?id='.$date.'" title="Chart" class="chart">'; echo '<img src="web/WEB-INF/classes/lineChart.php?id='.$date.'" alt="">' ?></a>
Firefox and IE image cache
Just as tadman states in the comments of the question, I had to invent my own solution, since Rails doesn't technically allow tags in the sense that I needed them. Here's a generalized solution for those interested in doing something similar: I created a new table called SimilarPages: create_table :similar_pages, {:id => false} do |t| t.integer :page_id, :similar_page_id # you could also do `t.string :tag_name` or similar end add_index :similar_pages, :page_id add_index :similar_pages, :similar_page_id Technically, I could do a self-referential has_many relationship on Pages, but I decided not to since I don't ever need to reference it that way. I just created a simple SimilarPage model: class SimilarPage < ActiveRecord::Base belongs_to :page belongs_to :similar_page, :class_name => 'Page' end Then using ar-extensions (because I'm lazy, and also because I wanted to do this in one INSERT statement), I do this within the cache block: SimilarPage.delete_all("page_id = '#{@page_id}'") SimilarPage.import [:page_id, :similar_page_id], @similar_pages.collect {|s| SimilarPage.new(:page_id=>@page_id,:similar_page_id=>s.id)} In my expire_cache_for method of my Observer, I do this: SimilarPage.where(:similar_page_id => expiring_page.id).all.each do |s| ActionController::Base.new.expire_fragment(/page_show__#{s.page_id}__.*/) # the regexp is for different currencies being cached ^ Rails.cache.delete("page_show_#{s.page_id}") end
Our app uses Rails.cache in the controller to cache some items outside the scope of the view (like meta tags), then uses fragment_caching on the bulk of the view. The view caches one main model, but we have used data from 5 other models (not connected by an Association) inside that main cache. It's easy to expire the fragment with a sweeper on the main model, but those additional models also change and need to trigger this page to expire. We can't use a regexp route for deleting the cache keys because we have to reference this cache entry by only the main model -- the other models are determined by an expensive query that we perform inside the cache block in the controller. Does Rails 3 have a way to essentially use tags to mark a cache entry, so we can trash it when any of the 6 models on the page change, but we can still find the cache entry from only the main model's key? Here's some dummy code to express the idea: In the controller @cache_key = "/page/#{params[:name]}/#{params[:id]}" unless fragment_exist? ( { :slug => @cache_key }) # run our processes here that will be needed in the view, # then cache the data that is used outside the view Rails.cache.write(@cache_key, { (data goes here) } ) # run our expensive query here: @similar_pages = Page.pricey_query!.limit(5).all else cached = Rails.cache.read(@cache_key) end In the view - cache( {:slug => @cache_key} ) do - @similar_pages.each do |page| = image_tag page.photos.first.image.url -# more pretty stuff here My goal: Me: "Oh, page @cache_key has changed, let's expire it!" Rails: Okay, easy! Me: "One of the similar pages changed their first photo, what do I do?" Rails: Umm... #(*$^*@ .. does ... not ... compute.
Does Rails have tags for expiring a cache?
2 Another one with the same problem as me :) I ended up with this solution: http://szeryf.wordpress.com/2008/02/02/multilingual-page-caching-in-ruby-on-rails/ I couldn't change the structure to include the language identifier in the URL as suggested here: http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/341bba9357bfc608 Depending on your structure and how fare you are down development, choose either one. However, it's probably easier if you have the cache either as part of your domain or your url. I hope multilingual caching will be improved in future rails versions. Share Improve this answer Follow answered Apr 18, 2011 at 13:47 leifcrleifcr 1,4681212 silver badges1515 bronze badges 1 I should have closed out this question. I always run full caching locally why it was surprising to me. The answer turned out to be that I used rsync to deploy to production and I had a left-over file that did not get deleted. Very silly I know. – Erik Apr 19, 2011 at 4:20 Add a comment  | 
I have a standard Rails application running with the I18n support. I have extensive caching running for this app. I edited a few strings and confirmed it worked locally. I also confirmed I have the right strings on the file for the live site. Still for some weird reason I do not see these changes for my live site even though I have not fragment cached anything here. Any ideas what is going on?
My Rails Application doesn't update the localized strings in production mode
There's two different questions here. HTTP cache headers can never specify that a user-agent must cache a resource, only that it must not cache a resource. So Firefox, by not caching your video, is not failing to honour the headers. However, Firefox clearly has some rules about when to cache resources. I don't know what they are, but I recommend that you don't rely on them. They are likely to depend on the platform on which Firefox is running in quite intricate ways.
Firefox is caching 10sec 1.5MB videos but not 50sec 8.5MB videos. I assume its because of the file size, but I'm not sure. Under what conditions does firefox honor caching requests? I'm using this code to force caching of webm files: <FilesMatch "\.(webm|ogg|mp4)$"> Header set Expires "Mon, 27 Mar 2038 13:33:37 GMT" Header set Cache-Control "max-age=864000" </FilesMatch> AddType video/webm .webm
Under what conditions does firefox honor cache expires / headers
there are no properties available to check if its enabled or disabled (apart from looking in the web.config). So you will have to read through your web.config. There are however some articles concerning how to reset/clear the blob cache: example 1
Does anyone know if there is a boolean value somewhere in the object model that allows me to check if blobcaching is enabled or not? I've just been unable to locate it, looking through intellisense for SPContext and a few other places. Google turned up nothing outside of the web.config. I was hoping to find something under SPContext.Current.Site.WebApplication, but nothing. I can always create my own static property that programmatically looks into the web.config to find out, but would rather not reinvent the wheel if such a property already exists somewhere I didn't think to look. Thanks.
Checking if BlobCaching is enabled in Sharepoint (without looking at the web.config)
You should check out Matthias Kaeppler's project Droid-Fu: https://github.com/mttkay/droid-fu In Droid-Fu, there is an ImageCache, which uses memory for the first level cache, and disk for the second level. It it specifically made for Android, and does the right thing there, which is to use the designated cache directory for the current application instead of polluting the sdcard or other directories. Android can automatically clean up the cache directory when it needs to. Here is the Javadoc: http://mttkay.github.com/droid-fu/com/github/droidfu/imageloader/ImageCache.html
I'm writing a fairly Android application which will need to cache a lot of different images around 48x48 to 500x500 pixels in size. These images are fetched over the network from a number of different sources (think: user selects a source, browses a bunch of images, changes source, browses a bunch of images, etc.). I'd like to implement caching for these images, as I don't want to hit HTTP if someone's flinging through some images they've already seen. Obviously, memory usage is pretty key, so that's where EhCache comes in, as it offers a lot of different options for bounding the cache, expanding it to disk, etc. Is this the right/best way to go about caching these images? I have noticed a lot of applications cache right to disk on the SD card, but I'd like to avoid this if possible for the sake of speed/convenience.
EhCache in Android for caching bitmap images?
2 You can add this to your app's manifest: application android:name ="MyApplication" (...) You can then create a class that has the name "MyApplication". You can then use that class across your activities. Check, before making the async call, if you already have a proper image to use. If you have, you use the one "cached", if not, you can get a new one. You can try something like this (in this case to get some random strings): ArrayList myStrings = ((MyApplication) this.getApplication()).getRandomStrings(); Hope this helped you. :) Edit: Don't forget to the create your "MyApplication" like this: public class MyApplication extends Application Share Improve this answer Follow edited Jan 31, 2016 at 18:24 answered Feb 7, 2011 at 19:02 Rui PeresRui Peres 25.8k99 gold badges8989 silver badges139139 bronze badges 1 Thanks. The key was to extend the application task. – tsr Feb 9, 2011 at 4:14 Add a comment  | 
I am developing an Android application and can't quite figure out the best way of implementing a 2-level image cache that can be shared among multiple activities w/in a single application. Example: Application has 3 activities (A, B, and C) and for the sake of argument lets say that A calls B and B calls C and C calls A. Each activity displays an image downloaded from the web and I'm using asynctask to download and display images w/in each activity - easy enough. Now I'd like to add an image cache to avoid multiple downloads of the same image. Right now each activity starts a new instance of a simple asynctask that downloads the image and updates the view appropriately. Obviously its easy enough to update the basic asynctask to check the image cache before proceeding to download and to update the cache once the download is complete but I'm stuck on how/where to create and initialize the cache. Any thoughts would be appreciated.
Android: sharing an image cache among activities
I don't think this is possible. You marked Mikushi's answer correct, however from this page: http://framework.zend.com/manual/en/zend.cache.backends.html#zend.cache.backends.memcached Be careful : with this backend, "tags" are not supported for the moment as the "doNotTestCacheValidity=true" argument.
I'm thinking of using two level cache backend, in a Zend Framework application. Fast: APC Slow: File But I need it to use cache tagging, to make an easy cache clearing. So is it possible? to use those combinations? PS. I'm asking this question because I've read: Be careful : with this backend, "tags" are not supported for the moment as the "doNotTestCacheValidity=true" argument. In the official Zend Framework document: Zend Cache APC Backend, so I was wondering how to get use of tags, since it's the most interesting part in caching IMO.
How to use I use Zend_Cache_Backend_TwoLevels with tagging?
I would suggest you have a look at overwriting the sfExecutionFilter. It's the last filter in the default filters.yml, which means it's the first executed. This is what is responsible for calling your action's executeXXX method and loading associated view and bunch of other things. Presumably you could write your own filter the extends sfExecutionFilter and overwrite it's functionality to skip executing the controller it the output is cached. You can find the default filters.yml @ %SYMFONY_DIR%/config/config/filters.yml
The idea of the desired filter is to check the memcached for page content with url as a key and if found, return it to client directly from cache and skip the controller altogether. Storing would be done in separate filter, which is the easy part. I'm aware i could write it to action's preExecute() but filters would offer more elegant solution (could turn them off for dev envs). In other words - is there a smart way for a filter to push the response to client and skip going to action?
Symfony filter to run before and possibly skip the controller
Use Code Splitting to only load what's needed as it's needed. Use Compile Reports to find out which of your dependencies is causing your code size to be so huge, and (re)move them from the initial download.
in my GWT project when I tested it by firebug I saw the ...cache.html file size is very big (about 700KB) and it cause for slow-loading the project for first time. In my project it can be a problem. how to prevent size for cache.html in GWT?
cache.html size in gwt and Slow-Loading
By default it is saved in RAM. If you have saving that large amount of data you should think about saving it in a database.
I'm on IIS6 > ASP .NET > C# > WebService I have to put in Cache a lot of data (thousands of serialized object of about 2MB each). How does IIS6 manage HttpContext.Current.Cache - does it save in RAM or temp file? Can I compress data before caching? What are the alternatives of HttpContext.Current.Cache?
HttpContext.Current.Cache performance
Here is my take on this: 1) Server: Default; the request can be seen on the Fiddler. 2) Browse cache: No request is sent so Fiddler will not show a request to the server. Also if the resource is changed on the server, it is not updated on the client. 3) Proxy/Cache server: It is tricky and not always reliable. It looks like the server but you will most likely see X-cache or similar cache related and sometimes non-standard headers, depending on the proxy or the cache server used.
Is there is any way to find out from where an image is loaded to browser. From server / browser cache or proxy cache etc. I am using asp.net MVC
Is there is any way to find out from where an image is loaded to browser. From server / browser cache/ proxy cache etc
2 This sounds very elegant but elegancy is not necessarily a good thing. What makes me worried is not the using of caching, it is trying to solve an inherently database problem outside the database - not every company is Microsoft/Oracle/... and has the manpower to make a brilliant database. I believe you have issues with the database perfromance and caching has been put forward as the solution. But it is not a pure cache, it needs to handle data consistency and changes to the data as well as simple reads and you are trying to deal with the data that is often changing and as such is not a good candidate for cache. IMO, this is a call for disaster. Having to implement all database functionality in front of another database it is just not right. Simplify the database and denormalise. If you still need caching, use ASP.NET caching outside ASP.NET by just referencing it in your project; it has a rich API catering for pretty much any requirement you need. Share Improve this answer Follow edited Oct 14, 2010 at 9:09 answered Oct 14, 2010 at 9:01 AliostadAliostad 81.1k2121 gold badges161161 silver badges208208 bronze badges 0 Add a comment  | 
I need to develop a dedicated caching service ( either a WCF service or a .Net remoting service or other implementation) to cache the data (monitoring data of .net3.5 Latency measuring application) from Database ( SQL Server 2005) which can then be consumed by 2-3 windows services( .net 3.5 WCf services) so that they do not need to call DB repeatedly. So basically it is a additonal level of service layer between these services and DB to reduce the performance penalty of calling DB The data in Database is large and very dynamic (events continously inserted in DB during the day) which we want to cache. Each of the consuming windows service is dependent on another ( one service is retrieving data from one Table in Db and aggegating the data and putting in another table in DB which would then be consumed by another service) . we have the following requirements : Could have either Push or Pull model for pushing or retrieving data to/from DB and Services. The cache must reduce the overall impact to the DB and load data by delta, rather than reloading the data completely The cache data must be updated if the source data in DB has changed. Sql cache expiration policy must be defined. Should have asynchronous method calls for Data retrieval from DB and cache update to minimise wait times The cache must support parallel requests to a single DB CPU and Memory Utilization should be kept at optimum levels so it does not negatively affect other services. We do not have a clustered or a distributed environment and is not meant to be a very highly scalable solution. I want to know what is the best way of implementing this based on several technologies available to avoid making it overly complicated: .Net Framework Caching Coherence caching Velocity Rest based services for WCF Any suggestions and guidance would be very invaluable. regards, KK
How to implement caching in dedicated caching service in .net 3.5/ 4.0?
Ok found it. The object implemented IXmlSerializable so AppFabric used that instead of the regular serialization. Running it through an XmlSerializer (instead of a BinaryFormatter) gives the same null fields as I was experiencing. It seems the IXmlSerializable implementation has issues.
Problem: When caching an instance of a class and immediately getting it back out of cache, i get the object back (its not null), but all of its properties / fields are null or defaults. _cacheHelper.PutInCache("testModuleControlInfoOne", mci); //mci has populated fields var mciFromCacheOne = _cacheHelper.GetFromCache("testModuleControlInfoOne"); //mciFromCacheOne now has null or default fields So I suspect the way the object is structured is the problem and AppFabric is not serializing the object properly for some reason. When I use the following Serialization method however, I get the object back with all properties / fields as they were prior to serialization. public T SerializeThenDeserialize<T>(T o) where T : class { BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { bf.Serialize(ms, o); ms.Position = 0; return (T)bf.Deserialize(ms); } } How can an object serialize and deserialize properly using the binary formatter and not do exactly the same thing via caching? Has anyone encountered this or does anyone have any suggestions or tips on generally what to look out for?
AppFabric Caching - What are its serialization and deserialization requirements for an object?
You can try to cache complicated views like lists etc. An example: You have a category overview, it shows the name of all categories and the count of items in it. You can cache this view as static html as long as no new item has been inserted or deleted in any category. So every time you create a new item or delete one you have to regenerate this view. Since items are created less often than being viewed, you can save many queries ;) PS: You don't have to use files for that, you could use memcache (google for it)
I have made a framework for a project. The project does a medium amount of query requests (but the traffic it will be getting will make it more per user). The views are mixed HTML and PHP. Just looking for the best minimalist ways on how I should go about caching my view files (the controller uses output buffering so maybe I can leverage that?) and cache my queries. I've looked around but only could find big/bloated libraries or very crude methods on doing these things, something I'm not interested in. Thanks for the help!
PHP Caching (HTML + PHP)
Basic answer: The CPU registers are directly on the CPU. The L1, L2, and L3 caches are often on-chip; however, they may be shared between multiple cores or processors, so they're not always "physically on the CPU." However, they're never part of main memory either. The general principle is that the closer memory is to the CPU, the faster and more expensive (and thus smaller) it is. Every item in the cache has a particular main memory address associated with it (however, the same slot can be associated with different addresses at different times). However, there is no direct association between registers and main memory. That is why if you use the register keyword in C (not that it's often necessary, since the compiler is usually a better optimizer), you can not use the & operator. The DMA controller executes the transfer directly. The CPU watches the bus so it knows when changes are made "behind its back", which invalidate its cache(s).
Question 1: Where exactly does the internal register and internal cache exist? I understand that when a program is loaded into main memory it contains a text section, a stack, a heap and so on. However is the register located in a fixed area of main memory, or is it physically on the CPU and doesn't reside in main memory? Does this apply to the cache as well? Questions 2: How exactly does a device controller use direct memory access without using the CPU to schedule/move datum between the local buffer and main memory?
2 basic computer questions
I use this code to view the cache data. http://www.codeproject.com/KB/session/exploresessionandcache.aspx Its not a cache manager, but its a good point to start.
I would like to integrate a Cache Manager in an ASP.NET application. Basically I would like a page that would display what's in the cache and let me delete specific items or clear the whole cache. Ideally I would like as much information as possible, such as how long it's been in the cache for, the hit count, the size of the object, possibly see the object itself, etc. Of course I realize that some of this information might not be available from the default cache API. I think it would be fairly easy to implement but I don't want to reinvent the wheel. I did a search and came across that one: http://aspalliance.com/cachemanager/Screenshots.aspx Just wondering if there are other options that I could compare. Cheers
Cache Manager for ASP.NET
1 I am assuming you are using DB backend for that. I'd use limits to return small chunks of data, most DB vendors have solution for this. That would make your queries faster, and also most of JS fameworks with grid type of components will support paginating results(ExtJS for example). If you are fetching data from 3rd party and passing it on (with some modifications or not) I'd still stick to the database and use such workflow: pool data from 3rd party, save in db, call from your widget small chunks required by customers. Hope this helps. Share Improve this answer Follow answered Aug 2, 2010 at 11:44 GregGreg 2,48355 gold badges2222 silver badges2323 bronze badges 1 1 I have no choice but to fetch all data in one go on first request. Also populating this data is expensive and thats why i do not want to do processing each time. So limiting with DB query is not an option. Thanks. – ashish Aug 2, 2010 at 12:05 Add a comment  | 
Here is my situation: I have Java EE single page application. All client-server communication is AJAX based with JSON is used as format to exchange data. One of my request takes around 1 min to calculate data required by client. Also this data is huge(Could be > 20 MB). So it is not possible to pass entire data to javascript in one go. So for this reason I am only passing few records to client and using grid to display data with paging option. Now when user clicks on next page button, I need to get more data. My question is how do I cache data on server side ? I need this data only for one user as a time. Would you recommend caching all data one first request using session id as key ? Any other suggestions ?
Server side caching for Java/Java EE application
Your code has two problems: (1) It uses the old dict.has_key() method which is slow and has vanished in Python 3.x. Instead use "key in dict" or "key not in dict". So: def foo(self, a, b): params = frozenset([a, b]) if params in self._cache: self._cache[params] = self._calculate(a, b) return self._cache[params] (2) "key in dict" is more readable, and exposes the much worse problem: your code doesn't work! If the args are in the dict, it recalculates. If they're not in the dict, it will blow up with a KeyError. Consider copy/paste instead of typing from memory. So: def foo(self, a, b): params = frozenset([a, b]) if params not in self._cache: self._cache[params] = self._calculate(a, b) return self._cache[params] (3) Some more efficiency suggestions: def foo(self, a, b): if a < b: params = (a, b) else: params = (b, a) try: return self._cache[params] except KeyError: v = self._cache[params] = self._calculate(a, b) return v
I have a method with two parameters that does some complex computation. It is called very often with the same parameters, so I am using a dictionary for caching. Currently this looks something like this: def foo(self, a, b): params = frozenset([a, b]) if not params in self._cache: self._cache[params] = self._calculate(a, b) return self._cache[params] The reason for building the frozenset is that the parameters can be in any order, but the result will be the same. I am wondering if there is a simpler (and most importantly more efficient) solution for this.
Caching the results of a function with two parameters in Python
2 I don't think you'll ever find a published formula or strict guideline on optimizing your cache. Every situation is going to be radically different, and even from the number of variables you're talking about here, it's impossibly to quantify. It'll be a combination of experience, guessing, monitoring and incremental adjustments to find your caching sweet spot for any given application. It sounds like you've already got a handle on what might happen, so I would start with caching the 10% that represent your high traffic, and optimize from there. You may or may not find any performance gains further down the road with your less-used content, but put your effort into the major optimizations first. Share Improve this answer Follow answered Jun 2, 2010 at 22:51 wompwomp 116k2626 gold badges238238 silver badges269269 bronze badges Add a comment  | 
I've read lots of material on how to do ASP.Net caching but little on the optimal duration that pages should be cached for. Let's say that I have a popular site with 50,000 pages. The content does not change frequently, so I could cache pages for up to an hour if I wanted. The server has 16 GB of RAM, but database connections are limited. How long should pages be cached for? My thinking is that if I set the cache duration too high (let's say 60 minutes), I will fill up memory with a fraction of the total content, which will continually be shuffled in and out of memory. Furthermore, let's say that 10% of the pages are responsible for 90% of traffic. If the popular pages are hit every second, and the unpopular ones every hour, then a 60 second cache would only keep the load-intensive content cached without sacrificing freshness. Should numerous but rarely-accessed content be cached at all?
Optimal ASP.Net cache duration for a large site?
Have you tried reading HTTP_IF_NONE_MATCH from apache_request_headers()? If you are running pre-4.3 php, it was called getallheaders() before. Edit I now see, in the page I linked, that you may also want to try to put RewriteEngine on RewriteRule .* - [E=HTTP_IF_MODIFIED_SINCE:%{HTTP:If-Modified-Since}] RewriteRule .* - [E=HTTP_IF_NONE_MATCH:%{HTTP:If-None-Match}] in the appropriate .htaccess file to force Apache to set the PHP $_SERVER[...] variables you're unsuccessfully trying to read.
What I'm doing I'm pulling an image from the database and sending it to the browser with all the proper headers - the image displays fine. I also send an ETag header, using the SHA1 of the image's content as the tag. The images are getting called semi regularly, so caching is a bit of an issue (won't kill the site, but nice to have). The Problem $_SERVER['HTTP_IF_NONE_MATCH'] is not available to me. As far as I can tell, this is because of PHP's "disobey the cache controls" life style. I can't mess with the session cache limiter, because I don't have access. But, even if I did have access, I wouldn't want to touch it: 99% of the site is under WordPress. The Environment PHP 4 (don't ask) Apache 2.2 WordPress The images live in the database (largeblog), which I can't change. Any guidance, tip/tricks, etc. would be helpful. I don't have much room to change the environmental/structural stuff. Cheers.
PHP not obeying my defined ETags
As you say above, ASP.NET output caching out of the box works on a per-server basis. However in ASP.NET 4.0 the whole caching infrastructure is pluggable. ScottGu has a blogpost on taking advantage of this for output caching. I've written some demo code that uses Velocity/AppFabric as a caching engine, which should do what you want - have a look at my blog here.
i've got a website that uses OutputCache attribute to cache pages. Works great. Now, I'm in the middle of R&D'ing scaling up this site to be in a web farm. Along with the usual suspects for webfarm pain ... I've noticed (pretty quickly/obviously) that the OutputCache from Server_A doesn't invalidate the OutputCache from Server_B .. if a try and invalidate a single server's OutputCache. This makes total sense -> how can S_A 'tell' S_B to invalidate when they are physically 2 seperate machines, etc? So - what are our options? Velocity? I understand this will move the caching to a different layer .. which means that the final result (output) will always be required to be determined .. as opposed to the OutputCache whic remembers the final output content (yes, varby gives different versions, etc.. which is totally fine). So even though the poco or business objects are all sync'd, there's still that last rendering effort required (even if it's tiny .. compared to the effort to generate/sync business objects). So yeah .. not sure of the options here and what other people do?
How to invalidate the OutputCache in a webfarm?
2 Have you tried appending a timestamp with the current time interval to the URL as a querystring parameter, e.g. http://www.myhost.com/page.html?timestamp=123456789.0 I don't know if this works, it depends on how the cache is implemented, but it might be worth giving it a try; it's a bit hacky, but I've used this a long time ago in a galaxy far far away when doing Flash applets. I'm having the same problems now, and I've even tried using: [[NSURLCache sharedURLCache] removeCachedResponseForRequest: request]; After the UIWebView has finished loading. Share Improve this answer Follow answered Jul 26, 2010 at 21:07 pikuserupikuseru 7144 bronze badges Add a comment  | 
I have a UIWebView object, with the caching-policy specified as: NSURLRequestReloadIgnoringLocalCacheData This should ignore whatever objects are in the local cache and retrieve the latest version of a site from the web. However, after the first load of the site (ten resources in trace, HTTP GET), all subsequent loads of the site only retrieve a small subset of resources (three resources in trace, HTTP GET). The images all appear to be loaded from some local source. I have confirmed that my sharedURLCache has a memory usage of 0 bytes, and a disk usage of 0 bytes. Whenever the process starts fresh, the full version of the site is retrieved again. This leads me to believe that these resources are being stored in an in-memory cache, but as I noted before, [[NSURLCache sharedURLCache] currentMemoryUsage] returns 0. I have also tried explicitly removing the cached response for my request, but this seems to have no effect. What gives? Edit: Furthermore, the NSHTTPCookieStorage is cleared before each load, and I can confirm that the subsequent loads retrieve four resources now instead of three. The caching issue persists regardless of the change.
UIWebView NSURLRequestReloadIgnoringLocalCacheData doesn't actually ignore the cache
ActiveRecord provides a reload method for reloading the attributes of a model object from the database. The source code for this method is: # File vendor/rails/activerecord/lib/active_record/base.rb, line 2687 def reload(options = nil) clear_aggregation_cache clear_association_cache @attributes.update(self.class.find(self.id, options).instance_variable_get('@attributes')) @attributes_cache = {} self end —As you can see it calls a clear_association_cache method, so there's definitely caching of associations going on which would explain the behaviour you're seeing. You should probably reload the model in one of your methods prior to saving.
I have a problem with making changes to an object from within another model as well as within the object's model. I have the following models: class Foo < ActiveRecord::Base has_many :bars def do_something self.value -= 1 # Complicated code doing other things to this Foo bars[0].do_other save! end end class Bar < ActiveRecord::Base belongs_to :foo def do_other foo.value += 2 foo.save! end end If I have a Foo object with value set to 1, and call do_something on it, I can see from my database logs the following two operations: Foo Update (0.0s) UPDATE "foos" SET "value" = 2 WHERE "id" = 1 Foo Update (0.0s) UPDATE "foos" SET "value" = 0 WHERE "id" = 1 ... so do_something is presumably caching the self object. Can I avoid this, other than by moving the save!s around?
Cache problems when updating an object from another model
I guess all Memory caching library have an option to persist or expand on disk. At least, EHCache does. So you can just configure a cache library to write on disk (either because you want the data to be persistant, or to expand the cache size over your memory limits). Note that EhCache has LRU capabilities.
I'm looking to implement a disk based caching system. The idea is to allocate a certain amount of disk space and save however much data fits in there, discarding of old files as I run out of space. LRU is my first choice of deletion strategy, but I'm willing to settle for FIFO. When googling for cache algorithms, the discussion seems to be dominated by memory-based caching. Memcached, for example, would be exactly what I'm looking for, except that it's memory based. On the other hand, solutions like Memcachedb, couchdb etc. don't seem to have LRU capabilities. The closest thing I've found is the squid proxy server storage systems. COSS seems to be the most documented one, but to use it I would probably have to rewrite it as a stand-alone process (or library). What project or (java/python) library can I use for such a thing? EDIT: found this related question.
Looking for a FIFO/LRU file storage system
So many options here: since you might end-up supporting complex interactions with multiple threads, you might want to consider using a "virtual clock" with a message passing "bus". This way, you'll have more time to focus on the core functionality instead of debugging the synchonization logic... Using this technique, you can build a state-machine (see here) per "actor" thread (worst case) and worry less about mutexes/conditions. Once you've got this base, you'll be able to handle cases that show up mid-stream (e.g. "I forgot about this detail... no worries, just add a state here... don't have to re-shuffle my mutexes). Also, since doing simulation is all about "virtual time" (since you can't run real-time !), then having a base architecture based on a "virtual clock" abstracts the problem to an appropriate level.
Closed. This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this post. Closed last month. Improve this question I have to build a dual-core processor simulator in C (it's actually a multilevel memory simulation, cache L1/L2, block substitution, etc). Thing is, I'm having a hard time figuring a way to synchronize the cores (which I'm programming as threads). Any ideas how I could do a global clock? Should I change from threads to child processes? Thanks in advance
Way to synchronize two cores in simulation [closed]
Which version of Firefox? Is the server sending Etags for the static files? You can view details about Firefox cache by going to the address about:cache and poking around. That will give you an idea of what Firefox is caching. Update: After looking at your header tags, it seems as if the max-age value is set to a date that is way in the past and that is overriding the the value being set in the Expires header. See the HTTP 1.1 protocol definition at: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.3. If a response includes both an Expires header and a max-age directive, the max-age directive overrides the Expires header, even if the Expires header is more restrictive. This rule allows an origin server to provide, for a given response, a longer expiration time to an HTTP/1.1 (or later) cache than to an HTTP/1.0 cache. This might be useful if certain HTTP/1.0 caches improperly calculate ages or expiration times, perhaps due to desynchronized clocks. You will have to modify your Cache-Control header being sent by the server.
I'm using valid expires and no-cache headers for my static files and they stay cached for as long as I keep browsing, but when I close my browser and use it back after a while I see the static files loading again, even when not refreshing with ctrl (+ shift) + r I'm using Firefox, cache size set to 250MB and I don't let it remove any private or cached data. Headers: Accept-Ranges: bytes Cache-Control: max-age=29030400, public Content-Length: 142061 Content-Type: image/png Date: Tue, 08 Dec 2009 19:18:43 GMT Expires: Tue, 09 Nov 2010 19:18:43 GMT Last-Modified: Sun, 18 Jan 2009 18:33:48 GMT Server: Apache/2.2.14 (EL)
Why doesn't my expires headers make my files stay in cache?
2 I've done this before. It can be a useful technique. Just make sure the data is accurate and that you support JS disabled user agents. EDIT: And that there is no better solution. Share Improve this answer Follow edited Dec 3, 2009 at 16:53 answered Dec 3, 2009 at 16:45 AllynAllyn 20.4k1616 gold badges5858 silver badges6868 bronze badges 1 +1 for "Just make sure the data is accurate". Anything cached on the client will be unknown to the server... but then I guess "cache" by its nature is at risk of being out of date... – ChronoFish Dec 3, 2009 at 18:03 Add a comment  | 
I'm trying to speed up response times in my ajax web application by doing the following: Say the user requests a page whose contents don't change (e.g a web form). When the user makes a different request, I 'cache' the form by putting it in a hidden div. Before displaying the new information. So the form is basically still loaded in the browser but not visible to the user. If the user requests the same form again, it gets loaded from the hidden div. That's notably faster than doing a round-trip to the server for the form. I do realise doing so with lots of data will probably degrade performance as the browser gets to keep a lot in memory. But I will place a limit on how much gets "cached" this way. Now, I came up with this on my own which is why I'd like to know if there is a better/established way of doing this. It works as expected but I don't know what the possible drawbacks are (security-related perhaps?). I would appreciate any suggestions. Many thanks.
Caching data by using hidden divs
2 If you can't get it working using the IIS admin tool, try Jeff Atwood's recommendation from this thread: <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <staticContent> <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" /> </staticContent> </system.webServer> </configuration> Share Improve this answer Follow edited May 23, 2017 at 12:19 CommunityBot 111 silver badge answered Oct 15, 2009 at 6:18 Justin GrantJustin Grant 45.5k1515 gold badges127127 silver badges214214 bronze badges Add a comment  | 
I've deployed an ASP.NET MVC app on IIS7 and Windows Server 2008. I've read posts on here, and around the web, but can't get the darn client-side caching to work. I'm trying to cache everything in the /Content folder. So far I've select that folder in IIS manager, and set the appropriate HTTP Response Headers (under Common Headers). I've also checked the web.config file in the /Content folder and the values there are being set. All resources in /Content come back with this (from FireBug): Cache-Control no-cache, no-store, must-revalidate Pragma no-cache Content-Type image/png Expires -1 Last-Modified Sun, 11 Oct 2009 19:01:40 GMT Accept-Ranges bytes Etag "f318d643a54aca1:0" Server Microsoft-IIS/7.0 X-Powered-By ASP.NET Date Sun, 11 Oct 2009 20:40:01 GMT Content-Length 620 Note the Cache-Control and Expires values for this static image being requested. The site is currently compiled in Debug (this will change), but surely that wouldn't make a difference? Obviously I'm overlooking something, any ideas would be appreciated. Thanks
IIS7 + ASP.NET MVC Client Caching Headers Not Working
A consideration is the typical usage pattern. Do most snapshots eventually result in either being printed or exported or both? If such is the case, we might as well "get it in memory" (temporarily) in the form of a non blocking (asynchronous) select statement from the device to the server. In this fashion the data will "be there" or well on its way when user decides to use it. If on the other hand many snapshot end up not being effectively used, Solution #1 seems quite ok (maybe the table could be named after the account/user, hence guaranteeing "self clean up" based on the number of snapshot a user can maintain at a given time (though it seems to be just one, with even the tolerance of loosing it sometimes).
Background I have an SQL CE database, that is constantly updated (every second). I have a (web) application that allows a user to look at the data in real-time. At some point a user can click "take a snapshot" button, and it will open the snapshot in a different window. And then on that form, there is "print" and "download" buttons that will either generate a page for printing, or will stream the data as CSV file - but same data snapshot has to be used, i.e. I can't go to the DB to get latest data for that. Details SQL CE dabatase is exposed through WCF web service. Snapshot consists of up to 500 records, 10 columns each. Expiration time on the snapshot of 2 hours is sufficient. It is a low-traffic application, so I don't expect more than few (5) connections at the same time. Loosing snapshot is not a big deal, user can simply generate new one. database is accessed by self-hosted WCF web service using Linq-to-SQL. Web site is ASP.NET MVC hosted on UltiDev Cassini. database, and web site are most likely be on the same box, when deployed. The entire app is intranet bound. Problem I need to cache the snapshot of the data at the moment user pressed "take a snapshot" button, so that I can use same data to generate print page, or generate a file for download. Solution 1: Each time there is a need to generate a snapshot, I will create a table in the database. Since there are no temp tables in SQL CE, I will need to clean it up myself. Solution 2: Cache the snapshot in-memory on either DB server, or web server. Question: Is there anything wrong with proposed solutions? Any different solution suggestions?
Cache data in SQL CE database
2 Similar to voldy's answer but using non-deprecated methods. caches_action :show, :cache_path => :post_cache_path.to_proc, :expires_in => 1.hour protected def post_cache_path if request.xhr? "#{request.url}.js" else "#{request.url}.html" end end Share Improve this answer Follow answered May 7, 2012 at 0:18 Philip CunninghmPhilip Cunninghm 3355 bronze badges Add a comment  | 
I have a rails action which responds to requests in various formats including AJAX requests, for example: def index # do stuff respond_to do |format| format.html do # index.html.erb end format.js do render :update do |page| page.replace_html 'userlist', :partial => "userlist", :object=>@users page.hide('spinner') page.show('pageresults') end end end end I have set this action to cache using memcached using: caches_action :index, :expires_in=>1.hour, :cache_path => Proc.new { |c| "index/#{c.params[:page]}/#{c.request.format}" } This pattern seems to work fine for caching the HTML result but not for the JS result. The JS part always works fine when it is not coming from the cache. However when there is a cache hit, the page does not update. What could cause this and what is the fix? Update: digging into this more it looks like requests from the cache get mime type 'text/html' instead of 'text/javascript'. However I'm not sure how to fix this - is it a quirk of memcached? (Rails 2.3.2)
How can caches_action be configured to work for multiple formats?
2 Rails only adds the session cookie data to the Set-Cookie header if it has been touched. You might be setting things to the values that they already contain - it's not smart enough to check to see if the data is actually different. edit My response is a little misleading. When you are using the cookie session store, a new cookie is set if the cookie value (after Marshaling) changes. See actionpack/lib/action_controller/session/cookie_store.rb Share Improve this answer Follow edited Mar 17, 2010 at 2:23 answered Mar 15, 2010 at 20:59 outcassedoutcassed 5,23322 gold badges2828 silver badges2424 bronze badges 2 Yeah I already suspected that... Does "touching" in this sense also mean reading from the session hash? +1 for supporting my suspicion – hurikhan77 Mar 16, 2010 at 15:18 Reading is okay. Check out CGI::Session::CookieStore#close in actionpack/lib/action_controller/session/cookie_store.rb – outcassed Mar 17, 2010 at 2:15 Add a comment  | 
How do I prevent Rails from always sending the session header (Set-Cookie). This is a security problem if the application also sends the Cache-Control: public header. My application touches (but does not modify) the session hash in some/most actions. These pages display no private content so I want them to be cacheable - but Rails always sends the cookie header, no matter if the sent session hash is different from the previous or not. What I want to achieve is to only send the hash if it is different from the one received from the client. How can you do that? And probably that fix should also go into official Rails release? What do you think?
Prevent Ruby on Rails from sending the session header
Ignoring the possibility of a server farm and load balancing, this behaviour can be caused by the application pool running as a web-garden. To quote the relevant section from MSDN: Because Web gardens enable the use of multiple processes, each process will have its own copy of application state, in-process session state, caches, and static data. Web gardens should not be used for all applications, especially if they need to maintain state. Be sure to benchmark the performance of the application before deciding whether Web garden mode is appropriate. This will cause it to appear as if caching is storing multiple values for the same key, effectively having duplicate entries in the cache. To resolve this in IIS 7, open the application pool's Advanced Settings and set Maximum Worker Processes to 1. For IIS 6, see the MSDN article (With pretty screenshots). Albeit 8 months late, I'm answering this question because I found it long before I found this decent article on web-garden gotchas. Hopefully this answer will save future searchers a chunk of time. :)
Although i have specified a unique key, it seems the following code will return one value for 5 requests, then another for the next couple, then revert back to the value saved in the original request and just continue until there are 10's of different objects all stored under the same key. It then seems almost random which of these values it will return from the cache. string strDateTime = string.Empty; string cachename = "datetimeexample"; object cachedobject = HttpRuntime.Cache.Get(cachename); if (cachedobject != null) strDateTime = (string)cachedobject; else { strDateTime = DateTime.Now.ToString(); HttpRuntime.Cache.Insert(cachename, strDateTime, null, DateTime.MaxValue, TimeSpan.FromDays(10), CacheItemPriority.NotRemovable, null); } Response.Write(strDateTime +" keys:"+ HttpRuntime.Cache.Count); Very confused, is this because of threading or something?
Httpruntime cache keys not unique?
2 Use this function to get page content and You can save it in your database. your table must contain 2 columns: 1-url 2-pagecontent static string GetHtmlPage(string PageURL) { String r; WebResponse wres; WebRequest wreq= HttpWebRequest.Create(PageURL); wres= wreq.GetResponse(); using (StreamReader sr = new StreamReader(wres.GetResponseStream())) { r= sr.ReadToEnd(); sr.Close(); } return r; } Share Improve this answer Follow answered Aug 3, 2009 at 11:24 HosseinHossein 1,69922 gold badges2727 silver badges4242 bronze badges Add a comment  | 
I'm thinking of a way of creating a local backup for the pages I will be linking to from my site. This would be text-only, similar to Google's 'Copy' feature on the search pages. The idea is to be sure that the pages I would reference to, or cite from, do not dissapear from the Web in the near future. I know I could just keep local copies, but I will have A LOT of citations. What would be the best way of achieving this in ASP.NET? Some custom caching in database?
Caching linked pages in ASP.NET
CPU designs appear to be evolving towards hardware support for tagged TLB entries. This eliminates the need to flush the TLB. So even assuming that TLB flushing is a concern for today's processors, it may not be relevant anymore in a few years. I wouldn't base any design decisions on it.
I wonder if there is a common mechanism implemented in operating systems to minimize TLB flushes, by for instance grouping threads in the same process together in a "to be scheduled" list. I think this is an important factor when deciding between using processes against threads. If OS doesn't care whether the next thread is in the same process space or not, the so called advantage of threads "minimizing TLB flushes" might be overrated. Is that the case? Consider a system with hundreds of threads and tens of processes. If these are not optimized in a way to schedule threads in same process in tandem, our expectations on thread performance may not be that big. I'll give examples if question isn't that clear.
How hard do operating systems try to minimize TLB flushes?
Try Ventus Proxy For Webservices. it does exactly what you need. http://www.ventusproxy.com
I'd like to put some kind of caching reverse proxy in front of a SOAP webservice over HTTP to improve both performance and availability. Is there some software that performs this? (Preferably free and easy to install/use). The idea is here: the responses of the webservice vary with the request, but for each request the responses rarely change. So the proxy could store the responses for each request for some time, and give the cached response when the same request is sent again. There is only a limited number of different requests. The proxy does not need to parse and understand the request or response. But it does need to understand HTTP POSTs and, say, construct a hash of the request in order to find the correct response. Caching by the URL, as done normally in HTTP Proxies, does not help here. (Of course one can cache the webservice's results in the application that calls the webservice, but I am looking for a solution that is standalone, independent from the application.)
Webservice caching reverse proxy?
Definitely possible. I suggest using the enyim.com client instead of the "official one" as it a lot faster.
I'm considering using memcached (at some point) in my application i'm currently developing. Eventually, i'm planning on hosting this on Amazon EC2 - i was just wondering, would it be possible to have a linux server (aws instance) running memcached, and use the windows server (aws instance) for the app, but set it to use the linux server for the cache??
memcached - using with a C# asp.net application
2 I also observed the same behavior on XP. I am trying to clear IE cache programmatically using WinInet APIs. The code at the following MSDN link works perfectly fine on Win7/Vista but deletes cache files in batches(multiple runs) on XP. On debugging I found that API FindNextUrlCacheEntry gives different sizes for the same entry when executed multiple times. MSDN Link: http://support.microsoft.com/kb/815718 Here is what I am doing: First of all I make a call to determine the size of the next URL entry fSuccess = FindNextUrlCacheEntry(hCacheHandle, 0, &cacheEntryInfoBufferSizeInitial) // cacheEntryInfoBufferSizeInitial = 0 at this point The above call returns false with error no as INSUFFICIENT_BUFFER and with cacheEntryInfoBufferSizeInitial parameter set equal to the size of the buffer required to retrieve the cache entry, in bytes. After allocating the required size (cacheEntryInfoBufferSizeInitial) I call the same WinInet API again expecting it to retrieve the entry successfully this time. But sometimes it fails. I see that the cases in which API fails again even though with required buffered sizes (as determined it only) because it expects morebytes then what it retrieved earlier. Most of times the difference is of few bytes but I have also seen cases where the difference is almost 4 to 5 times. Share Improve this answer Follow answered Jan 7, 2011 at 19:26 user561832user561832 5111 silver badge55 bronze badges 1 I have experienced this as well. I simply allocate (yet again) the NEW size returned and that seems to work for a subsequent call to FindNextUrlCacheEntry() Have you figured out why different sizes are returned? – Ryan Griffith Jan 13, 2014 at 16:34 Add a comment  | 
I got a ERROR_INSUFFICIENT_BUFFER error when invoking FindNextUrlCacheEntry(). Then I want to retrieve the failed entry again, using a enlarged buffer. But I found that when I invoke FindNextUrlCacheEntry(), it seems I was retrieving the one next to the failed entry. Is there any approach I can go back to retrieve the information of the just failed entry?
If FindNextUrlCacheEntry() fails, how can I retrieve info of the failed entry again?
1 One way to do it is to store the sorting permutation of all tails of your text (text from certain point up until end). Then to find a substring you binary search for it in those cyclic shifts. Memory used using 32 bit ints would be 4 bytes per original character. p.s: I heard there is a way to accomplish a similar thing by storing the Burrows-Wheeler transform of the text (1 charecter per original charecter) but I can't seem to find any references to it.. Share Improve this answer Follow answered Jun 18, 2009 at 0:01 yairchuyairchu 24.1k77 gold badges7070 silver badges111111 bronze badges 2 Permutations! THAT'S a great idea! I'll just split each "word" into characters, sort them, and store the result as map key (such result would be the "initial permutation", or "permutation 0"). Querying would be done similar! – ivan_ivanovich_ivanoff Jun 18, 2009 at 15:50 Oh, sorry, my proposal with permutations would not allow to search of partial character sequences :( – ivan_ivanovich_ivanoff Jun 18, 2009 at 17:57 Add a comment  | 
I wonder, how are systems for fulltext search implemented, to be able to query millions of entries very fast? Please note: I'm not talking about systems which tokenize the content by separating it at whitespaces, but about system which are able to query even parts from the middle of tokens (which is a real challange). Background information I experimented with a home-made string cacher (using Java) which is able to search for strings, given a substring as query. The substring is not required to be at the begin of potential retrieved strings. It works on a huge array of strings. Caching is done using a TreeMap<Character,TreeSet<String>>. Adding entry For each unique character in the to-be-added string: Get the set for that character, and add the string to it. Example: "test" is first split in "t", "e", "s". Then, we retrieve the sets for those three keys, and add "test" to each of the set. Querieng Querying is done by splitting the query into unique characters, retrieve for every character a Set<String>, build an intersection of all sets, and finally search the intersection using contains() to ensure correct order of query characters. Benchmark On a 3GHz machine, I added 2'000'000 strings with average length of 10, random content. Done 100 queries. It took: Min: 0.4sec, Average: 0.5sec, Max: 0.6sec. 1.5GB of memory were wasted.
How do fulltext indexers (or caches) work?
turns out it is part of NHContrib http://sourceforge.net/projects/nhcontrib/
In the nhibernate doco is states that to use the prevalence cache use the provider class “NHibernate.Caches.Prevalence.PrevalenceCacheProvider, NHibernate.Caches.Prevalence” https://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/performance.html#performance-cache Where do I go to doanload the assembly that contains this type? According to the doco (https://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/caches.html) it can be obtained from http://bbooprevalence.sourceforge.net/ . But I downloaded Bamboo.Prevalence-1.4.4.4 and could not find any cache assemblies. Thanks
Where to download the assembly that contains NHibernate.Caches.Prevalence.PrevalenceCacheProvider, NHibernate.Caches.Prevalence?
2 You can have a single re-use identifier, but to change the height you'll have to implement the UITableViewDelegate method: - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath That said, I can't imagine one cell that's 44 pixels high and another that's 70 pixels high as having the "same general" configuration. If they're that different in height, they're probably going to be that different in contents, and that would require different re-use identifiers. Share Improve this answer Follow answered Mar 16, 2009 at 14:06 AugustAugust 12.2k33 gold badges3030 silver badges3030 bronze badges 2 I'm looking to do this, and the only difference is that some cells have taller images than others so there is a case where variable height would work for the same reuse identifier. – Kevlar Apr 14, 2009 at 21:06 2 If they're that different in height, they're probably going to be that different in contents, and that would require different re-use identifiers. Not so much actually. The memory overhead comes from having to create and destroy objects like Labels, TextViews, and Buttons. If you're just changing sizes but keeping the same general layout (ie: same objects), it should be fine and work better to reuse cells. – Michael Grinich Jul 10, 2009 at 5:08 Add a comment  | 
I have five different cells in a table across five sections differing just in height, and text. Will I need to have one reuse identifier or five ? I am using a custom cell. The Apple document talks about reuse with cell having the "same general" configuration. Does differing height make each different for caching and reuse perspectives. I may use differing fonts but the rest of the stuff between cells is the same, color etc. When I pop this table and push a new one the new table cell again will differ in height based on the amount of text content in the new row selection. Since my device seems already getting hot while running my app just want to make sure I do this efficiently. I want to reuse the cache and cells within the table as well as when reloading table with new data. Would appreciate some suggestions.
UITableViewCell Reuse Identifier with Variable Height Cells
Some rules of thumb Think in terms of cache miss to request ratio each time you contemplate using the cache. If cache requests for the item will miss most of the time then the benefits may not outweigh the cost of maintaining that cache item Contemplate the query expense vs cache retrieval expense (e.g. for simple reads, SQL Server is often faster than distributed cache due to serialization costs) Some tricks gzip strings before sticking them in cache. Effectively expands the cache and reduces network traffic in a distributed cache situation If you're worried about how long to cache aggregates (e.g. counts) consider having non-expiring (or long-lived) cached aggregates and pro-actively updating those when changing the underlying data. This is a controversial technique and you should really consider your request/invalidation ratio before proceeding but in some cases the benefits can be worth it (e.g. SO rep for each user might be a good candidate depending on implementation details, number of unanswered SO questions would probably be a poor candidate)
Closed. This question is opinion-based. It is not currently accepting answers. Want to improve this question? Update the question so it can be answered with facts and citations by editing this post. Closed 2 years ago. Improve this question I have been doing some reading on this subject, but I'm curious to see what the best ways are to optimize your use of the ASP.NET cache and what some of the tips are in regards to how to determine what should and should not go in the cache. Also, are there any rules of thumb for determining how long something should say in the cache?
What are some ways to optimize your use of ASP.NET caching? [closed]
There is nothing wrong with caching your database queries. For every category name you can store the ID in a dictionary as an example that expire after a certain period of time. This will remove the DB calls in this case. As an example: Dictionary<string, int> categoryIdLookup; This can be stored in the HTTP cache and retrieved, if it is null (I.e. it has never been added or has fallen out of cache) build the dictionary, lookup the correct Id and then do the rewrite.
I'm performing a UrlRewrite for my main category pages. Converting: www.mysite.com/Category.aspx?id=2 to www.mysite.com/Dogs In order to do so I'm using Global.asax's Application_BeginRequest where I perform the following code(pseudocode): protected void Application_BeginRequest(Object sender, EventArgs e) { if (IsCategoryUrl()) { string CategoryName = ParseCategoryNameFromUrl(Request.Url); string CategoryId = GetCategoryIdByNameFromDB( CategoryName ); Context.RewritePath("/Category.aspx?id=" + CategoryId); } } My questions are: Is this the right way to perform Url Rewriting? (It's the first time I'm doing so). This code causes a read from DB on almost EVERY request, is there any way to cache it? The only technique I found for SQL Caching required a <%@ Page %> directive which isn't possible on the global.asax. Any other solution? Thanks in advance.
UrlRewriting on Global.asax and SQL Output Caching
The only reason it may be bad to use the static property is that breaks the separation of concerns between your view and your model. The model should be the only one concerned with how the data is retrieved - even from objects that are in the same application domain. While it may seem like overkill to present this data to the view via ViewData it really is the best practice as it preserves the separation of concerns. The more you actively preserve this separation, the better your application will handle refactoring and bug fixes down the road.
I am creating a portal where many sites will run of the same MVC application. I have a list of Sites stored in the HttpRuntime.Cache. Is it wrong to access the cache via a static method? Should I instead be passing this on view data? For example, is this wrong on the view: Where the code for SiteHelper is: public class SiteHelper { private static object @lock = new object(); private const string siteKey = "FelixSites"; public static Site CurrentSite { get { var context = HttpContext.Current.Wrap(); var sites = context.Cache[siteKey] as Site[]; if (sites == null) { lock (@lock) { if (sites == null) { sites = SiteService.GetSites(); context.Cache[siteKey] = sites; } } } return sites.Single(s => s.Domain == context.Request.UrlReferrer.AbsoluteUri); } } }
In ASP.Net MVC, is using static methods to look up cached objects on views bad practice?
You'll have HTML5.0 with local database-like features. However what do you mean by secure? HTML5.0 will be secure against cross-site issues, but the user will still have full access to the data, I don't think encryption is required. Google gears does fit, but its not a standard while HTML5.0 is, Safari supports 5.0, and I guess Opera and Firefox will too by mid 2009, if they don't already. Explorer, probably will have some buggy implementation so they can force developers to use Silverlight. Edit: Stephen, I see you need to destroy the cache after they leave, of course unless their machine has a proximity sensor this won't be possible :) But you could have your Javascript delete everything when they Logoff for example. Link to HTML5.0 specs, Link to HTML5.0 Cache specs Link to HTML5.0 session storage specs (By popular request :)
Note: this is a different problem to https - it's related to privacy security I'm trying to figure out if there's a way to take load off our server [cache] by pushing information to the browser. Is there any technology that will provide secure caching that is bound to a session? We have privacy-sensitive data that's often used, but will not change much. Re-requesting updates from the server/database all the time will reduce the sensitivity. The solution cannot rely on any page being held open the entire time (e.g. no framesets). Navigation away from a page (or opening a new tab) is allowed. Does Google Gears fit here? I can't find any way of tying the cache to the session. The problem domain is cafe/shared machine login with multiple web app users. e.g. when the session expires, or the user logs off, there should be no cached data anywhere. While they are logged on, I presume that nobody will else have physical access to the computer. See also Can HTML5 sessionStorage be written to disk?
Is there a secure browser cache?
I ended up following this discussion post https://github.com/vercel/next.js/discussions/48324 and setting the get() method of Next's IncrementalCache to return early, and the data threshold of the set() function to be very low, effectively skipping them entirely. Not sure if next hits those caches any other time, especially if my entire site is static so I think this solution should be fine. node_modules/next/dist/esm/server/lib/incremental-cache/index.js & node_modules/next/dist/server/lib/incremental-cache/index.js // get data from cache if available async get(cacheKey, ctx = {}) { return null; ... } async set(pathname, data, ctx) { ... if (ctx.fetchCache && JSON.stringify(data).length > 0.001 * 1024 * 1024) { if (this.dev) { throw new Error(`fetch for over 0.001MB of data can not be cached`); } return; } ... }
The Problem When I run next build, newly fetched data is not being served to the client, even though the fetch call is hitting my server. I can solve the problem by using {cache: "no-store"} in my fetch requests, but that turns my SSG pages into SSR which I don't want. Nextjs version: 13.5.2 (app router) Replication Change data on local instance of CMS (I'm using Strapi) Run next build within several components, fetch() calls to CMS and populates site Run next start Normal refresh or hard refresh to attempt to see new data Result: I can see fetch hitting my CMS, but the fresh data is not displayed. This persists over multiple builds. Example code (simplified): /articles.ts export async function getArticleBySlug(slug){ try { const res = await fetch(path, { method: GET }) return await res.json() } catch (error) { console.log(error) return null } } [slug]/page.tsx export default async function Article({ params }) { const article = await getArticleBySlug(params.slug) return <div>{article.data}</div> } Hypothesis From my research, it seems like the Nextjs Data Cache is the culprit here. The docs say the data cache is persisted between deployments, which is a feature I don't want. I want the cache to be completely invalidated on every build, while maintaining SSG. A funny solution to this seems to be having my fetch calls be larger than 2MB. That way the cache is unable to be set but SSG is preserved. Forcing all of my requests to be larger than 2MB is definitely not the solution, so other ways of solving this would be greatly appreciated! Another janky solution would be setting the cache invalidation limit to something really low, but that also seems wrong. It's very possible I'm diagnosing my problem incorrectly, but I can't seem to find any other reason why stale data would be populating my site. Thank you for the help!!
How to disable caching between deployments while maintaining SSG in Nextjs13 app router?
Check your Redis server configuration to ensure that key expiration is enabled. Look for the notify-keyspace-events configuration directive in your Redis configuration file (redis.conf) and make sure it includes the Ex flag. For example, notify-keyspace-events Ex.
I have a Micronaut cache in Redis configured like this: redis: uri: ${REDIS_URL:`redis://localhost`} caches: kyc-fenergo-service-token: expire-after-write: 14m I have a method annotated like this: @Cacheable(value = "kyc-fenergo-service-token") After the first call, the value is cached as expected, but it never expires. Any idea why this is the case?
Why don't items expire in my Micronaut/Redis cache?
1 terra does some work to allow serialization, for example: library(terra) f <- system.file("ex/elev.tif", package="terra") r <- rast(f) saveRDS(r, "test.rds") readRDS("test.rds") [1] "This is a PackedSpatRaster object. Use 'terra::rast()' to unpack it" readRDS("test.rds") |> rast() #class : SpatRaster #dimensions : 90, 95, 1 (nrow, ncol, nlyr) #resolution : 0.008333333, 0.008333333 (x, y) #extent : 5.741667, 6.533333, 49.44167, 50.19167 (xmin, xmax, ymin, ymax) #coord. ref. : lon/lat WGS 84 (EPSG:4326) #source : memory #name : elevation #min value : 141 #max value : 547 But it seems that knitr caches with "save" to an RData file; in that case, the raw object is stored, which won't be valid when reloaded. I think it may be possible to work around this with some clever use of hook functions; but that would be so involved that it would defeat the purpose of caching. Share Improve this answer Follow edited Jun 17, 2022 at 12:01 answered Jun 17, 2022 at 6:54 Robert HijmansRobert Hijmans 43k44 gold badges5858 silver badges6767 bronze badges Add a comment  | 
I'm using knitr to make a document that uses the terra package to draw maps. Here's my minimal .Rmd file: ```{r init, echo=FALSE} library(knitr) opts_chunk$set(cache=TRUE) ``` ```{r maps} library(terra) r = rast(matrix(1:12,3,4)) plot(r) ``` ```{r test2} print(r) plot(r) ``` First run (via rmarkdown::render(...)), this works, creates a test_cache folder. Running a second time (with no changes) it also runs fine. If I make a minor change to chunk 2 (eg add a comment) and run I get: Quitting from lines 14-17 (cache.Rmd) Error in .External(list(name = "CppMethod__invoke_notvoid", address = <pointer: (nil)>, : NULL value passed as symbol address I've also had this from another Rmd file, probably related: Quitting from lines 110-115 (work.Rmd) Error in x@ptr$readStart() : external pointer is not valid clearing the cache or running with cache=FALSE then works, but then what's the point of the cache. I think its because r is some sort of reference class which exists via some memory allocated by Rcpp, and knitr is only caching a reference, so when it tries to read the cached version it gets a reference to memory which doesn't have the object that was created to go with the reference there. So it fails. FWIW a terra0 raster object looks like this: terra1 and terra2 Is there a way to make the knitr cache work with these objects? I know I could exclude just these from the cache but 90% of my document is working with these sorts of objects and that's the reason I want to use the cache to speed things up. But then every time I get this error I have to stop, clear the cache, start again, and I don't know if that time is worth the speedup I get with the cache. R 4.1.1 with terra3
Can knitr's cache work with pointer objects?
1 Try adding blocking flag set to true so that your computation waits until that cached data is really removed. [ def unpersist(blocking: Boolean) ] data_frame.unpersist(true) Share Improve this answer Follow answered Oct 8, 2021 at 9:41 chomar.cchomar.c 7155 bronze badges Add a comment  | 
I am reading a bench of csv file at a specific path : spark.read.format('csv').load('/mnt/path/') I am caching my dataframe in order to access corrupt records enter link description here data_frame.cache() At the end of my notebook, i want to remove this path from the cache by using data_frame.unpersist() Then I am changing the underlying data, for example deleting or adding new files to the table path But if i read again the csv, spark.read.format('csv').load('/mnt/path/'), spark does not have the last changes, it still shows the cached data. Which makes me think that the dataframe is not really uncached. The only way it can work out, it is restarting the cluster. I dont want to use spark.catalog.clearCache() as this would impact caching all the jobs running on the cluster. I only want to uncache the specific dataframe from the current notebook. Any suggestion or observation would be much appreciated. edit : I was not assigning it to my dataframe. It looks like there is a difference between data_frame = data_frame.unpersist() and data_frame.unpersist()
Why unpersist() does not remove my path from the cache in pyspark in Azure Databricks?
1 +100 AFAIK, I am afraid that the implementation of the cache mechanism is tightly coupled in the library. All the actual interactions with Redis are performed by DefaultRedisCacheWriter which is package scoped. The following code is the one corresponding to the put (cache) operation. As described in the Spring Data Redis documentation, probably the way to go will be providing your own RedisCacheWriter, I assume based on DefaultRedisCacheWriter with the necessary modifications, and configure Spring cache RedisCacheManager appropriately: RedisCacheWriter cacheWriter = // Provide your custom implementation... RedisCacheManager cm = RedisCacheManager.build(cacheWriter) .cacheDefaults(defaultCacheConfig()) ... Share Improve this answer Follow edited Aug 11, 2021 at 22:41 answered Aug 11, 2021 at 22:05 jccampanerojccampanero 52k33 gold badges2323 silver badges5353 bronze badges Add a comment  | 
I have students which I would like to save both in DB and in Redis cache for improving performance. I have the Student POJO: @NoArgsConstructor @AllArgsConstructor @Builder @Data @RedisHash("Student") public class Student implements Serializable, RedisElement { private static final long serialVersionUID = 4555735174035964832L; public enum Gender { MALE, FEMALE } @Id private String id; private String name; private Gender gender; private int grade; } Used in StudentRepository: @Repository public interface StudentRepository extends CrudRepository<Student, String>{ } I have service which can add, find and delete student: @Service public class StudentsService { @Cacheable(value = "Student", key = "#id") public Student findById(String id) { // simulates getting it from db Student studentFromDB = Student.builder().id(id).name("db user " + id) .gender((new Random()).nextDouble() > 0.5 ? Gender.FEMALE : Gender.MALE) .grade((new Random()).nextInt(100)).build(); return studentFromDB;// will be cached next time } @CachePut(value = "Student", key = "#id") public Student add(Student student) { System.out.println("added student " + student); return student; } } Running my application with RedisApplication: @SpringBootApplication @EnableAutoConfiguration @EnableRedisRepositories public class RedisApplication { public static void main(String[] args) { SpringApplication.run(RedisApplication.class, args); } } Whenever I call explicitly to the studentrepository.save(student) method , it calls Redis HMSET and SADD commands to add the student to the cache, but when I use Spring @Cachaeble to do that, it uses the Redis Set command to add the student. How can I configure @Cachaeble or @CachePut to treat student object the way that calling explicitly will use the Redis HMSET and SADD commands?
Spring Redis save POJO as different types when using @Cacheable or @CachePut
1 As it explains here, you can cache the whole virtual environment: - uses: actions/cache@v2 with: path: ${{ env.pythonLocation }} key: ${{ env.pythonLocation }}-${{ hashFiles('setup.py') }}-${{ hashFiles('dev-requirements.txt') }} Share Improve this answer Follow edited Mar 23, 2021 at 12:48 Espoir Murhabazi 6,16055 gold badges4545 silver badges7575 bronze badges answered Jan 10, 2021 at 17:34 Antonio Gamiz DelgadoAntonio Gamiz Delgado 1,93711 gold badge1414 silver badges3636 bronze badges 2 No, I tried it and it doesn't work for me. I have no env.pythonLocation variable in my github workflow. – xpt Dec 18, 2021 at 19:36 You need to use the setup python action to have that variable – Antonio Gamiz Delgado Dec 19, 2021 at 13:46 Add a comment  | 
I'm trying to cache the python dependencies of my project. To do that, I have this configuration in my workflow: - uses: actions/cache@v2 id: cache with: path: ~/.cache/pip key: pip-${{ runner.os }}-${{ hashFiles('**/requirements.txt') }}-${{ hashFiles('**/requirements_dev.txt') }} restore-keys: pip-${{ runner.os }} - name: Install apt dependencies run: | sudo apt-get update sudo apt-get install gdal-bin - name: Install dependencies if: steps.cache.outputs.cache-hit != 'true' run: | pip install --upgrade pip==9.0.1 pip install -r requirements.txt pip install -r requirements_dev.txt This works, by 'works' I mean that it loads the cache and skip the 'Install dependencies step' and it restores the ~/.cache/pip directory. The problem is that when I try to run the tests, the following error appears: File "manage.py", line 7, in <module> from django.core.management import execute_from_command_line ImportError: No module named django.core.management Error: Process completed with exit code 1. Am I caching the incorrect directory? Or what am I doing wrong? Note: this project is using python2.7 on Ubuntu 16.04
Cache is not being correctly loaded in Github actions
1 You can store the compiled regular expressions in pickle files: import re import pickle r1 = re.compile('\d\d\d') with open('tmp', 'wb') as fh: pickle.dump(r1, fh) with open('tmp', 'rb') as fh: r2 = pickle.load(fh) print(r2.match('673')) <re.Match object; span=(0, 3), match='673'> Share Improve this answer Follow answered Dec 4, 2020 at 14:43 sophrossophros 15.4k1111 gold badges4848 silver badges7777 bronze badges 8 1 But loading those precompiled regexes is pretty much guaranteed to take more time than recompiling them. – Ivan C Dec 4, 2020 at 14:47 Not if you store them in a dictionary and pickle the whole dictionary. – sophros Dec 4, 2020 at 14:54 @John Jackson: if you find the answer useful could you please mark the answer as accepted? – sophros Dec 8, 2020 at 11:33 @sophros Thank you for your answer! I'll give it a try this week and let you know how it works out! I apologize for the late response; life has been hectic... – John Jackson Dec 9, 2020 at 5:15 I finally got time to try this out today. It saved about 2 seconds out of 55. Saving the compiled regexes appeared to be no problem, but loading them back took almost as much time as compiling them. I ran the experiment 3 times to get a feel for the variance. The experiment compiled 653 regexes whose total text length (uncompiled length) added up to 1042102 characters. The regexes were contained in a dictionary, which is what I pickled and unpickled. The average compile time was 55.4 seconds The average pickle save time was 0.006 seconds The average pickle load time was 53.8 seconds – John Jackson Dec 15, 2020 at 3:15  |  Show 3 more comments
I have an application that loads a large table of regular expressions from an Excel file, compiles them, and then uses them to perform its function. It takes about 2 minutes for Python to compile the regular expressions, which will increase as I add more expressions to the Excel file. The Excel file does not change often, so I would like to avoid the two-minute+ startup time whenever the Excel file has not changed. Is there a way to cache the compiled regular expressions to a file that I can load when the Excel file hasn't changed?
Can you pre-compile regular expressions in Python, save them to a file, and then reload them from the file?
1 I found. I share it to help you. var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_cache) as dynamic; List<ICacheEntry> cacheCollectionValues = new List<ICacheEntry>(); foreach (var cacheItem in cacheEntriesCollection) { ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null); cacheCollectionValues.Add(cacheItemValue); } Share Improve this answer Follow answered Oct 25, 2020 at 14:14 community wiki ozancank Add a comment  | 
How to list all the register keys from Memory Cache in the .NET Core web application?
How to retrieve a list of Memory Cache keys in .NET Core?