Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
24 According to full page configuration you have to set hosting key first. This has to work: { "hosting": { "public": "app", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ], "headers": [{ "source" : "**", "headers" : [{ "key" : "Cache-Control", "value" : "max-age=31536000" }] }] } } Share Improve this answer Follow edited Apr 3, 2023 at 16:07 answered Sep 4, 2016 at 11:00 Arnold GandarillasArnold Gandarillas 4,05411 gold badge3232 silver badges3636 bronze badges 9 I did this for the headers and I have to hard refresh to see my index.html changes – AngularM Mar 31, 2017 at 16:29 Hi buddy to avoid this issue you can disable your cache or if you are already in production but you have to do some changes in short periods you can set max-age=3600 in this way the browser will request new data each hour. – Arnold Gandarillas Mar 31, 2017 at 21:46 I'm using angular 2 and my aim is to prevent my customers having to hard refresh – AngularM Mar 31, 2017 at 22:00 1 I set max age to 0 and they still have to hard refresh. – AngularM Mar 31, 2017 at 22:46 1 How can I prevent that? – AngularM Mar 31, 2017 at 22:46  |  Show 4 more comments
The Cache-Control header in my firebase.json does not seem to be working. The max-age value for all files is set to 31536000 (1 year), but when loading the page it is still set to the browser default of 3600 (1 hour). The firebase.json file seems to abide by the firebase documentation. { "hosting": { "public": "public" }, "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ], "headers": [{ "source": "**", "headers": [{ "key": "Cache-Control", "value": "max-age=31536000" }] }] }
Cache-Control header in firebase.json not working
if you are using htaccess then you can do like #Initialize mod_rewrite RewriteEngine On <FilesMatch "\.(html|htm|js|css)$"> FileETag None <IfModule mod_headers.c> Header unset ETag Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate" Header set Pragma "no-cache" Header set Expires "Wed, 12 Jan 1980 05:00:00 GMT" </IfModule> </FilesMatch>
I put only index.html in /var/www/html. The page doesn't update after I changed the contents of index.html and reload. I already disable cache_module in httpd.conf like this below. # LoadModule cache_module modules/mod_cache.so # LoadModule disk_cache_module modules/mod_disk_cache.so
How to disable cache of Apache?
The following works to instruct the browser to cache the files. The last line was necessary to make the server deliver webm files with the correct header MIME type. # Expires is set to a point we won't reach, # Cache control will trigger first, 10 days after access # 10 Days = 60s x 60m x 24hrs x 10days = 864,000 <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 will the browser cache files? Sometimes it does, sometimes it doesn't. If no one here knows, my next step will be to test the various file format, file size, and htaccess scenarios. If you don't know, can you think of any other variables that you'd recommend testing? Thanks in advance!
Under what conditions will the browser cache <video> files?
Adding an additional answer here as I feel the existing one capture the 'what' but not enough of the 'why'. The reason it's best to store individual entries separately in the cache have little to do with perf. Instead, it has to do with allowing the system to perform proper memory management. There is a lot of logic in the ASP.NET cache to figure out what to do when it runs into memory pressure. In the end, it needs to kick out some items, and it needs to do this in the least disruptive way possible. Which items it chooses to kick out depends a lot of whether they were accessed recently. There are other factors, like what flags are passed at caching time. e.g. you can make an item non-removable, and it'll never be kicked out. But going back to the question, if you store your entire dictionary as a single item, you are only leaving two options to the ASP.NET memory manager: keep the entire thing alive, or kill the whole thing. i.e. you completely lose the benefit of having your 'hot' items stay in the cache, while your rarely accessed memory-hogging items get kicked out. In other words, you lose any level of caching granularity. Of course, you could choose to implement your own scheme in your dictionary to remove items that are rarely used. But at that point you're re-inventing the wheel, and your new wheel will not work as well since it won't coordinate with the rest of the system.
I have a website where I cache a lot of info. I am seeing conflicting information around storing stuff in the asp.net cache. For example lets say I have this data structure: Dictionary<string, List<Car>> mydictionary; I could store the whole thing with a string key as "MyDictionary" and then drill down once i pull out the object. HttpContext.Cache.Add("MyDictionary", mydictionary, null, Cache.NoAbsoluteExpiration, new TimeSpan(10, 0, 0), CacheItemPriority.Normal, null); var myDict = HttpContext.Cache["MyDictionary"] as Dictionary<string, List<Car>>; The other thing i could do is break it down and store each item in my dictionary separately in the cache (given the cache is a dictionary anyway). Dictionary<string, List<Car>> mydictionary; foreach (var item in mydictionary.Keys) { HttpContext.Cache.Add(item, mydictionary[item], null, Cache.NoAbsoluteExpiration, new TimeSpan(10, 0, 0), CacheItemPriority.Normal, null); } var myitem = "test"; var myDict = HttpContext.Cache[myItem] as List<Car>; Would the performance implication be very different (given i am assuming that everything is in memory anyway ?)
What is the most efficient way to store / retrieve items in asp.net httpContext.Cache
It is recommended that you use System.Web.HttpRuntime.Cache rather than System.Web.HttpContext.Current.Cache, as explained in this article. Additionally, while the article talks about performance, I've also had issues in the past where HttpContext.Current isn't always available when you'd expect it to be, especially when dealing with asynchronous handlers. Another thing to note is that if you aren't accessing the cache in the context of an HTTP request, HttpContext won't help you, since there won't be a relevant context for you to access.
How can I access HTTP Cache in a C# class library ?
How can I access HTTP Cache in a C# class library?
Make a separate location block for config.js above the others. location ~ config\.js { alias xyz; expires off; } location static etc
location /static { alias /home/ubuntu/Documents/zibann/momsite/momsite/static; # your Django project's static files - amend as required if ($uri ~* ".*config.js") { expires off; } if ($uri ~* ".*\.(js|css|png|jpg|jpeg|gif|swf|svg)" ) { access_log off; expires 365d; add_header Cache-Control public; } } Hoping config.js would not get cached, but it does. How can I exclude one file from being cached?
Nginx, turn off cache for a specific file
As you're dealing with image caching, filectime is inappropriate - it marks the last time: when the permissions, owner, group, or other metadata from the inode is updated source: php.net You want to know if the image file content has changed - if it's been resized, cropped or replaced entirely. Therefore, filemtime is more suitable for your application: when the data blocks of a file were being written to, that is, the time when the content of the file was changed source: php.net If you don't want the ? to always appear, set filemtime to a variable first and test for it: $filemtime = @filemtime("/images/123.png"); <img src="/images/123.png<?= $filemtime ? '?' . $filemtime : ''?>" /> Better still, test for the existence of the file with file_exists() before using filemtime.
I'm trying to ensure some images aren't cached when they're modified but which would be more suitable for this filectime or filemtime? I can't really see much difference from the php manuals? Would either be faster? <img src="/images/123.png?<?=md5(@filectime("/images/123.png"))?>" /> <img src="/images/123.png?<?=md5(@filemtime("/images/123.png"))?>" /> Also is there a function like this that doesn't emit an e_warning on file error? Ideally I don't want to ever serve just the question mark <img src="/images/123.png?" />
filectime vs filemtime for file modification time?
System.Web.Caching.Cache is a class - you see people using a property named Cache that is an instance of System.Web.Caching.Cache. If you're using it outside of a class that provides you with the Cache property, access it using System.Web.HttpRuntime.Cache: var settings = System.Web.HttpRuntime.Cache[cacheKey] as Dictionary<string, bool>;
I have a class that looks like this: using System.Collections.Generic; using System.Web.Caching; public static class MyCache { private static string cacheKey = "mykey"; public static Dictionary<string, bool> GetCacheValue(bool bypassCache) { var settings = Cache[cacheKey] as Dictionary<string, bool>; // error on this line // ...etc... return settings } } the problem I'm having is that this wont compile. The compiler says Cache can't be used the way I'm doing it. Here's the message: 'System.Web.Caching.Cache' is a 'type' but is used like a 'variable' This perplexes me. I've googled the ASP.NET Cache API and have found many examples of Cache being used this way. Here's one of those examples: // http://www.4guysfromrolla.com/articles/100902-1.aspx value = Cache("key") - or - value = Cache.Get("key") When I try using Cache.Get() I get another error saying that it's not a static method. Evidently I need to initialize an instance of Cache. Is this the correct way to use this API? A follow-up question is, does cached information persist across instances? Thanks for your help.
How to use System.Web.Caching in asp.net?
On Windows, you can use VirtualProtect(ptr, length, PAGE_NOCACHE, &oldFlags) to set the caching behavior for memory to avoid caching. Regarding too many indirections: Yes, they can damage cache performance, if you access different pieces of memory very often (which is what happens usually). It's important to note, though, that if you consistently dereference the same set of e.g. 8 blocks of memory, and only the 9th block differs, then it generally won't make a difference, because the 8 blocks would be cached after the first access.
I was reading the wikipedia on the CPU cache here: http://en.wikipedia.org/wiki/CPU_cache#Replacement_Policies Marking some memory ranges as non-cacheable can improve performance, by avoiding caching of memory regions that are rarely re-accessed. This avoids the overhead of loading something into the cache, without having any reuse. Now, I've been reading and learning about how to write programs with better cache performance (general considerations, usually not specific to C++), but I did not know that high-level code can interact with CPU caching behavior explicitly. So my question, is there a way to do what I quoted from that article, in C++? Also, I would appreciate resources on how to improve cache performance specifically in C++, even if they do not use any functions that deal directly with the CPU caches. For example, I'm wondering if using excessive levels of indirection (eg., a container of pointers to containers of pointers) can damage cache performance.
How to mark some memory ranges as non-cacheable from C++?
http://moprea.ro/2011/may/6/magento-performance-optimization-varnish-cache-3/ describes the Magento extension that enables full page cache with varnish. This extension relies on Varnish config published on github. These are the features already implemented: Workable varnish config Enable full page caching using Varnish, a super fast caching HTTP reverse proxy. Varnish servers are configurable in Admin, under System / Configuration / General - Varnish Options Automatically clears (only) cached pages when products, categories and CMS pages are saved. Adds a new cache type in Magento Admin, under System / Cache Management and offers the possibility to deactivate the cache and refresh the cache. Notifies Admin users when a category navigation is saved and Varnish cache needs to be refreshed so that the menu will be updated for all pages. Turns off varnish cache automatically for users that have products in the cart or are logged in, etc.) Default varnish configuration offered so that the module is workable. Screen shots: https://github.com/madalinoprea/magneto-varnish/wiki
First please forgive me for total lack of understanding of Varnish. This is my first go at doing anything with Varnish. I am following the example at: http://www.kalenyuk.com.ua/magento-performance-optimization-with-varnish-cache-47.html However when I install and run this, Varnish does not seem to cache. I do get the X-Varnish header with a single number and a Via header that has a value of 1.1 varnish I have been told (by my ISP) it is because of the following cookie that Magento sets: Set-Cookie: frontend=6t2d2q73rv9s1kddu8ehh8hvl6; expires=Thu, 17-Feb-2011 14:29:19 GMT; path=/; domain=XX.X.XX.XX; httponly They said that I either have to change Magento to handle this or configure Varnish to handle this. Since changing Magento is out of the question, I was wondering if someone can give me a clue as to how I would configure Varnish to handle this cookie?
Getting Varnish To Work on Magento
NSURLCache is broken on iOS 8.0.x - it never purges the cache at all, so it grows without limit. See http://blog.airsource.co.uk/2014/10/11/nsurlcache-ios8-broken/ for a detailed investigation. Cache purging is fixed in the 8.1 betas - but removeCachedResponseForRequest: is not. removeCachedResponsesSinceDate: does appear to work on iOS 8.0 - an API that was added for 8.0, but hasn't made it to the docs yet (it is in the API diffs). I am unclear what use it is to anyone - surely what you normally want to do is remove cached responses before a particular date. removeAllCachedResponses works as well - but that's a real sledgehammer solution.
Here is the sample function I call when i need to clear cache and make a new call to URL - (void)clearDataFromNSURLCache:(NSString *)urlString { NSURL *requestUrl = [NSURL URLWithString:urlString]; NSURLRequest *dataUrlRequest = [NSURLRequest requestWithURL: requestUrl]; NSURLCache * cache =[NSURLCache sharedURLCache]; NSCachedURLResponse* cacheResponse =[cache cachedResponseForRequest:dataUrlRequest]; if (cacheResponse) { NSString* dataStr = [NSString stringWithUTF8String:[[cacheResponse data] bytes]]; NSLog(@"data str r= %@",dataStr); NSLog(@"url str r= %@",[[[cacheResponse response] URL] absoluteString]); [cache storeCachedResponse:nil forRequest:dataUrlRequest]; [NSURLCache setSharedURLCache:cache]; } [[NSURLCache sharedURLCache] removeCachedResponseForRequest:dataUrlRequest]; //Check if the response data has been removed/deleted from cache NSURLRequest *finalRequestUrlRequest = [NSURLRequest requestWithURL:requestUrl]; NSURLCache * finalCache =[NSURLCache sharedURLCache]; NSCachedURLResponse* finalcacheResponse =[finalCache cachedResponseForRequest:finalRequestUrlRequest]; if (finalcacheResponse) { //Should not enter here NSString* finaldataStr = [NSString stringWithUTF8String:[[finalcacheResponse data] bytes]]; NSLog(@"data str r= %@",finaldataStr); NSLog(@"url str r= %@",[[[cacheResponse response] URL] absoluteString]); } } In iOS 6/7 the response is deleted successfully for the requestURL, but in iOS 8 it never gets deleted. I have searched but could not find any reason why this should not work in iOS8. Any help will be appreciated…..
NSURLCache does not clear stored responses in iOS8
Request context Any request that hits a web farm gets served by an available IIS server. Context gets created there and the whole request gets served by the same server. So context shouldn't be a problem. A request is a stateless execution pipeline so it doesn't need to share data with other servers in any way shape or form. It will be served from the beginning to the end by the same machine. User information is read from a cookie and processed by the server that serves the request. It depends then if you cache complete user object somewhere. Session If you use TempData dictionary you should be aware that it's stored inside Session dictionary. In a server farm that means you should use other means than InProc sessions, because they're not shared between IIS servers across the farm. You should configure other session managers that either use a DB or others (State server etc.). Cache When it comes to cache it's a different story. To make it as efficient as possible cache should as well be served. By default it's not. But looking at cache it barely means that when there's no cache it should be read and stored in cache. So if a particular server farm server doesn't have some cache object it would create it. In time all of them would cache some shared publicly used data. Or... You could use libraries like memcached (as you mentioned it) and take advantage of shared cache. There are several examples on the net how to use it. But these solutions all bring additional overhead of several things (like network and third process processing and data fetching etc.) if nothing else. So default cache is the fastest and if you explicitly need shared cache then decide for one. Don't share cache unless really necessary.
What will be the most efficient way to make an ASP.NET MVC application web-farm ready. Most importantly sharing the current user's information (Context) and (not so important) cached objects such as look-up items (States, Street Types, counties etc.). I have heard of/read MemCache but haven't seen a simple applicable way (documentation) on how to implement and test it.
Make an ASP.NET MVC application Web Farm Ready
It's safe generally, The cache in /System/Library/Caches is useful for system but the cache in ~/Library/Caches are not that useful. Deleting everything at once is not recommended. But if you want to delete specific file remove it manually
Hi I notice that I have large folders <1Gb from AndroidStudio on Libraries/Cache OSX 10.9 The folders are: AndroidStudio AndroidStudio1.3 AndroidStudioBeta AndroidStudioPreview1.3 AndroidStudioPreview1.4 I'm using AndroidStudio 1.4 beta 4 currently Can I safe delete some of these cache folders? Do you know what would be the proper manner to do it?
Remove old AndroidStudio Cache folders - OSX
I did this by overriding Request#addMarker and checking for a "cache-hit" marker being added: public class MyRequest<T> extends Request<T> { protected boolean cacheHit; @Override public void addMarker(String tag) { super.addMarker(tag); cacheHit = false; if (tag.equals("cache-hit")){ cacheHit = true; } } }
How can I check whether Volley gets the results of a JsonObjectRequest from the cache or from the network? I need to show a progress dialog when it needs a network connection but not when the results are quickly received from the cache. my request looks something like this volleyQueue = Volley.newRequestQueue(this); JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>(){...stuff}, new Response.ErrorListener(){...errorstuff}); jr.setShouldCache(true); volleyQueue.add(jr);
Check if Volley gets results from cache or over network
Well a lot of operations in Python are thread-safe by default, so a standard dictionary should be ok (at least in certain respects). This is mostly due to the GIL, which will help avoid some of the more serious threading issues. There's a list here: http://coreygoldberg.blogspot.com/2008/09/python-thread-synchronization-and.html that might be useful. Though atomic nature of those operation just means that you won't have an entirely inconsistent state if you have two threads accessing a dictionary at the same time. So you wouldn't have a corrupted value. However you would (as with most multi-threading programming) not be able to rely on the specific order of those atomic operations. So to cut a long story short... If you have fairly simple requirements and aren't to bothered about the ordering of what get written into the cache then you can use a dictionary and know that you'll always get a consistent/not-corrupted value (it just might be out of date). If you want to ensure that things are a bit more consistent with regard to reading and writing then you might want to look at Django's local memory cache: http://code.djangoproject.com/browser/django/trunk/django/core/cache/backends/locmem.py Which uses a read/write lock for locking.
I have implemented a python webserver. Each http request spawns a new thread. I have a requirement of caching objects in memory and since its a webserver, I want the cache to be thread safe. Is there a standard implementatin of a thread safe object cache in python? I found the following http://freshmeat.net/projects/lrucache/ This does not look to be thread safe. Can anybody point me to a good implementation of thread safe cache in python? Thanks!
python threadsafe object cache
12 You can use html-webpack-plugin plugins: [ new HtmlWebpackPlugin({ hash: true }) ] hash: true | false if true then append a unique webpack compilation hash to all included scripts and css files. This is useful for cache busting. Share Improve this answer Follow answered Apr 7, 2016 at 16:07 JackJack 8,90133 gold badges2121 silver badges2727 bronze badges 5 Thank you for quick reply. I am getting following error Failed to load resource: the server responded with a status of 404 (Not found) for file bundle.js?1c03629db68f03ac936e & similar error is coming for styles.css?1c03629db68f03ac936e file. I installed the npm package and simple added the code shown by you in webapck config file. after building and deploying I am getting error. when I run the application locally I get following error ncaught Invariant Violation: _registerComponent(...): Target container is not a DOM element. – OpenStack Apr 7, 2016 at 17:08 Make sure the html file generated from HtmlWebpackPlugin is referencing the files correctly. I don't know how you're project is set up so it might think your distribution directory structure is different than it is. – Jack Apr 7, 2016 at 18:12 I think the problem is, the query string is not in correct format. instead of key value pair, the file is just value. by that I mean instead of bundle.js?v=1c03629db68f03ac936e its coming as bundle.js?1c03629db68f03ac936e. the key is missing. Did I miss a configuration option. – OpenStack Apr 7, 2016 at 21:25 this work with 'webpack' or need 'webpack-dev-server' ? – stackdave Aug 8, 2017 at 19:56 @stackdave I think it should work with just webpack, it would do the hashing during the build process. – Jack Aug 10, 2017 at 14:14 Add a comment  | 
I am working on a web application developed using reactjs and webpack. After every deployment, we have to ask users to clear the browser cache and restart their browsers. I think the javascript bundle file and css file both are getting cached on user browser. How can we force browser not to cache these files or make it download the latest files from the server. <html> <head> <meta charset="utf-8"> <title>My App</title> <link rel="stylesheet" href="styles.css" media="screen" charset="utf-8"> </head> <body> <div id="app"></div> <script src="bundle.js"></script> </body> </html>
caching issue with web application developed using reactjs & webpack
Your understanding of the the array case is mostly correct. If an array is accessed sequentially, many processors will not only fetch the block containing the element, but will also prefetch subsequent blocks to minimize cycles spent waiting on cache misses. If you are using an Intel x86 processor, you can find details about this in the Intel x86 optimization manual. Also, if the array elements are small enough, loading a block containing an element means the next element is likely in the same block. Unfortunately, for linked lists the pattern of loads is unpredictable from the processor's point of view. It doesn't know that when loading an element at address X that the next address is the contents of (X + 8). As a concrete example, the sequence of load addresses for a sequential array access is nice and predictable. For example, 1000, 1016, 1032, 1064, etc. For a linked list it will look like: 1000, 3048, 5040, 7888, etc. Very hard to predict the next address.
Say we have an unsorted array and linked list. The worst case when searching for an element for both data structures would be O( n ), but my question is: Would the array still be way faster because of the use of spatial locality within the cache, or will the cache make use of branch locality allowing linked lists to be just as fast as any array ? My understanding for an array is that if an element is accessed, that block of memory and many of the surrounding blocks are then brought into the cache allowing for much faster memory accesses. My understanding for a linked list is that since the path that will be taken to traverse the list is predictable, then the cache will exploit that and still store the appropriate blocks of memory even though the nodes of the list can be far apart within the heap.
Arrays vs Linked Lists in terms of locality
The cache does just that, it caches whatever you put into it. If you cache a reference type, retrieve the reference and modify it, of course the next time you retrieve the cached item it will reflect the modifications. If you wish to have an immutable cached item, use a struct. Cache.Insert("class", new MyClass() { Title = "original" }, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration); MyClass cachedClass = (MyClass)Cache.Get("class"); cachedClass.Title = "new"; MyClass cachedClass2 = (MyClass)Cache.Get("class"); Debug.Assert(cachedClass2.Title == "new"); Cache.Insert("struct", new MyStruct { Title = "original" }, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration); MyStruct cachedStruct = (MyStruct)Cache.Get("struct"); cachedStruct.Title = "new"; MyStruct cachedStruct2 = (MyStruct)Cache.Get("struct"); Debug.Assert(cachedStruct2.Title != "new");
I'm having an issue when using the Asp.Net Cache functionality. I add an object to the Cache then at another time I get that object from the Cache, modify one of it's properties then save the changes to the database. But, the next time I get the object from Cache it contains the changed values. So, when I modify the object it modifies the version which is contained in cache even though I haven't updated it in the Cache specifically. Does anyone know how I can get an object from the Cache which doesn't reference the cached version? i.e. Step 1: Item item = new Item(); item.Title = "Test"; Cache.Insert("Test", item, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration); Step 2: Item item = (Item)Cache.Get("test"); item.Title = "Test 1"; Step 3: Item item = (Item)Cache.Get("test"); if(item.Title == "Test 1"){ Response.Write("Object has been changed in the Cache."); } I realise that with the above example it would make sense that any changes to the item get reflected in cache but my situation is a bit more complicated and I definitely don't want this to happen.
Asp.Net Cache, modify an object from cache and it changes the cached value
Looking at IPython/core/displayhook.py Line 209-214 I would say that it is not configurable. You could try making a PR to add an option to disable it totally.
I'm dealing with some GB-sized numpy arrays in IPython. When I delete them, I definitely want them gone, in order to recover the memory. IPythons output cache is quite annoying there, as it keeps the objects alive even after deleting the last actively intended reference to them. I already set c.TerminalInteractiveShell.cache_size = 0 in the IPython configuration, but this only disables caching of entries to _oh, the other variables like _, __ and so on are still created. I'm also aware of %xdel, but anyways, I'd prefer to disable it completely, as I rarely use the output history anyways, so that a plain del would work again right away.
Completely disable IPython output caching
You can point api.yourdomain.com to cloudfront domain. Cloudfront will cache the json response based on your cache control headers. However, you'll likely have to deal with cross domain issue if your single page app is not served from api.yourdomain.com. Cloudfront supports OPTIONS request which means it should be able to support CORS. You can also enable caching of OPTIONS requests. http://aws.amazon.com/cloudfront/faqs/#Does_Amazon_CloudFront_cache_POST_responses
I have a Single Page Application, and would like to cache some of the public REST API calls. Is it possible to use CloudFront to cache the JSON result of those API calls?
Is it possible for CloudFront to cache REST API calls
13 +150 They simply fill the free space on iPhone temporarily with random data leaving the system with no free space at all. This forces iOS to clear all temp data, caches and iCloud Photos -if you enabled storage optimization- to clear space. So basically they are tricking the system to force it to clear temp and cached data. Share Improve this answer Follow answered Aug 21, 2017 at 15:12 Moaz AhmedMoaz Ahmed 45122 silver badges88 bronze badges 2 I already said, "I am not looking for reference". Can you show me how? Do you have an example? Then, please share. – Sohil R. Memon Aug 21, 2017 at 16:41 P.S. - What you have said is already been answered on SO. Can I know how they are tricking? – Sohil R. Memon Aug 21, 2017 at 16:42 Add a comment  | 
Recently, I have came across many apps which "Clear Cache" on iPhone. They also specify that you may lose some saved data and temp files. What I know is that Apple doesn't allows you to access data of other Apps neither directory. So, how they are cleaning cache data? Can anyone put some light on it? Reference: Magic Phone Cleaner Power Clean
Clear Cache in iOS: Deleting Application Data of Other Apps
There are 2 questions in one: 1/ How to preload tiles ? Tiles are images. You just have to create a reference to these images. Look at JavaScript Preloading Images 2/ What tiles must you load when you know the boundaries ? Take a look at https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames I cooked an example here that should be helpful. It's preloading tiles from the next zoom level when you move the map: https://yafred.github.io/leaflet-tests/20170311-preloading-tiles/ It first calculates which tiles you need for each corner of your boundaries with following code: function long2tile(lon,zoom) { return (Math.floor((lon+180)/360*Math.pow(2,zoom))); } function lat2tile(lat,zoom) { return (Math.floor((1-Math.log(Math.tan(lat*Math.PI/180) + 1/Math.cos(lat*Math.PI/180))/Math.PI)/2 *Math.pow(2,zoom))); } then, it calculates which tiles are inside the boundaries.
I'm developing a web application which displays animated markers on a Leaflet map. The map is programmatically zoomed to the first animation bounds, then the animation is played, then the map is zoomed to the second animation bounds and the second animation is played, and so on... My problem is that the OpenStreetMap tiles loading time sometimes exceeds the animation duration so the map is partially loaded or even not loaded when the marker animation reaches its end. As i know from the beginning all the bounds i'm going to zoom on, i would like to make ajax calls to download all useful tiles images in advance (before any animation starts) to be sure they are in the browser cache when i need them. I have searched a lot and i don't find a way to get a list of tiles URLs from Leaflet bounds. Is there a way to manually load tiles in browser cache for known bounds and zoom level ? SOLUTION thanks to YaFred answer : Here is the code to preload tiles around "mypolyline" with 20% padding : var bounds = mypolyline.getBounds().pad(0.2); var zoom = map.getBoundsZoom(bounds); var east = bounds.getEast(); var west = bounds.getWest(); var north = bounds.getNorth(); var south = bounds.getSouth(); var dataEast = long2tile(east, zoom); var dataWest = long2tile(west, zoom); var dataNorth = lat2tile(north, zoom); var dataSouth = lat2tile(south, zoom); for(var y = dataNorth; y < dataSouth + 1; y++) { for(var x = dataWest; x < dataEast + 1; x++) { var url = 'https://a.tile.openstreetmap.fr/osmfr/' + zoom + '/' + x + '/' + y + '.png'; var img=new Image(); img.src=url; } } It combines his two answers. When an animation is running, I'm now able to preload tiles for the next to come. It works fantastically.
How to preload Leaflet tiles of known bounds in browser cache for faster display?
No; I do not believe that it is; if you want it cached, you must hold onto the Delegate reference (typically Func<...> or Action<...>). Likewise, if you want to get the best performance, you would compile it as a parameterised expression, so you can send in different values when you invoke it. In this case, re-phrasing would help: public MyResultType DoSomething(int arg1, int arg2) { var result = invokeHandler( (IDoSomethingHandler h, int a1, int a2) => h.DoSomething(a1, a2), arg1, arg2); return result; } private TResult invokeHandler<T, TResult>(Expression<Func<T,int,int,TResult>> action, int arg1, int arg2) where T : class { // Here, I might want to check to see if action is already cached. var compiledAction = action.Compile(); var methodCallExpr = action as MethodCallExpression; // Here, I might want to store methodCallExpr in a cache somewhere. var handler = ServiceLocator.Current.GetInstance<T>(); var result = compiledAction(handler, arg1, arg2); return result; } i.e. make the numbers parameters of the expression, and pass the actual ones it at runtime (rather than being constants in the expression).
When an Expression<T> is compiled, is the resultant code implicitly cached by the framework? I'm thinking along the lines of the static Regex methods where the framework implicitly compiles and caches the last few regexes. If compiled Expression<T> objects are not cached, can you recommend some best practices for keeping the compile-time down or any gotchas that could cause problems if I manually cache an expression? public MyResultType DoSomething(int arg1, int arg2) { var result = invokeHandler( (IDoSomethingHandler h) => h.DoSomething(arg1, arg2) ); return result; } private TResult invokeHandler<T, TResult>(Expression<Func<T, TResult>> action) where T : class { // Here, I might want to check to see if action is already cached. var compiledAction = action.Compile(); var methodCallExpr = action as MethodCallExpression; // Here, I might want to store methodCallExpr in a cache somewhere. var handler = ServiceLocator.Current.GetInstance<T>(); var result = compiledAction(handler); return result; } In this example, I'm slightly concerned that if I cache the compiled expression, that it will use the values of arg1 and arg2 as they were at the time the expression was compiled, rather than retrieving those values from the appropriate place in the stack (i.e. rather than getting the current values).
When an Expression<T> is compiled, is it implicitly cached?
I used getBitmap() in the sample someone posted here. This is the answer you're looking for under a different title. You will have to create a Utils for some of the code but it's pretty straightforward. Good Luck! Using DiskLruCache in android 4.0 does not provide for openCache method
I want to use the DiskLruCache from Jake Wharton in my Android app based on API Level 7+. I would use it in my ListView to Cache downloaded images on SdCard but i didn't understood the usage of this library. Can anybody show me a example of how to get Bitmaps from this Cache or put Bitmaps in the cache? ( key = filePath, value = Bitmap ) I found no method to get the Value of this Snapshot Object. Thanks for every help.
Example of JakeWhartons DiskLruCache
5 Yeah, as Marecky have already mentioned, there is a ticket for that. Also, there is another one here https://jira.atlassian.com/browse/BCLOUD-17605, which should exactly address the issue. In short, there is an API to invalidate the cache, but it's currently reserved for internal use only. Share Improve this answer Follow edited Sep 13, 2019 at 8:53 answered Sep 12, 2019 at 13:58 Alexander ZhukovAlexander Zhukov 4,44711 gold badge2020 silver badges3232 bronze badges Add a comment  | 
I have a node_modules cache in my Bibucket Pipeline and I added new module (eg yarn add react-modal) - how to make Bitbucket pipelines detect new yarn.lock and invalidate its cache?
How to programmatically invalidate Bitbucket Pipeline's cache?
8 I am using Ehcache and i had the same issue because i had two different names for cache and Cacheable. Please make you use same name for cache and Cacheable. @Cacheable("codetable") <cache name="codetable" maxEntriesLocalHeap="100" maxEntriesLocalDisk="1000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" transactionalMode="off"> <persistence strategy="localTempSwap" /> </cache> Share Improve this answer Follow edited Nov 24, 2023 at 19:41 Toni 4,56233 gold badges1515 silver badges4646 bronze badges answered Sep 26, 2017 at 14:22 BibhutiBibhuti 13122 silver badges33 bronze badges Add a comment  | 
According to link, the simplest configuration to use cache in spring boot is using CacheManager (an cache Map would be initialized in this class): @Configuration @EnableCaching public class CacheService extends CachingConfigurerSupport { @Bean public CacheManager concurrentMapCacheManager() { ConcurrentMapCacheManager cmcm = new ConcurrentMapCacheManager(); return cmcm; } @Bean @Primary public CacheManager guavaCacheManager() { GuavaCacheManager gcm = new GuavaCacheManager(); return gcm; } } and in serviceImpl.java: @Cacheable(cacheManager="guavaCacheManager") @Override public List<RoleVO> getDataForCreateNewOperator() { ... } But it throws: java.lang.IllegalStateException: No cache could be resolved for 'Builder[public java.util.List getDataForCreateNewOperator()] caches=[] | key='' | keyGenerator='' | cacheManager='guavaCacheManager' | cacheResolver='' | condition='' | unless='' | sync='false'' using resolver 'org.springframework.cache.interceptor.SimpleCacheResolver@38466d10'. At least one cache should be provided per cache operation. EDIT: if I assign a cacheName in cacheManager, and use it in the advised method, the exception is gone. But all methods in the bean would be cached, while I only assigned @Cacheable on one method.
Spring boot cache No cache could be resolved for Builder
7 I'm using version 4.2.1 and even with autowarmCount="0" the cache is not updated after doing a Dataimport. In that case, on Solr Admin (usually http://localhost:8983/) Go to Core Admin and click Reload. When refreshed, you should see a green check mark on the "current" field. Share Improve this answer Follow answered May 15, 2013 at 14:10 bubbassaurobubbassauro 4,10122 gold badges4646 silver badges4747 bronze badges Add a comment  | 
I'm trying to compare the performance of different Solr queries. In order to get a fair test, I want to clear the cache between queries. How is this done? Of course, one can restart the server, I was curious if there is a quicker way.
How to clear the cache in Solr?
9 The maximumSize() method refers to the (approximate) maximum number of entries in the cache. It makes no guarantees about how much memory the cache's contents will consume (and as Louis points out, there's no reasonable way for any Java object to do so). If you have a way of measuring the relative "cost" of caching a particular object you can specify a maximumWeight() instead. For example, if you were caching byte[] instances you could use their length as the weight and this would roughly reflect their memory footprint. For other types you'd need to determine an appropriate proxy notion of "cost". Share Improve this answer Follow answered Nov 22, 2017 at 9:31 dimo414dimo414 47.9k1919 gold badges159159 silver badges249249 bronze badges Add a comment  | 
I'm trying to figure out what the number that you specify in Guava CacheBuilder maximumSize() represent. Say I've got something like this in my code, Cache<String, Object> programCache = CacheBuilder.newBuilder() .maximumSize(1000) .build(); Does the 1000 that I specified as the max size mean that I can have a thousand different entries in the cache before it starts kicking out the LRU (no matter what size the object might be)? If this is the case, is there a limit to the size of the object? Or does that 1000 mean, that I have a 1000mb(is MB correct?) to work with and I can have as many of the Objects in the cache as I want up to 1000mb before it starts kicking out the LRU?
Guava CacheBuilder maximumSize
TouchInterceptor.java - This is class responsible for reordering your playlist in the default music player. It uses setDrawingCacheEnabled when you start dragging the current view. Basically, it creates a bitmap from the ListView item and drag it. Take a closer look at onInterceptTouchEvent method.
I am reading about setDrawingCacheEnabled and getDrawingCache and I was wondering when is it good to use it or when its not good. Basically in my case I have an HorizontalScrollView with many things inside it so its scrolls left/right and most of the things are not visible. If I use setDrawingCacheEnabled(true) on the views, does it help? or this is only when I use custom views and I call getDrawingCache()? Is there any other 'cache' way to use in a HorizontalScrollView?
Android - drawing cache - when is it useful?
8 The problem is, that selenium copies every startup a new (firefox/chrome) profile to the temp directory and starts firefox/chrome with it. However, it is possible to always use the same profile for your test instances. I think this way you can get it working faster. For firefox you just need to do these steps: 1. Load your webapp in a selenium firefox instance and don't close it afterwards (not driver.close();). 2. Then go to Help->Troubleshooting Information and open the folder under Profile folder. 3. Copy its content to a new folder near your test code. 4. Load the saved Profile in your test code. You can do it this way: FirefoxProfile profile = new FirefoxProfile(new File("profile/folder/path")); WebDriver driver = new FirefoxDriver(profile); I think you can do this in chrome analogous. Share Improve this answer Follow edited Jun 18, 2014 at 12:48 answered Jun 17, 2014 at 16:26 ThorbenThorben 9651313 silver badges3030 bronze badges 1 1 do you know how to do it with github.com/facebook/php-webdriver? – gouchaoer Jul 28, 2016 at 8:58 Add a comment  | 
Currently our web application takes around 3 mins to load completely without caching and 10 secs with caching. When I open the app through WebDriver its taking around 3 mins to load i.e. caching is not used. I observed this on Firefox and Chrome browser. Not sure how to enabled the driver to use cache instead of loading each file from server every time I open the app. Here are the things I tried. 1. disabled clearing cache on browser exit in browser setting. 2. set 'applicationCacheEnabled' desiredcapabilitiy to 'true' DesiredCapabilities cap = DesiredCapabilities.firefox(); cap.setCapability("applicationCacheEnabled", "true"); WebDriver d = new FirefoxDriver(cap) But nothing seems to work. Please let me know how can I make webdriver to use caching.
retaining cache in firefox and chrome browser - Selenium WebDriver
If all you want to do is output the file contents, you should be using readfile(). This is faster and less memory intensive than file_get_contents()
have a file caching system for a php 5 library i use often. when the request is made i check for a cached file, if there is one i render it and exit. $contents = file_get_contents( self::_cacheFile() ); echo $contents; exit(); i have to do file_get_contents instead of just include because of cached xml files with the pesky `<?xml version="1.0"?>` is there a better way to pull in my cache files without shorttags firing?
how to read a cached xml file?
if you are trying to load an image through Json(from db) try clearing the networkCache for a better result. Picasso.with(context).load(uri).networkPolicy(NetworkPolicy.NO_CACHE) .memoryPolicy(MemoryPolicy.NO_CACHE) .placeholder(R.drawable.bv_logo_default).stableKey(id) .into(viewImage_imageView);
I'm trying to clear the cache memory of Picasso via Android coding. Can anyone please help me in this issue..? I have tried using the following code, but this was not useful in my case: Picasso.with(getActivity()).load(data.get(pos).getFeed_thumb_image()).skipMemoryCache().into(image);
Clear Cache memory of Picasso
I guess when you disable caching it will also stop writing to the cache. So when you re-enable the cache the old cached copy will still be there and valid. You could try (with caching enabled) ini_set('soap.wsdl_cache_ttl', 1); I put in a time-to-live of one second in because I think if you put zero in it will disable the cache entirely but not remove the entry. You probably will only want to put that line in when you want to kill the cached copy.
I know how to disable WSDL-cache in PHP, but what about force a re-caching of the WSDL? This is what i tried: I run my code with caching set to disabled, and the new methods showed up as espected. Then I activated caching, but of some reason my old non-working wsdl showed up again. So: how can I force my new WSDL to overwrite my old cache?
Force re-cache of WSDL in php
The best solution seems to be to version filenames by appending the last-modified time. You can do it this way: add a rewrite rule to your Apache configuration, like so: RewriteRule ^(.+)\.(.+)\.(js|css|jpg|png|gif)$ $1.$3 This will redirect any "versioned" URL to the "normal" one. The idea is to keep your filenames the same, but to benefit from cache. The solution to append a parameter to the URL will not be optimal with some proxies that don't cache URLs with parameters. Then, instead of writing: <img src="image.png" /> Just call a PHP function: <img src="<?php versionFile('image.png'); ?>" /> With versionFile() looking like this: function versionFile($file){ $path = pathinfo($file); $ver = '.'.filemtime($_SERVER['DOCUMENT_ROOT'].$file).'.'; echo $path['dirname'].'/'.str_replace('.', $ver, $path['basename']); } And that's it! The browser will ask for image.123456789.png, Apache will redirect this to image.png, so you will benefit from cache in all cases and won't have any out-of-date issue, while not having to bother with filename versioning. You can see a detailed explanation of this technique here: http://particletree.com/notebook/automatically-version-your-css-and-javascript-files/
If I understand correctly, a broswer caches images, JS files, etc. based on the file name. So there's a danger that if one such file is updated (on the server), the browser will use the cached copy instead. A workaround for this problem is to rename all files (as part of the build), such that the file name includes an MD5 hash of it's contents, e.g. foo.js -> foo_AS577688BC87654.js me.png -> me_32126A88BC3456BB.png However, in addition to renaming the files themselves, all references to these files must be changed. For exmaple a tag such as <img src="me.png"/> should be changed to <img src="me_32126A88BC3456BB.png"/>. Obviously this can get pretty complicated, particularly when you consider that references to these files may be dynamically created within server-side code. Of course, one solution is to completely disable caching on the browser (and any caches between the server and the browser) using HTTP headers. However, having no caching will create it's own set of problems. Is there a better solution? Thanks, Don
client-side file caching
Django has a SimpleLazyObject. In Django 1.3, this is used by the auth context processor (source code). This makes user available in the template context for every query, but the user is only accessed when the template contains {{ user }}. You should be able to do something similar in your context processor. from django.utils.functional import SimpleLazyObject def my_context_processor(request): def complicated_query(): do_stuff() return result return { 'result': SimpleLazyObject(complicated_query)
In each view of my application I need to have navigation menu prepared. So right now in every view I execute complicated query and store the menu in a dictionary which is passed to a template. In templates the variable in which I have the data is surrounded with "cache", so even though the queries are quite costly, it doesn't bother me. But I don't want to repeat myself in every view. I guessed that the best place to prepare the menu is in my own context processor. And so I did write one, but I noticed that even when I don't use the data from the context processor, the queries used to prepare the menu are executed. Is there a way to "lazy load" such data from CP or do I have to use "low level" cache in CP? Or maybe there's a better solution to my problem?
"Lazy load" of data from a context processor
You can stuff the actually cached values in the Rails cache (use memcached if you require that it be distributed). The tough bit is cache expiry, but cache expiry is uncommon, right? In that case, we can just loop over each of the parent objects in turn and zap its cache, too. I added some ActiveRecord magic to your class to make getting the parent objects simplicity itself -- and you don't even need to touch your database. Remember to call Part.sweep_complicated_cache(some_part) as appropriate in your code -- you can put this in callbacks, etc, but I can't add it for you because I don't understand when complicated_calculation is changing. class Part < ActiveRecord::Base has_many :sub_parts, :class_name => "Part" belongs_to :parent_part, :class_name => "Part", :foreign_key => :part_id @@MAX_PART_NESTING = 25 #pick any sanity-saving value def complicated_calculation (...) if cache.contains? [id, :complicated_calculation] cache[ [id, :complicated_calculation] ] else cache[ [id, :complicated_calculation] ] = complicated_calculation_helper (...) end end def complicated_calculation_helper #your implementation goes here end def Part.sweep_complicated_cache(start_part) level = 1 # keep track to prevent infinite loop in event there is a cycle in parts current_part = self cache[ [current_part.id, :complicated_calculation] ].delete while ( (level <= 1 < @@MAX_PART_NESTING) && (current_part.parent_part)) { current_part = current_part.parent_part) cache[ [current_part.id, :complicated_calculation] ].delete end end end
I have a tree of active record objects, something like: class Part < ActiveRecord::Base has_many :sub_parts, :class_name => "Part" def complicated_calculation if sub_parts.size > 0 return self.sub_parts.inject(0){ |sum, current| sum + current.complicated_calculation } else sleep(1) return rand(10000) end end end It is too costly to recalculate the complicated_calculation each time. So, I need a way to cache the value. However, if any part is changed, it needs to invalidate its cache and the cache of its parent, and grandparent, etc. As a rough draft, I created a column to hold the cached calculation in the "parts" table, but this smells a little rotten. It seems like there should be a cleaner way to cache the calculated values without stuffing them along side the "real" columns.
How can I cache a calculated column in rails?
after some more digging I finally found the solution. It's a bit hinted in the url_for method: In particular, a leading slash ensures no namespace is assumed. Thus, while url_for :controller => 'users' may resolve to Admin::UsersController if the current controller lives under that module, url_for :controller => '/users' ensures you link to ::UsersController no matter what. So basically, expire_action(:controller => '/newsposts', :action => 'index') Will expire in the default namespace, and expire_action(:controller => 'admin/newsposts', :action => 'index') in the admin namespace (when in default). RailsCast
My application is using a namespace for administrative purposes. I recently tried to start using action caching however I ran into some problems trying to expire the cache using expire_action. Basically I have a index action in my default namespace newsposts controller that is cached using action caching like this: class NewspostsController < ApplicationController caches_action :index, :layout => false def index @posts = Newspost.includes(:author).order("created_at DESC").limit(5) end end This caches the view under views/host/newsposts. The default namespace has no actions for modifying data, they are all in my admin namespace. In my Admin::NewspostsController I am trying to expire this cache in the create action like this: expire_action(:controller => 'newsposts', :action => 'index') however this will expire a cache file located under views/host/admin/newsposts. Obviously it can not work since im in the admin namespace and rails is (rightfully) looking to expire cache for this namespace. Sadly I can not pass a namespace parameter to the axpire_action method, so how can i expire the action cache in another namespace?
rails caching: expire_action in another namespace
display: none images will be downloaded and cached on the client. However, JavaScript already has a well-defined way of preloading images: var nextImage = new Image(); nextImage.src = "your-url/newImage.gif"; This will preload an image without displaying it to the user.
I'm trying to figure out a way to cache the next and previous images in my gallery script ... I'm wondering if this is a good way to do it. Also, is there any way to manually specify the cache time for the downloaded image?
Will an image with style="display: none" still be downloaded and cached?
Be careful about using "None" vs. "". If you send "" then the HttpHeader for Vary is not sent. If you send "None" then the HttpHeader for Vary is sent. I used Fiddler to verify this behavior. This seems to have an impact on whether or not the browser goes back to the server to check for latest version (causing a 304). At least in Chrome it does. You want to use Varies="" if you know for sure you aren't going to want to update the file before it has expired. I'd recommend using Varies="" as I did in this post. For my javascript file I dont want the browser going back and making another Http request until it has expired. 304 is unnecessary.
I am using the standard outputcache tag in my MVC app which works great but I need to force it to be dumped at certain times. How do I achieve this? The page that gets cached is built from a very simple route {Controller}/{PageName} - so most pages are something like this: /Pages/About-Us Here is the output cache tag that is at the top of my .aspx view page just to be clear: <@ OutputCache Duration="100" VaryByParam="None" %> So in another action on the same controller where content is updated I need to dump this cache, or even all of it - it's a very small app so not a big deal deal to dump all cached items.
Expire Output Cache ASP.Net MVC
You should use sqlContext.cacheTable("table_name") in order to cache it, or alternatively use CACHE TABLE table_name SQL query. Here's an example. I've got this file on HDFS: 1|Alex|[email protected] 2|Paul|[email protected] 3|John|[email protected] Then the code in PySpark: people = sc.textFile('hdfs://sparkdemo:8020/people.txt') people_t = people.map(lambda x: x.split('|')).map(lambda x: Row(id=x[0], name=x[1], email=x[2])) tbl = sqlContext.inferSchema(people_t) tbl.registerTempTable('people') Now we have a table and can query it: sqlContext.sql('select * from people').collect() To persist it, we have 3 options: # 1st - using SQL sqlContext.sql('CACHE TABLE people').collect() # 2nd - using SQLContext sqlContext.cacheTable('people') sqlContext.sql('select count(*) from people').collect() # 3rd - using Spark cache underlying RDD tbl.cache() sqlContext.sql('select count(*) from people').collect() 1st and 2nd options are preferred as they would cache the data in optimized in-memory columnar format, while 3rd would cache it just as any other RDD in row-oriented fashion So going back to your question, here's one possible solution: output = sqlContext.sql("SELECT * From people") output.registerTempTable('people2') sqlContext.cacheTable('people2') sqlContext.sql("SELECT count(*) From people2").collect()
Is there any way to cache a cache sql query result without using rdd.cache()? for examples: output = sqlContext.sql("SELECT * From people") We can use output.cache() to cache the result, but then we cannot use sql query to deal with it. So I want to ask is there anything like sqlcontext.cacheTable() to cache the result?
Spark SQL: how to cache sql query result without using rdd.cache()
After some research, I found a great tutorial on Medium by Alex Barashkov: "Best practices for cache control settings for your website". Alex writes: I recommend you apply Cache-Control: no-cache to html files. Applying “no-cache” does not mean that there is no cache at all, it simply tells the browser to validate resources on the server before use it from the cache. That’s why we need to use it with Etag, so browsers will send a simple request and load the extra 80 bytes to verify the state of the file.
Definition of ETag header (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag): The ETag HTTP response header is an identifier for a specific version of a resource. It allows caches to be more efficient, and saves bandwidth, as a web server does not need to send a full response if the content has not changed. On the other side, if the content has changed, etags are useful to help prevent simultaneous updates of a resource from overwriting each other ("mid-air collisions"). Definition of Cache-Control header (https://developer.mozilla.org/de/docs/Web/HTTP/Headers/Cache-Control): The Cache-Control general-header field is used to specify directives for caching mechanisms in both requests and responses. So the ETag header tells the browser for a resource to send a single HTTP request to the server and ask if the file hash has changed. If yes, download a new one. Great. So if the ETag header is set why should I need Cache-Control any more (beside of the Expires header which may help to avoid this single request)? So if I have to set the Cache-Control header anyway it can only be harmful right? I think the most appropriate value would be: Cache-Control: must-revalidate But I am not sure if this triggers unecessary additional actions.
Does the ETag header make the Cache-Control header obsolete? How to make sure Cache-Control is not harmful then?
gcc uses builtin functions as an interface for lowlevel instructions. In particular for your case __builtin_prefetch. But you only should see a measurable difference when using this in cases where the access pattern is not easy to predict automatically.
In my application, at one point I need to perform calculations on a large contiguous block of memory data (100s of MBs). What I was thinking was to keep prefetching the part of the block my program will touch in future, so that when I perform calculations on that portion, the data is already in the cache. Can someone give me a simple example of how to achieve this with gcc? I read _mm_prefetch somewhere, but don't know how to properly use it. Also note that I have a multicore system, but each core will be working on a different region of memory in parallel.
Prefetching data to cache for x86-64
If you want an LRU cache, the simplest in Java is LinkedHashMap. The default behaviour is FIFO however you can changes it to "access order" which makes it an LRU cache. public static <K,V> Map<K,V> lruCache(final int maxSize) { return new LinkedHashMap<K, V>(maxSize*4/3, 0.75f, true) { @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > maxSize; } }; } Note: I have using the constructor which changes the collection from newest first to most recently used first. From the Javadoc public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) Constructs an empty LinkedHashMap instance with the specified initial capacity, load factor and ordering mode. Parameters: initialCapacity - the initial capacity loadFactor - the load factor accessOrder - the ordering mode - true for access-order, false for insertion-order When accessOrder is true the LinkedHashMap re-arranges the order of the map whenever you get() an entry which is not the last one. This way the oldest entry is the least which is recently used.
I was looking at this problem of LRU cache implementation where after the size of the cache is full, the least recently used item is popped out and it is replaced by the new item. I have two implementations in mind: 1). Create two maps which looks something like this std::map<timestamp, k> time_to_key std::map<key, std::pair<timestamp, V>> LRUCache To insert a new element, we can put the current timestamp and value in the LRUCache. While when the size of the cache is full, we can evict the least recent element by finding the smallest timestamp present in time_to_key and removing the corresponding key from LRUCache. Inserting a new item is O(1), updating the timestamp is O(n) (because we need to search the k corresponding to the timestamp in time_to_key. 2). Have a linked list in which the least recently used cache is present at the head and the new item is added at the tail. When an item arrives which is already present in the cache, the node corresponding to the key of that item is moved to the tail of the list. Inserting a new item is O(1), updating the timestamp is again O(n) (because we need to move to the tail of the list), and deleting an element is O(1). Now I have the following questions: Which one of these implementations is better for an LRUCache. Is there any other way to implement the LRU Cache. In Java, should I use HashMap to implement the LRUCache I have seen questions like, implement a generic LRU cache, and also have seen questions like implementing an LRU cache. Is generic LRU cache different from LRU cache? Thanks in advance!!! EDIT: Another way (easiest way) to implement LRUCache in Java is by using LinkedHashMap and by overriding the boolean removeEldestEntry(Map.entry eldest) function.
Best way to implement LRU cache
If a memory region is accessed by both hardware and software simultaneously (EX: hardware configuration register or scatter-gather list for DMA), this region must be defined as non-cached. For actual DMA, the memory buffer can be defined as cached, and in most cases, it is advisable for the buffer to be cached to allow the application level speedy access to that buffer. It's the driver's responsibility to flush/invalidate cache before passing the buffer to DMA or the application. Small update, above must is not correct in case we have a specialized hardware, i.e. Cache Coherency Interconnect (CCI) which will synchronize access of various hardware blocks to memory.
In an embedded application, we have a table describing the various address ranges that are valid on our target board. This table is used to set up the MMU. The RAM address range is marked as cacheable, but other regions are not. Why is that?
Why would a region of memory be marked non-cached?
I assume that lambda cannot be that better than bind. That's quite a preconception. Lambdas are tied into the compiler internals, so extra optimization opportunities may be found. Moreover, they're designed to avoid inefficiency. However, there are probably no compiler optimization tricks happening here. The likely culprit is the argument to bind, bind(&decltype(result)::eval, &result). You are passing a pointer-to-member-function (PTMF) and an object. Unlike the lambda type, the PTMF does not capture what function actually gets called; it only contains the function signature (parameter and return types). The slow loop is using an indirect branch function call, because the compiler failed to resolve the function pointer through constant propagation. If you rename the member eval() to operator () () and get rid of bind, then the explicit object will essentially behave like the lambda and the performance difference should disappear.
I wanted to time a few functions' execution and I've written myself a helper: using namespace std; template<int N = 1, class Fun, class... Args> void timeExec(string name, Fun fun, Args... args) { auto start = chrono::steady_clock::now(); for(int i = 0; i < N; ++i) { fun(args...); } auto end = chrono::steady_clock::now(); auto diff = end - start; cout << name << ": "<< chrono::duration<double, milli>(diff).count() << " ms. << endl; } I figured that for timing member functions this way I'd have to use bind or lambda and I wanted to see which would impact the performance less, so I did: const int TIMES = 10000; timeExec<TIMES>("Bind evaluation", bind(&decltype(result)::eval, &result)); timeExec<1>("Lambda evaluation", [&]() { for(int i = 0; i < TIMES; ++i) { result.eval(); } }); The results are: Bind evaluation: 0.355158 ms. Lambda evaluation: 0.014414 ms. I don't know the internals, but I assume that lambda cannot be that better than bind. The only plausible explanation I can think of is the compiler optimizing-out subsequent function evaluations in the lambda's loop. How would you explain it?
std::bind vs lambda performance
Caching like you might need for simple offline operation is not exactly that easy. Your first option is the cache manifest. It has some limitations (like the size of the cache) but might work for you since it was designed to do what you want. Another options is that you can store content on the disk of the device using the file system APIs. This has some drawbacks like security and the fact that you have to load the file from a path / url that is different than you might normally load it from on the web. Check out the hydra plugin for an example of this. One final option might be to store stuff in localStorage (which has the benefit of being private on all platforms) and then pull it out of there when needed ... that means base64'ing all your images tho so that is a pretty big departure from just standard caching.
I need a way for cache images and html files in PhoneGap from my site. I'm planning that users will see site without internet connection like it will be with it. But I see information only about sql data storing, but how can I store images (and use later).
How to cache images and html files in PhoneGap
You can add ResponseCacheAttribute to the controller, like this: [ApiVersion("1.0")] [Route("api/[controller]")] [ApiController] [ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] public class TestScenariosController : Controller { ... } Alternatively, you can add ResponseCacheAttribute as a global filter, like this: services .AddMvc(o => { o.Filters.Add(new ResponseCacheAttribute { NoStore = true, Location = ResponseCacheLocation.None }); }); This disables all caching for MVC requests and can be overridden per controller/action by applying ResponseCacheAttribute again to the desired controller/action. See ResponseCache attribute in the docs for more information.
I have a simple ASP.NET Core 2.2 Web Api controller: [ApiVersion("1.0")] [Route("api/[controller]")] [ApiController] public class TestScenariosController : Controller { [HttpGet("v2")] public ActionResult<List<TestScenarioItem>> GetAll() { var entities = _dbContext.TestScenarios.AsNoTracking().Select(e => new TestScenarioItem { Id = e.Id, Name = e.Name, Description = e.Description, }).ToList(); return entities; } } When I query this action from angular app using @angular/common/http: this.http.get<TestScenarioItem[]>(`${this.baseUrl}/api/TestScenarios/v2`); In IE11, I only get the cached result. How do I disable cache for all web api responses?
How to disable caching for all WebApi responses in order to avoid IE using (from cache) responses
According to nginx manual, this directive adds the Expires and Cache-Control HTTP header to the response. Value -1 means these headers are set as: Expires: current time minus 1 second Cache-Control: no-cache So in summary it instructs the browser not to cache the document.
Given the sample location example below, what does -1 mean for expires? Does that mean "never expires" or "never caches"? # cache.appcache, your document html and data location ~* \.(?:manifest|appcache|html?|xml|json)$ { expires -1; access_log logs/static.log; } https://github.com/h5bp/server-configs-nginx/blob/b935688c2b/h5bp/location/expires.conf
What does `expires -1` mean in NGINX `location` directive?
Caching only works for get() calls by default, but queries use the query cache if you update them with cache: true (criteria and HQL). cache true creates a read-write cache but you can configure a read-only cache with static mapping = { cache usage:'read-only' } The read-only cache is good for lookup data that never changes, for example states, countries, roles, etc. If you have domain classes that update, create, or delete frequently, query caching will often be slower than not caching. This is because changes like these cause all cached queries to be cleared, so you're often going directly to the database anyway. See http://tech.puredanger.com/2009/07/10/hibernate-query-cache/ for a more detailed description of this. For this reason I rarely use query caching and often disable it completely with hibernate { cache.use_second_level_cache=true cache.use_query_cache=false cache.provider_class='org.hibernate.cache.EhCacheProvider' } Domain classes that are "read-mostly" are the best candidates for read-write caching. The caches get cleared for each update, create, and delete, but if these are somewhat rare you'll see an overall performance boost. Hibernate has an API to monitor cache usage. The http://grails.org/plugin/app-info and http://grails.org/plugin/hibernate-stats plugins make the information available and you can use the approach there in your own code.
I have been considering implementing EhCache in my Grails domain objects like this : static mapping = { cache true } I am not too familiar with exactly how this caching mechanism works and was wondering what a good rule of thumb is in determining which domain objects would benefit from being cached. eg, objects that are accessed rarely.. often... ? Thanks!
Caching domain objects in Grails
And/or how to developers normally work with Firefox in this regard? I tend to use CTRL + F5 to do hard reload (ignores cache). Pretty standard for all browsers. Since there is no native way to configure for individual domains, you could write a Browser Extension that can intercept responses via the webRequest API (see for example onHeadersReceived) by overriding cache headers for a selected domain (you may even be able to find one already in existence). Or simply configure settings in developer tools to ignore cache when toolbox is open: There is also the Forget Button that can be dragged into the toolbar from customize.
I've been curious to try switching to Firefox Quantum from Chrome, but for web development have hit a major obstacle that I have not been able to easily resolve –– it's caching my localhost files so when I attempt to load various ember applications at localhost:4200 I end up viewing a cached application different than the one that is currently running. Is there a way to disable caching for localhost in Firefox? And/or how to developers normally work with Firefox in this regard?
Prevent Firefox from caching localhost?
Caching should be done in the model. If I had to choose in general, I would probably end up transparently caching the model's database interaction, which wouldn't require you to make any changes to the rest of your code. This of course would be done in the parent class of your models. Definitely focus on caching your database query results, as interfacing with your database is where you will see the most overhead. I would argue that it would be more efficient to cache your database results (or maybe your entire initialized model) more than anything else. Remember that you can serialize your objects before caching, so sending complex types (arrays or objects) into memcache shouldn't be a problem. PHP 5 provides the magic methods __sleep() and __wakeup() for the very purposes of seralizing and reconstructing your serialized objects. Caching full objects in PHP is basically a piece of cake. See http://php.net/manual/en/language.oop5.magic.php for more info. Whether you decide to cache just your data or your entire model shortly after initialization is up to you.
I am having some second thoughts about where to implement the caching part. Where is the most appropriate place to implement it, you think? Inside every model, or in the controller? Approach 1 (psuedo-code): // mycontroller.php MyController extends Controller_class { function index () { $data = $this->model->getData(); echo $data; } } // myModel.php MyModel extends Model_Class{ function getData() { $data = memcached->get('data'); if (!$data) { $query->SQL_QUERY("Do query!"); } return $data; } } Approach 2: // mycontroller.php MyController extends Controller_class { function index () { $dataArray = $this->memcached->getMulti('data','data2'); foreach ($dataArray as $key) { if (!$key) { $data = $this->model->getData(); $this->memcached->set($key, $data); } } echo $data; } } // myModel.php MyModel extends Model_Class{ function getData() { $query->SQL_QUERY("Do query!"); return $data; } } Thoughts: Approach 1: No multiget/multi-set. If a high number of keys would be returned, overhead would be caused. Easier to maintain, all database/cache handling is in each model Approach 2: Better performancewise - multiset/multiget is used More code required Harder to maintain Tell me what you think!
Cache layer for MVC - Model or controller?
It cache the result of the previous steps of the Flux/Mono until the cache() method is called, check the output of this code to see it in action: import reactor.core.publisher.Mono; public class CacheExample { public static void main(String[] args) { var mono = Mono.fromCallable(() -> { System.out.println("Go!"); return 5; }) .map(i -> { System.out.println("Double!"); return i * 2; }); var cached = mono.cache(); System.out.println("Using cached"); System.out.println("1. " + cached.block()); System.out.println("2. " + cached.block()); System.out.println("3. " + cached.block()); System.out.println("Using NOT cached"); System.out.println("1. " + mono.block()); System.out.println("2. " + mono.block()); System.out.println("3. " + mono.block()); } } output: Using cached Go! Double! 1. 10 2. 10 3. 10 Using NOT cached Go! Double! 1. 10 Go! Double! 2. 10 Go! Double! 3. 10
I'm a beginner of spring webflux. While researching I found some code like: Mono result = someMethodThatReturnMono().cache(); The name "cache" tell me about caching something, but where is the cache and how to retrieve cached things? Is it something like caffeine?
How to use "cache" method of Mono
18 Apparently all the comments about your problem were right. You should use CacheEvict. I found solution here: https://www.baeldung.com/spring-boot-evict-cache and it looks like this: All you have to do is create class called e.g. CacheService and create method that will evict all cached objects you have. Then you annotate that method @Scheduled and put your interval rate. @Service public class CacheService { @Autowired CacheManager cacheManager; public void evictAllCaches() { cacheManager.getCacheNames().stream() .forEach(cacheName -> cacheManager.getCache(cacheName).clear()); } @Scheduled(fixedRate = 6000) public void evictAllcachesAtIntervals() { evictAllCaches(); } } Share Improve this answer Follow edited Jan 19, 2020 at 21:34 Dharman♦ 31.9k2525 gold badges9191 silver badges139139 bronze badges answered Jan 19, 2020 at 19:26 J.Kennsy J.Kennsy 59811 gold badge66 silver badges1919 bronze badges 2 I want to unit test cacheservice.evictAllcaches. I observed cacheManager.getCacheNames() returns same cache values after clearing cache. Any idea how to test empty cache scenario. – StackOverFlow Jul 1, 2020 at 12:55 Since Collection also has a forEach method, the solution can be simplified a little by removing the .stream() call: cacheManager.getCacheNames().forEach – M. Justin Apr 26, 2023 at 18:30 Add a comment  | 
I am using Spring Boot and for caching I am using Ehcache. It's working fine till now. But now I have to reload / refresh so how can I do this so that my application will not be having any downtime. I have tried many ways in Spring Ehcache but it didn't work or Else have to write a scheduler and reload the data. @Override @Cacheable(value="partTypeCache", key="#partKey") public List<PartType> loadPartType(String partKey) throws CustomException { return productIdentityDao.loadPartType(); }
Reload/Refresh cache in spring boot
The answer to your question is no. There is no built-in dns caching in the std lib resolver. Would it be helpful? Maybe in some cases. Our org runs a local dns cache on each server and points resolv.conf there. So it wouldn't necessarily help us much to have caching in the language. There are some solutions that could help you. This package seems to have a pretty good solution. From the snippet in their readme you could even do: http.DefaultClient.Transport = &http.Transport { MaxIdleConnsPerHost: 64, Dial: func(network string, address string) (net.Conn, error) { separator := strings.LastIndex(address, ":") ip, _ := dnscache.FetchString(address[:separator]) return net.Dial("tcp", ip + address[separator:]) }, } To enable it for all http requests from http.Get and friends.
I am building a test crawler and wanted to know if Go (golang) caches DNS queries. I don't see anything about caching in the dnsclient. This seems like an important thing to add to any crawler to prevent lots of extra DNS queries. Does Go (1.4+) cache DNS lookups? If not, does debian/ubuntu/linux, windows, or darwin/OSX do any caching at the network level Go benefits from?
Does Go cache DNS lookups?
10 I have been developing a tool chain for our company that is built around waf. It targets Fedora, Ubuntu, Arch, Windows, Mac OSX and will be rolled out to our embedded devices doing cross-compilation on various hosts. We have found the way that waf allows contained extensibility through the tools, features and other methods has made it incredibly easy to customise and extend for our projects. Personally, I think it is brilliant and find it nicely abstracts the interfaces to different tools that are integrated. Unfortunately, I have no in-depth experience with Scons but lots with GNU Make/Autotools. Our decision to go with waf after evaluating build tools was that we needed something that worked well everywhere which made our build tool being backed by python and that it was fast. I based my decision on these results and went from there. Share Improve this answer Follow edited Jan 12, 2015 at 13:56 answered Feb 7, 2013 at 15:48 Matt ClarksonMatt Clarkson 14.3k1010 gold badges5959 silver badges8585 bronze badges 2 The benchmarks are interesting, but not very current. Scons 1.2.0 is from 2008 and Waf 1.5.7 is from 2009. – Demyn Oct 11, 2013 at 17:15 @Demyn, yes they are old but the only ones I could find and I wasn't interested in performing my own benchmarks. waf has worked out brilliantly for our uses. The extension mechanisms it provides are excellent. It's odd distribution method actually works well for us as it is self-unpacking. – Matt Clarkson Jan 12, 2015 at 13:55 Add a comment  | 
We are thinking about converting a really large project from using GNU Make to some more modern build tool. My current suggestion is to use SCons or Waf. Currently: Build times are around 15 minutes. Around 100 developers. About 10 percent of code is C/C++/Fortran rest is Ada (using gnatmake). Potential hopes/gains on improvements are Shared Compiler Cache to cut down build times and requires disk space Easier maintenance Does SCons scale well for this task? I've seen comments on it not scaling aswell as Waf. Those are however a couple of years old. Have scons gained in performanced the last years? If not, what is the reason for its bad performance compared to Waf.
Choosing between Scons and Waf in Large Projects
You have to delete the files manually, like so (using .bat file): @echo off rmdir /s /q "%APPDATA%\Subversion\auth" See the Authentication section of the TortoiseSVN documentation.
TortoiseSVN is nice for the most part, but one thing that blows in a team development situation where more than one person is using a particular PC is the authentication. When I'm working on stuff, I like to save my credentials so that I don't need to keep entering it in for logging, branching, committing, etc. The problem is that I always forget to clear my credentials when I walk away, because: I don't want to have to re-enter it again if no one else uses the computer and purposely forget. It's a PITA to do and requires 4 too many mouse clicks to do. Ideally, I would just have a couple of nice batch files in SVN to deal with this sort of thing, including rebuilding the icon cache (which I have working okay). I looked at the command line documentation and it doesn't mention clearing the authentication cache. Has anyone figured out how to do it? I think it'll encourage me to clear my credentials more often. It's not the end of the world since we can always change the author after the commit, but still...
Clearing TortoiseSVN authentication cache from the command line
By default google maps return's cached images (you can see this in the network tab of the console). If you user's having trouble caching the images, it's probably because they disabled the cache
I'm using Google Maps JS API v3 for a project. Is there a way to ask the map to cache tiles on the client's machine so that when they refresh the browser, the tiles don't have to all download again? Many of my clients are on cellular connections where redownloading the map takes a considerable amount of time. Thanks!
Google Maps v3 - Map tile caching on client?
If you dont have APC or Memcached installed already (or dont want to use them for this) you can also create a RAM disk. Then use file_get_contents() and file_put_contents() where filename is your key and the file content is your value. I dont have numbers for that, but it should be fast.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 12 years ago. I'm looking for the fastest in-memory cache/hashtable available for PHP. I will be storing some system-configuration values in it and I'm trying to get the least possible overhead. The data will be small and granular. What would you recommend and why?
Fastest PHP memory cache/hashtable [closed]
If you want to refresh a specific object, then the Refresh() method may be your best bet. Like this: Context.Refresh(RefreshMode.OverwriteCurrentValues, objectToRefresh); You can also pass an array of objects or an IEnumerable as the 2nd argument if you need to refresh more than one object at a time. Update I see what you're talking about in comments, in reflector you see this happening inside .Refresh(): object objectByKey = context.Services.GetObjectByKey(trackedObject.Type, keyValues); if (objectByKey == null) { throw Error.RefreshOfDeletedObject(); } The method you linked seems to be your best option, the DataContext class doesn't provide any other way to clear a deleted row. The disposal checks and such are inside the ClearCache() method...it's really just checking for disposal and calling ResetServices() on the CommonDataServices underneath..the only ill-effect would be clearing any pending inserts, updates or deletes that you have queued. There is one more option, can you fire up another DataContext for whatever operation you're doing? It wouldn't have any cache to it...but that does involve some computational cost, so if the pending insert, update and deletes aren't an issue, I'd stick with the ClearCache() approach.
I'm using Linq to Sql to query some database, i only use Linq to read data from the DB, and i make changes to it by other means. (This cannot be changed, this is a restriction from the App that we are extending, all updates must go trough its sdk). This is fine, but I'm hitting some cache problems, basically, i query a row using Linq, then i delete it trough external means, and then i create a new row externally if i query that row again using linq i got the old (cached) data. I cannot turn off Object Tracking because that seems to prevent the data context from auto loading associated propertys (Foreign Keys). Is there any way to clear the DataContex cache? I found a method sufring the net but it doesn't seem safe: http://blog.robustsoftware.co.uk/2008/11/clearing-cache-of-linq-to-sql.html What do you think? what are my options?.
How to clear the DataContext cache on Linq to Sql
Caching is controlled via a variety of HTTP headers. You should read Mark Nottingham's Caching Tutorial for Web Authors and Webmasters. You can set HTTP headers for documents outputted from PHP using the header function.
According to: http://code.google.com/speed/page-speed/docs/caching.html#LeverageBrowserCaching I should be using browser caching. However, I don't know how. Do I simply add certain tags into the html section? Or is thing something I need to send via to server to the client? something to do with php headers?
Leverage browser caching
cache._expire_info.get('foo') to get the unix timestamp
It must be stored somewhere. I can change it with set()/incr(), but I couldn't find the way to read it.
Can I get expiration time of specified key in django cache?
Unless the browser is seriously broken, there should be nothing wrong. Suppose you wanted to use a dynamic file, such as url('/layout.php?section=1') or something. Query strings are kind of required there, so if the browser didn't work it'd be broken quite badly.
We're making changes to our main sprite and I'm debating the benefits of either changing its name completely or adding a query string to the end. There's logic to keeping the old version to support Google cache, archive.com, etc., but it'd also be much cleaner on our system if I was to just edit the file and add a query string to the CSS image call: #element-id { background-image: url('my-sprite.png?version1'); } My question is, does anyone know of any browser issues with using a query string cache buster in a CSS file? My suspicion is that browsers handle css image requests the same way whether it's from CSS files or via HTML, so, so long as my server is expressing header information properly I should be OK.
Does anyone know of any issues using a querystring within a CSS file?
HTML5 Cache HTML5 provides application cache, which means that a web application is cached, and accessible without an internet connection. Application cache gives an application three advantages: Offline browsing - users can use the application when they're offline Speed - cached resources load faster Reduced server load - the browser will only download updated/changed resources from the server Browser cache Internet browsers use caching to store HTML web pages by storing a copy of visited pages and then using that copy to render when you re-visit that page. If the date on the page is the same date as the previously stored copy, then the computer uses the one on your hard drive rather than re-downloading it from the internet. References - http://www.w3schools.com/html/html5_app_cache.asp http://www.pctools.com/security-news/what-is-a-browser-cache/ The new HTML5 specification allows browsers to prefetch some or all of a website assets such as HTML files, images, CSS, JavaScript, and so on, while the client is connected. It is not necessary for the user to have accessed this content previously, for fetching this content. In other words, application cache can prefetch pages that have not been visited at all and are thereby unavailable in the regular browser cache. Prefetching files can speed up the site's performance, though you are of course using bandwidth to download those files initially.
Is HTML5 Application Cache different from browser cache?? If so, in what aspects, it is different and how this mechanism works?? And tell me how using AppCache we can improve browsing performance.. Also discuss about the pros and cons of HTML5 AppCache (its expiry and storage size limit etc.,)??
Browser Cache Vs HTML5 Application Cache
Since it's out-of-process, it has to do serialization and deserialization. The problem you concern is how to reduce the serialization/deserizliation work. If you use Redis' STRING type, you CANNOT reduce these work. However, You can use HASH to solve the problem: mapping your SQL table to a HASH. Suppose you have the following table: person: id(varchar), name(varchar), age(int), you can take person id as key, and take name and age as fields. When you want to search someone's name, you only need to get the name field (HGET person-id name), other fields won't be deserialzed.
I have a SQL table that is accessed continually but changes very rarely. The Table is partitioned by UserID and each user has many records in the table. I want to save database resources and move this table closer to the application in some kind of memory cache. In process caching is too memory intensive so it needs to be external to the application. Key Value stores like Redis are proving inefficient due to the overhead of serializing and deserializing the table to and from Redis. I am looking for something that can store this table (or partitions of data) in memory, but let me query only the information I need without serializing and deserializing large blocks of data for each read. Is there anything that would provide Out of Process in memory database table that supports queries for high speed caching? Searching has shown that Apache Ignite might be a possible option, but I am looking for more informed suggestions.
Out of Process in memory database table that supports queries for high speed caching
See the Caching Tutorial for Web Authors and Webmasters which explains about all the different cache control headers (especially the part the explains that those meta tags are largely useless and real HTTP headers are the way forwards).
What is the difference between below 3 meta tags? <META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"> <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE"> <META HTTP-EQUIV="Expires" CONTENT="-1"> Do I need to use all those tags to avoid browser caching?
HTML Cache control
14 There is also a way of disabling this in system.webServer if you are using IIS7/7.5 or IIS Express. This will work in your main web.config file (for both webforms and mvc) and also in web.config files in subfolders, to disable it for particular areas of your application. <system.webServer> <caching enabled="false" /> </system.webServer> Share Improve this answer Follow answered Sep 5, 2012 at 11:05 StuntbeaverStuntbeaver 69077 silver badges88 bronze badges 0 Add a comment  | 
is there a way to disable server caching globally in ASP.NET? Like by adding some sort of setting to the web.config file? So far I've tried adding these and it didnt make a difference... <caching> <sqlCacheDependency enabled="false"></sqlCacheDependency> <outputCache enableOutputCache="false" enableFragmentCache="false" sendCacheControlHeader="false" omitVaryStar="false" /> </caching>
Disable cache globally .NET
According to the Google documentation, the best way to invalidate and reload the file is to add a version number to the file name and not as a query parameter: 'app/source/scripts/project.32472938.js' Here is a link to the documentation: https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching#invalidating_and_updating_cached_responses Another way is to use an ETag (validation token): https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching#validating_cached_responses_with_etags Here is how you would set up an ETag with Nginx: http://nginx.org/en/docs/http/ngx_http_core_module.html#etag And lastly, a tutorial about browser caching with Nginx and ETag: https://www.digitalocean.com/community/tutorials/how-to-implement-browser-caching-with-nginx-s-header-module-on-centos-7#step-2-%14-checking-the-default-behavior
When I deploy the version I will add the number as a query string with the JavaScript and CSS file like following? 'app/source/scripts/project.js?burst=32472938' I am using the above to burst the cache in the browser. But in Firefox, I am getting the latest script that I have modified. But in Chrome, I am not getting the latest script that I have modified. Instead of that, I am getting the old one. But in the developer console, I am seeing the burst number which is modified in latest.
Cache is not cleared in Google Chrome
You can either Use the maintainance script PurgeList.php like this: php purgeList.php --purge --all, for MW > 1.21, and php purgeList.php --all-namespaces for MW > 1.34. Really old MW versions do not have the --all option, so you will need a list of pages. Use the API: API:Purge, and feed it with a list of all pages (that you can get from API:Allpages) Invalidate all caches by setting $wgCacheEpoch to the current time in LocalSettings.php, e.g. $wgCacheEpoch = 20140901104232;. Set $wgInvalidateCacheOnLocalSettingsChange (since MW 1.17) to achieve pretty much the same thing. Only do this if your wiki has low to moderate traffic. Not sure if this is a good idea, but if you have access to the wiki's database you should also be able to achieve the same effect by truncating the table objectcache.
Is it possible to purge all pages in mediawiki? I've tried emptying the obejctcache table to no avail. I don't particularly want to hit each page with ?action=purge appended. Version 1.23.3
Purging all pages in mediawiki
You can modify the amount of ram available using this commands on the powerShell console: Stop-cachecluster Set-cacheHostConfig {Machine name} {port(22233)} -CacheSize {cache allocation in MB} Start-cachecluster More info on MSDN
How do I set the amount of memory available to the Windows Server AppFabric Caching service? We're running the AppFabric Cache on the same server which is hosting the website, and I'd like to be able to control how much RAM the cache will consume.
Set amount of memory available to AppFabric Caching
1 Cache["key"] = value is equal to Cache.Insert("key", value) MSDN Cache.Insert - method (String, Object): This method will overwrite an existing cache item whose key matches the key parameter. The object added to the cache using this overload of the Insert method is inserted with no file or cache dependencies, a priority of Default, a sliding expiration value of NoSlidingExpiration, and an absolute expiration value of NoAbsoluteExpiration. 2 It's better to remove values from cache by Cache.Remove("key"). If you use Cache["key"] = null it's equal to Cache.Insert("key", null). Take a look at the Cache.Insert implementation: public void Insert(string key, object value) { this._cacheInternal.DoInsert(true, key, value, null, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.Normal, null, true); } and CacheInternal.DoInsert: internal object DoInsert(bool isPublic, string key, object value, CacheDependency dependencies, DateTime utcAbsoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback, bool replace) { using (dependencies) { object obj2; CacheEntry cacheKey = new CacheEntry(key, value, dependencies, onRemoveCallback, utcAbsoluteExpiration, slidingExpiration, priority, isPublic); cacheKey = this.UpdateCache(cacheKey, cacheKey, replace, CacheItemRemovedReason.Removed, out obj2); if (cacheKey != null) { return cacheKey.Value; } return null; } } Compare it to Cache.Remove: public object Remove(string key) { CacheKey cacheKey = new CacheKey(key, true); return this._cacheInternal.DoRemove(cacheKey, CacheItemRemovedReason.Removed); } Cache.Insert("key", value)0: Cache.Insert("key", value)1 And finally Cache.Insert("key", value)2 is much more readble than Cache.Insert("key", value)3
If I insert to Cache by assigning the value: Cache["key"] = value; what's the expiration time? Removing the same value from Cache: I want to check if the value is in Cache by if(Cache["key"]!=null), is it better to remove it from Cache by Cache.Remove("key") or Cache["key"]=null ? -- Edit -- After having tried Cache.Remove and Cache["key"]=null, DO NOT USE Cache["key"]=null, as it will throw exceptions when used in stress.
C# - Inserting and Removing from Cache
7 You will find multiple answers here: Angular 2 cache observable http result data I would recommend to build simple class Cacheable<> that helps managing cache of data retrieved from http server or other any other source: declare type GetDataHandler<T> = () => Observable<T>; export class Cacheable<T> { protected data: T; protected subjectData: Subject<T>; protected observableData: Observable<T>; public getHandler: GetDataHandler<T>; constructor() { this.subjectData = new ReplaySubject(1); this.observableData = this.subjectData.asObservable(); } public getData(): Observable<T> { if (!this.getHandler) { throw new Error("getHandler is not defined"); } if (!this.data) { this.getHandler().map((r: T) => { this.data = r; return r; }).subscribe( result => this.subjectData.next(result), err => this.subjectData.error(err) ); } return this.observableData; } public resetCache(): void { this.data = null; } public refresh(): void { this.resetCache(); this.getData(); } } Usage Declare Cacheable<> object (presumably as part of the service): list: Cacheable<string> = new Cacheable<string>(); and handler: this.list.getHandler = () => { // get data from server return this.http.get(url) .map((r: Response) => r.json() as string[]); } Call from a component: //gets data from server List.getData().subscribe(…) More details and code example are here: http://devinstance.net/articles/20171021/rxjs-cacheable Share Improve this answer Follow answered Nov 27, 2017 at 18:50 instanceMasterinstanceMaster 47133 silver badges1212 bronze badges 1 Thanks for posting the links as part of your answer. – Chris Claude Jan 6, 2022 at 17:52 Add a comment  | 
I have a lot of services with requests to rest service and I want to cache data receive from server for further usage. Could anyone tell what is the best way to cash response?
Angular - best way to cache http response
7 This is specific for JQUERY.... Your can make ajax set up as cached. $.ajaxSetup({ cache: true}); and if for specific calls you don't want to make cached response then call $.ajax({ url: ..., type: "GET", cache: false, ... }); If you want opposite (cache for specific calls) you can set false at the beginning and true for specific calls If you want to store the result of ajax response, you can make use of Local Storage. All the modern browsers provides you storage apis. You can use them (localStorage or sessionStorage) to save your data. All you have to do is after receiving the response store it to browser storage. Then next time you find the same call, search if the response is saved already. If yes, return the response from there; if not make a fresh call. Smartjax plugin also does similar things; but as your requirement is just saving the call response, you can write your code inside your jQuery ajax success function to save the response. And before making call just check if the response is already saved. Share Improve this answer Follow edited Nov 24, 2015 at 6:20 Mauricio Gracia Gutierrez 10.6k66 gold badges7272 silver badges105105 bronze badges answered Nov 17, 2015 at 9:48 Somnath MulukSomnath Muluk 56.2k3838 gold badges219219 silver badges226226 bronze badges 2 That’s specific to jQuery. Can you extend your answer to include an answer for bare XMLHttpRequests? – Robin Whittleton Nov 17, 2015 at 9:50 3 The jQuery .ajax is simply an interface to the native XHR object, so it will not help in my case – Eugene Tiurin Nov 18, 2015 at 4:07 Add a comment  | 
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 8 years ago. Improve this question I am implementing a Javascript module manager that loads javascript files via XHR object. The problem of this method is resources caching: Firstly, XHR rely on in-built browser caching mechanism which is OK but it's behaviour depends on the browser implementation. Also there is a localStorage and there is a basket.js which uses localStorage to cache downloaded scripts, the problem is in limited size of storage which is usually 5-10MB. Besides, localStorage is a shared place for many scripts which also use it to store data. And there is a Cache interface of the ServiceWorker API, but it is available only in ServiceWorker runtime so it doubtingly fit my needs. Do anyone know some smart old or new javascript caching technique he's using in his project, or maybe heard of? Note: Please, don't propose to use jQuery .ajax which is an interface to XHR, or any other library that implements an interface to in-built Javascript features. Edit: There have been some valuable proposes: Use library called localForage. The library represents a unified API to IndexedDB, WebSQL and localStorage, which one is used depends on browser. Use IndexedDB which is truly powerfull storage with no significant space limits. The only concern is that only modern browsers implement IndexedDB.
What are possible techniques to cache an Ajax response in Javascript? [closed]
8 +150 Not directly possible. But can be done with some changes to your docker file. To forcibly break the cache, you can use "build-time arguments" (ARG); changing the value of that argument breaks the cache, and every step after it, for example: FROM something RUN apt-get update && apt-get install foo bar baz ...... ARG CACHE_DATE=2016-01-01 # steps below will always be executed if `CACHE_DATE` is changed to a unique value RUN blablabla And set a new date for CACHE_DATE during build: docker build --build-arg CACHE_DATE="$(date)" .... details taken directly from this github issue. Share Improve this answer Follow answered Aug 26, 2022 at 13:23 Just a coderJust a coder 16k1717 gold badges8585 silver badges143143 bronze badges Add a comment  | 
I have a long-running docker build process, so I would prefer not to disable caching for the entire build (with --no-cache). However, I would like to invalidate caching for a particular step. I had a bright idea: remove the cached layer and rebuild so this has to rebuild. I used: docker build --progress=plain to get hold of the sha of the cached layer: #16 [stage-9 3/15] RUN pip install -r /tmp/requirements.lock #16 sha256:e4ac79a1eac5702cd296ccf33a1cfa2e0c3890c77d42737dc62a3b26ac3e798e #16 CACHED But then I got this error > docker rmi e4ac79a1eac5702cd296ccf33a1cfa2e0c3890c77d42737dc62a3b26ac3e798 Error: No such image: e4ac79a1eac5702cd296ccf33a1cfa2e0c3890c77d42737dc62a3b26ac3e798 Is there an (easy) way of deleting this layer? Note: For most use cases (and maybe even this one) you might like to use the --no-cache option for docker build
Can I remove a single layer from from docker to prevent caching?
Comparing these cache providers effectively boils down to comparing memcached vs prevalence vs Velocity, etc, and that is not really related to NHibernate. Here are some reasons (by no means a complete list) to pick one over the others: If you want to keep it simple and don't run your app in a farm, you might want to use SysCache/Prevalence, which runs in-proc. If you use MS SQL Server, use SysCache2. If you need a huge cache across many cache-dedicated servers, you might want to use memcached, which can run on Linux so you'd avoid licensing costs. If your application runs on Azure or already uses AppFabric, you might want to use Velocity. Personally I prefer to do caching myself at a higher level than data access (only when really necessary), as to make caching more intentional and meaningful than just entities and to embrace more than data access in the cache. In a properly designed system, caching can be easily transparent using decorators or proxies.
I've been using NHibernate for a while now, I'm still wondering what the differences are between the the Second Level Cache Providers ? Do some perform better\worse ? What is popular and why ? For clarity I'm talking about: NHibernate.Caches.MemCache NHibernate.Caches.Prevalence NHibernate.Caches.SharedCache NHibernate.Caches.SysCache NHibernate.Caches.SysCache2 NHibernate.Caches.Velocity and I'm sure there are others. Thanks
NHibernate 2nd Level Cache Provider Differences
is it possible to make WeakReference from WeakMap or make garbage-collected cache from WeakMap ? AFAIK the answer is "no" to both questions.
I want to cache large objects in JavaScript. These objects are retrieved by key, and it makes sense to cache them. But they won't fit in memory all at once, so I want them to be garbage collected if needed - the GC obviously knows better. It is pretty trivial to make such a cache using WeakReference or WeakValueDictionary found in other languages, but in ES6 we have WeakMap instead, where keys are weak. So, is it possible to make something like a WeakReference or make garbage-collected caches from WeakMap?
Garbage-collected cache via Javascript WeakMaps
7 So, after few years ;) that's what I believe happened: Caching is not a way to save execution memory. The best you can do is not to lose execution memory (DISK_ONLY) when caching. It's most likely the lack of execution memory that caused my job to throw OOM error, although I don't remember the actual use case. I used MEMORY_AND_DISK caching and the MEMORY part took its part from the unified region which made it impossible for my job to finish (since the Execution = Unified - Storage memory was not enough to perform the job) Due to above, when I removed caching at all, it took slower, but the job had enough execution memory to finish. With DISK_ONLY caching it seems that the job would therefore finish as well (although not necessarily faster). https://spark.apache.org/docs/latest/tuning.html#memory-management-overview Share Improve this answer Follow answered Nov 19, 2019 at 9:41 MatekMatek 66155 silver badges1717 bronze badges Add a comment  | 
Lately I've been running a memory-heavy spark job and started to wonder about storage levels of spark. I persisted one of my RDDs as it was used twice using StorageLevel.MEMORY_AND_DISK. I was getting OOM Java heap space during the job. Then, when I removed the persist completely, the job has managed to go through and finish. I always thought that the MEMORY_AND_DISK is basically a fully safe option - if you run out of memory, it spills the object to disk, done. But now it seemed that it did not really work in the way I expected it to. This derives two questions: If MEMORY_AND_DISK spills the objects to disk when executor goes out of memory, does it ever make sense to use DISK_ONLY mode (except some very specific configurations like spark.memory.storageFraction=0)? If MEMORY_AND_DISK spills the objects to disk when executor goes out of memory, how could I fix the problem with OOM by removing the caching? Did I miss something and the problem was actually elsewhere?
Spark - StorageLevel (DISK_ONLY vs MEMORY_AND_DISK) and Out of memory Java heap space
The answer is that Chrome does not like "Expires:Mon, 01 Jan 0001 00:00:00 GMT" (a fake date, basically). I changed my date to be what they use in their Google API, and it worked: Cache-Control:no-store, must-revalidate, no-cache, max-age=0 Content-Length:1897 Content-Type:application/json; charset=utf-8 Date:Fri, 19 Jul 2013 20:51:49 GMT Expires:Mon, 01 Jan 1990 00:00:00 GMT Pragma:no-cache Server:Microsoft-IIS/8.0 So, for anyone else who comes across this problem, make sure you set your Expires date to this arbitrary date!
I am using ASP.NET WebApi and have the following code to stop caching in everything: public override System.Threading.Tasks.Task<HttpResponseMessage> ExecuteAsync(System.Web.Http.Controllers.HttpControllerContext controllerContext, System.Threading.CancellationToken cancellationToken) { System.Threading.Tasks.Task<HttpResponseMessage> task = base.ExecuteAsync(controllerContext, cancellationToken); task.GetAwaiter().OnCompleted(() => { task.Result.Headers.CacheControl = new CacheControlHeaderValue() { NoCache = true, NoStore = true, MaxAge = new TimeSpan(0), MustRevalidate = true }; task.Result.Headers.Pragma.Add(new NameValueHeaderValue("no-cache")); task.Result.Content.Headers.Expires = DateTimeOffset.MinValue; }); return task; } The result headers look like this (chrome): Cache-Control:no-store, must-revalidate, no-cache, max-age=0 Content-Length:1891 Content-Type:application/json; charset=utf-8 Date:Fri, 19 Jul 2013 20:40:23 GMT Expires:Mon, 01 Jan 0001 00:00:00 GMT Pragma:no-cache Server:Microsoft-IIS/8.0 I added the "no-store" after reading about the bug (How to stop chrome from caching). However, no matter what I do, when I do something that navigates me away from this page, and then use the "back" button, chrome always loads from cache: Request Method:GET Status Code:200 OK (from cache) Does anyone have any idea why this is happening? I have confirmed that the server is never hit for this request.
How to stop chrome from caching REST response from WebApi?
PostSharp Starter Edition is free and would meet your requirements.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers. Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it. Closed 9 years ago. Improve this question The application we are building sends out different kind of emails regularly. I stored the email templates in an Azure blob storage and the methods responsible for sending emails pull the appropriate email templates from there. I want the templates to be outside of the hosted service in case I want to update it, I can do that simply by uploading new templates to the blob. The problem I'm having, from performance and cost perspective, is that the email templates rarely change within a 24hr period. So caching the method in a way akin to [OutputCache(Duration = duration, VaryByParam = "id")] in ASP.NET MVC will be an ideal solution in order to increase the worker role performance. How to do this is now a problem. I learnt of PostSharp but our budget didn't take PostSharp's licencing fee into consideration from the beginning! Any other free alternatives? Thanks for helping out.
Any Free Alternative to PostSharp [closed]
0 The link you provided looks like a less than ideal solution (not to mention outdated). What you probably want is a local proxy server that gives you access to byte data before the MediaPlayer gets it. See my answer here for a little more explanation. Share Improve this answer Follow edited May 23, 2017 at 12:07 CommunityBot 111 silver badge answered Sep 7, 2013 at 4:25 DaveDave 4,29222 gold badges1919 silver badges2424 bronze badges Add a comment  | 
I want to stream an audio mp3 file and then play it through android media player plus I also want to cache this file, so that mediaplayer don't have to stream for recently played tracks. I have tried using prepareAsync method but it doesn't give me access to buffer content, so I have decided to stream the audio file myself and then pass it to the media player for playing. I have achieved this by following this article here but this approach has a problem i.e. while transferring the file to media player it goes into error mode which causes my player to behave inconsistently. When media player enters its error mode it doesn't come out of it automatically so I am forced to create a new media player and then re-provide it the downloaded file, this workaround causes the user to experience an undesired pause in the song playing. So, does any one have improved an version of code given in above link? or do they know a better solution to this problem or is there is actually a library for streaming an audio file in android? Thanks
Streaming audio file and caching it
An alternative would be to append a unique number to the url. <script> var xhr = new XMLHttpRequest; xhr.open('GET', 'test.html?_=' + new Date().getTime()); //xhr.setRequestHeader('Cache-Control', 'no-cache'); xhr.send(); </script> timestamp isn't quite unique, but it should be unique enough for your usecase.
I want to ensure that data I request via an AJAX call is fresh and not cached. Therefor I send the header Cache-Control: no-cache But my Chrome Version 33 overrides this header with Cache-Control: max-age=0 if the user presses F5. Example. Put a test.html on your webserver with the contents <script> var xhr = new XMLHttpRequest; xhr.open('GET', 'test.html'); xhr.setRequestHeader('Cache-Control', 'no-cache'); xhr.send(); </script> In the chrome debugger on the network tab I see the test.html AJAX call. Status code 200. Now press F5 to reload the page. There is the max-age: 0, and status code 304 Not Modified. Firefox shows a similar behavior. Intead of just overwriting the request header it modifies it to Cache-Control: no-cache, max-age=0 on F5. Can I suppress this?
Force Cache-Control: no-cache in Chrome via XMLHttpRequest on F5 reload
You can add local directories to your Gemfile (example from the docs): gem "nokogiri", :path => "~/sw/gems/nokogiri" Alternatively, you can set up a local Git repository with the gems in it and write a Gemfile like this: gem "gem1", :git => "file:///tmp/gems", :branch => "gem1"
I have bunch of gems on my computer that I want to use in a chef recipe. I know it is possible to put them in a directory like /tmp/gems and just: cd /tmp/gems gem install *.gem Is it possible to put all gems in one directory where I can install them with bundler without downloading them again? cd /somedir/my_rails_project bundle I want to save bandwidth.
Is it possible to bundle / install gems from a local cache?
You need to actually install the memcached server so that it can be connected to. On CentOS, this can be done with... sudo yum install memcached (on debian flavors of linux, use apt-get instead of yum)
I am trying to connect to memcache as they suggest: $memcache = new Memcache(); $memcache->pconnect('localhost',11211); But i get: Notice: Memcache::pconnect() [memcache.pconnect]: Server localhost (tcp 11211) failed with: Connection refused (111) in /home/user/public_html/website.com/includes/basedatos.php on line 26 Any idea why?
Can't connect to memcache
With Varnish 4.0 I ended up implementing it with the ban command: sub vcl_recv { # ... # Command to clear complete cache for all URLs and all sub-domains # curl -X XCGFULLBAN http://example.com if (req.method == "XCGFULLBAN") { ban("req.http.host ~ .*"); return (synth(200, "Full cache cleared")); } # ... }
I'm looking for a way to clear the cache for all domains and all URLs in Varnish. Currently, I would need to issue individual commands for each URLs, for example: curl -X PURGE http://example.com/url1 curl -X PURGE http://example.com/url1 curl -X PURGE http://subdomain.example.com/ curl -X PURGE http://subdomain.example.com/url1 // etc. While I'm looking for a way to do something like curl -X PURGE http://example.com/* And that would clear all URLs under example.com, but also all URLs in sub-domains of example.com, basically all the URLs managed by Varnish. Any idea how to achieve this? This is my current VCL file: vcl 4.0; backend default { .host = "127.0.0.1"; .port = "8080"; } sub vcl_recv { # Command to clear the cache # curl -X PURGE http://example.com if (req.method == "PURGE") { return (purge); } }
How to clear complete cache in Varnish?
Use this to build Retrofit and provide cache as null the API will not cache anything. private OkHttpClient createOkHttpClient() { return new OkHttpClient.Builder() ... .cache(null) .build(); }
i know to disable cache of okhttp is to call Request.cacheControl(CacheControl.FORCE_NETWORK). Is it possible to set the cacheControl from OkHttpClient.class? Because i have 1 client for all my request. So i want to disable cache for all the request by disabling it from the okhttpClient
Disable Cache of okhttp
23 Try changing the version of the style.css file If included by giving the path in header then try to append version as <link style ........ href="...../style.css?v=1.5"... /> note the ?v=1.5 indicates the version if style.css is auto loaded then open your style.css file and add/change version as below: /* Theme Name: yourthemename Theme URI: yoururl Author: Vantage Tel Version: 1.5 . . . */ //change this version and upload file try pressing Ctrl+F5 to refresh your page once.. Share Improve this answer Follow answered Jul 1, 2014 at 5:34 YamuYamu 1,6521010 silver badges1515 bronze badges 7 Thanks, Yamu! But I've found what's causing problem. :) – user12109321358 Jul 1, 2014 at 15:48 2 @icy, if you found out what's causing the problem, could you please expand on it? I'd love to know how you solved this. Thanks! – luqita Sep 14, 2014 at 15:50 2 Hi Luqita! CloudFlare is causing me the problem on this case. So I manually clear the cache on it whenever I make changes on the .css file. – user12109321358 Sep 23, 2014 at 14:50 1 Cloudflare was the cause for me too. Clicking on Caching Level: Standard, then Purge Individual Files, finally entering: (...)/themes/mythemename/style.css?ver=62743ebf16e235fcdfbf89640f63baa0 solved the problem (after waiting around one minute and pushing Ctrl+F5) – chelder Oct 21, 2015 at 12:18 Amazed.Worked like a charm.+1 – Death-is-the-real-truth May 16, 2017 at 11:21  |  Show 2 more comments
I have made changes to style.css but the wordpress website is still showing old contents. I checked the file in FTP, and the changes in the file are there, but it's not showing on the website. I don't have any WP cache plugins. I also deleted cache in my browser and forces cache refresh through Ctrl+F5. :(
WordPress website still loading old style.css
40 Launch the Settings app from the Home screen of your iPhone or iPad. Scroll down and tap on Safari. Now scroll all the way to the bottom and tap on Advanced. Tap on Website Data. Notice here you can see how much space on your iPhone or iPad website data is taking up. Scroll to the bottom again and tap on Remove All Website Data. Confirm one more time you'd like to delete all data. Share Improve this answer Follow answered Jul 11, 2014 at 4:34 satishiOS25satishiOS25 53144 silver badges1111 bronze badges 1 1 This also seems to clear javascript files etc. from memory. I was having error problems with a javascript app which didn't respond to changes in the files, but when I checked on an iPad it was ok. Clearing the cache from the phone fixed it. – David Jul 20, 2017 at 23:49 Add a comment  | 
Please forgive me if this question sounds like clearing Safari cache/cookies in General->Settings. The issue is as follows: We have a custom webpage where user can upload his profile icon/image by choosing from Phone's photo library or taking a photo. The 1st time user uploads an image P1, it's uploaded successfully to server. If user refreshes the webpage and tries to upload a different image P2, P1 is uploaded to server. Problem persists even after clearing browser cache. If I kill browser and clear cache, then I'll be able to upload a new image. This problem does not occur on browsers on Google devices or on PC. Somehow iPhone browser remembers the image object and I need to find a way to clear it.
How do you clear image cache in iPhone 5S Safari browser?
20 Add the following methods to app/AppKernel.php (AppKernel extends Kernel) making them return your preferred paths: public function getCacheDir() { return $this->rootDir . '/my_cache/' . $this->environment; } public function getLogDir() { return $this->rootDir . '/my_logs'; } Share Improve this answer Follow answered Nov 29, 2011 at 16:15 nuqqsanuqqsa 4,49111 gold badge2626 silver badges3030 bronze badges Add a comment  | 
Because of deployment constraints, I would like to have the log and cache directories used by my Symfony2 application somewhere under /var/... in my file system. For this reason, I am looking for a way to configure Symfony and to override the default location for these two directories. I have seen the kernel.cache_dir and kernel.log_dir and read the class Kernel.php. From what I have seen, I don't think that it is possible to change the dir locations by configuration and I would have to patch the Kernel.php class. Is that true, or is there a way to achieve what I want without modifying the framework code?
Changing cache_dir and log_dir with Symfony2
Thanks kapep, good advice. Wasn't sure how to phrase as a question - but answering my own question I can do! First of all to ensure an image IS cacheable you must inspect the Response Headers to ensure the following headers are set to valid values: 'Cache-Control' is set to private or public. 'Expires' is a date in the correct format that is in the future. (eg. Thu, 21 Jun 2012 06:20:49 GMT) 'Last-Modified' is not more recent than the 'Date' header. 'Content-Disposition' is not set to "attachment;" If you're convinced the headers are set correctly and it still seems like the images aren't arriving from the cache, ensure the following: You are NOT F5 refreshing the page to check for caching as firefox will fetch new copies of the images if you refresh. Ensure you are reloading your page by navigating to another page and re-visiting the same page (as would be normal behaviour by one of your users). In your about:config (just type this in your address bar to access hidden settings) browser.cache.memory.enable = true and browser.cache.disk.enable = true
Closed. This question is off-topic. It is not currently accepting answers. Want to improve this question? Update the question so it's on-topic for Stack Overflow. Closed 10 years ago. Improve this question EDIT: Answer provided below. I've struggled for a couple of days to understand why Mozilla Firefox continually failed to retrieve images from its' cache as opposed to fetching new copies everytime I reloaded a page. Google Chrome didn't appear to have this issue, but that's because refreshing the page in Chrome does NOT force it to reload images (unless a CTRL-F5 is used). Below I've answered my own question and added some extra info that I hope will save someone else some time in getting their head around this issue.
Why does firefox not appear to be caching images? [closed]
Author class should implement Serializable Then you can use ObjectOutputStream to serialize the object and ByteArrayOutputStream to get it written as bytes. Then deserialize it using ObjectInputStream and convert back. ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(list); byte[] bytes = bos.toByteArray();
This question already has answers here: Closed 11 years ago. Possible Duplicate: Converting any object to a byte array in java I have a class that needs to be cached. The cache API provides an interface that caches byte[]. My class contains a field as List<Author>, where Author is another class. What is the correct way for me to turn List<Author> to byte[] for caching? And retrieve the byte[] from cache to reconstruct the List<Author>? More detail about Author class: it is very simple, only has two String fields. One String field is possible to be List<Author>0.
In Java, how to convert a list of objects to byte array? [duplicate]
26 I think you're looking for docker-compose pull: $ docker-compose help pull Pulls images for services defined in a Compose file, but does not start the containers. So docker-compose pull && docker-compose up should do what you want, without needing to constantly wipe your cache or hard-code container names outside of your compose file Share Improve this answer Follow answered Nov 27, 2018 at 14:03 Kristian GlassKristian Glass 37.9k77 gold badges4747 silver badges7373 bronze badges 2 2 How is this not the accepted answer? Does exactly what the question is asking. Thanks! – Thomas Vuillemin Mar 26, 2020 at 9:01 3 It does not do what the author asks for. It pulls the images for the services, but not base images specified in FROM in Dockerfiles – Ivan Krivyakov May 23, 2020 at 4:13 Add a comment  | 
I am using the latest tag in my Dockerfile in the FROM statement: # Dockerfile FROM registry.website.com/base-image:latest Every time my latest version changes I need to re-pull that image. Unfortunately, docker just takes the cached version. I tried docker-compose build --no-cache and docker-compose up --build --force-recreate project But it always looks like this: > docker-compose up --build --force-recreate project Building project Step 1/12 : FROM registry.website.com/base-image:latest ---> e2a0bcaf3dd7 Any ideas why it's not working?
How to make docker-compose pull new images?
LangDataService.isDataReady.then(function () { this.modalOn() }.bind(this));
This question already has answers here: How to access the correct `this` inside a callback (15 answers) Closed 4 years ago. I have a variable called LangDataService.isDataReady that is a Promise wawiting to be resolved. Upon resolve some logic will happen. How can I pass this into that Promise? LangDataService.isDataReady.then(function () { this.modalOn() }); I know i can cache var self_ = this; but I'm curious of other alternatives?
How to pass 'this' into a Promise without caching outside? [duplicate]
It is very simple to download and cache. The following code will asynchronously download and cache. NSCache *memoryCache; //assume there is a memoryCache for images or videos dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ NSString *urlString = @"http://URL"; NSData *downloadedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]]; if (downloadedData) { // STORE IN FILESYSTEM NSString* cachesDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *file = [cachesDirectory stringByAppendingPathComponent:urlString]; [downloadedData writeToFile:file atomically:YES]; // STORE IN MEMORY [memoryCache setObject:downloadedData forKey:urlString]; } // NOW YOU CAN CREATE AN AVASSET OR UIIMAGE FROM THE FILE OR DATA }); Now there is something peculiar with UIImages that makes a library like SDWebImage so valuable , even though the asynchronously downloading images is so easy. When you display images, iOS uses a lazy image decompression scheme so there is a delay. This becomes jaggy scrolling if you put these images into tableView cells. The correct solution is to image decompress (or decode) in the background, then display the decompressed image in the main thread. To read more about lazy image decompression, see this: http://www.cocoanetics.com/2011/10/avoiding-image-decompression-sickness/ My advice is to use SDWebImage for your images, and the code above for your videos.
I have an iphone application that displays both images and videos. The way the app is structured most of the images and videos will remain the same, with one occasionally added. I would like an opinion on the best and easiest method for asynchronously downloading and caching both images and videos, so that they will persist even after the application has quit. Also, I am only really concerned with IOS 5 and later. Here is some information I have found thus far, but I am still unclear about what the best method is, and if the cache will be persistent. This article about asynchronous image caching (old 2009) This article about NSURLCache SDWebImage (looks great but only works with images) AFDownloadRequestOperation This seems like a pretty common use case, so I'm really looking for best practices and or references to example code.
IOS How do I asynchronously download and cache images and videos for use in my app
I'm running into similar issues sometimes that JS and CSS is cached to long. The solution that works for me is, adding an versionnumber or timestamp of the last update to the filename as querystring. This way the browser sees the file as changed and it will download it again. Could be something like this for getting JS: http://yourdomain.com/content/js/functions.js?v=201232
I've been really digging into Google Page Speed, optimizing a lot of the sites I'm working on to score well on that -- and quite successfully I'm proud to say. The only downside I've come across is that by some of the caching stuff being done, small changes to JS and CSS tend not to cause a new copy of the files to download. Is there any way when changes are made to the JS, CSS (or other resources) to force a new copy to download?
How to Invalidate Web Browser Cache Content
I found a solution how to add a random hash with each file with the build process witch will clear the cache in the browser: // vite.config.js import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { hash } from './src/utils/functions.js' export default defineConfig({ plugins: [vue()], build: { rollupOptions: { output: { entryFileNames: `[name]` + hash + `.js`, chunkFileNames: `[name]` + hash + `.js`, assetFileNames: `[name]` + hash + `.[ext]` } } } }) // functions.js export const hash = Math.floor(Math.random() * 90000) + 10000; output: dist/index.html dist/index87047.css dist/index87047.js dist/vendor87047.js or dist/index.html dist/index61047.css dist/index61047.js dist/vendor61047.js ...
I have a side project with Vue.js 3 and vite as my bundler. After each build the bundled files got the same hash from the build before, like: index.432c7f2f.js <-- the hash will be identical after each new build index.877e2b8d.css vendor.67f46a28.js so after each new build (with the same hash on the files) I had to reload the browser hard to clear the cache and see the changes I made. I tried forcing a clearing with a different version number in the package.json, but: It does not work in the Vite/Rollup environment, it doesn't make sense to enter a new number by hand every time after a change. Question: Is there any way to configure vite to randomly create new hashes after a new build, or do you know another trick to clear the cache?
how to force vite clearing cache in vue3
Using Haneke, I wasn't able to retrieve file path for cached video. I handled it by saving video in cached directory. public enum Result<T> { case success(T) case failure(NSError) } class CacheManager { static let shared = CacheManager() private let fileManager = FileManager.default private lazy var mainDirectoryUrl: URL = { let documentsUrl = self.fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first! return documentsUrl }() func getFileWith(stringUrl: String, completionHandler: @escaping (Result<URL>) -> Void ) { let file = directoryFor(stringUrl: stringUrl) //return file path if already exists in cache directory guard !fileManager.fileExists(atPath: file.path) else { completionHandler(Result.success(file)) return } DispatchQueue.global().async { if let videoData = NSData(contentsOf: URL(string: stringUrl)!) { videoData.write(to: file, atomically: true) DispatchQueue.main.async { completionHandler(Result.success(file)) } } else { DispatchQueue.main.async { completionHandler(Result.failure(NSError.errorWith(text: "Can't download video"))) } } } } private func directoryFor(stringUrl: String) -> URL { let fileURL = URL(string: stringUrl)!.lastPathComponent let file = self.mainDirectoryUrl.appendingPathComponent(fileURL) return file } } Sample usage of this class looks like this: CacheManager.shared.getFileWith(stringUrl: "http://techslides.com/demos/sample-videos/small.mp4") { result in switch result { case .success(let url): // do some magic with path to saved video case .failure(let error): // handle errror } }
I am trying to download and play videos in a tableView like Instagram, vine or even facebook. What I am trying to achieve is a tableView where I display the videos and they auto download and play while scrolling. Like Instagram... So far I have managed most of that, but what I would like to change is the fact that every time I view a cell the video gets downloaded again and again.... Surely there must be a way to cache videos, or only download the same video once.... Like you do with SDWebImages for images. Also at the moment with it download every time I view the cell, the scrolling is terrible as you can imagine. Now I cannot seem to figure out how Instagram does it, but I am 100% sure they don't download the same video more than once!! If anyone has and advice or ideas, I'd love to hear them!! Many thanks in advance.
Is it possible to cache Videos? IOS - Swift
The following excerpt is taken from https://joblib.readthedocs.io/en/latest/memory.html#gotchas caching methods: you cannot decorate a method at class definition, because when the class is instantiated, the first argument (self) is bound, and no longer accessible to the Memory object. The following code won’t work: class Foo(object): @mem.cache # WRONG def method(self, args): pass The right way to do this is to decorate at instantiation time: class Foo(object): def __init__(self, args): self.method = mem.cache(self.method) def method(self, ...): pass
I would like to cache the output of a member function of a class using joblib.Memory library. Here is a sample code: import joblib import numpy as np mem = joblib.Memory(cachedir='/tmp', verbose=1) @mem.cache def my_sum(x): return np.sum(x) class TestClass(object): def __init__(self): pass @mem.cache def my_sum(self, x): return np.sum(x) if __name__ == '__main__': x = np.array([1, 2, 3, 4]) a = TestClass() print a.my_sum(x) # does not work print my_sum(x) # works fine However, I get the following error: /nfs/sw/anaconda2/lib/python2.7/site-packages/joblib/memory.pyc in _get_output_dir(self, *args, **kwargs) 512 of the function called with the given arguments. 513 """ --> 514 argument_hash = self._get_argument_hash(*args, **kwargs) 515 output_dir = os.path.join(self._get_func_dir(self.func), 516 argument_hash) /nfs/sw/anaconda2/lib/python2.7/site-packages/joblib/memory.pyc in _get_argument_hash(self, *args, **kwargs) 505 def _get_argument_hash(self, *args, **kwargs): 506 return hashing.hash(filter_args(self.func, self.ignore, --> 507 args, kwargs), 508 coerce_mmap=(self.mmap_mode is not None)) 509 /nfs/sw/anaconda2/lib/python2.7/site-packages/joblib/func_inspect.pyc in filter_args(func, ignore_lst, args, kwargs) 228 repr(args)[1:-1], 229 ', '.join('%s=%s' % (k, v) --> 230 for k, v in kwargs.items()) 231 ) 232 ) ValueError: Wrong number of arguments for my_sum(self, x): my_sum(array([1, 2, 3, 4]), ) was called. Is there a way to cache a member function of a class using Memory or any other decorators?
How to use joblib.Memory of cache the output of a member function of a Python Class
By default, the bulk of your app should be cached by the browser until a new version of it is generated by your build process. It might help to understand the GWT bootstrapping model to understand how this works. The first script your client requests, your-app-name.nocache.js, is not cached, and it does nothing except check the browser's user agent and capabilities, and make a second request for the relevant app JS. At this point, the script it requests should be cached by the browser if it's been requested before. This is a {indistinguisable-numbers-and-letters}.cache.html file. When you redeploy your app, the nocache.js file will be executed and ask for a different cache.html file from the server, which will not already be present in the cache, but which will get cached by the browser once it is downloaded. Are you doing anything unusual with deferred binding, or with caching headers on your server? This might potentially be causing your nocache.js file to get cached after all, which would make it request old cache.htmls from the browser cache.
I have a GWT app deployed onto our client's machines. As an ongoing development alongside, we have to release new improved versions of the application fron time to time. Everytime we release a new version we often run into the problem where the client's browser has cached the old scripts scriptsand for a while it behaves strangly as the data it is trying to work with is not quite compatible with it. What is the best way to overcome this problem. Currently I have to tell the users to clear their browser's cache for a new release but it would be nice they don't have to do this.
Stop browser scripts caching in GWT App
HTTP_IF_MODIFIED_SINCE is the right way to do it. If you aren't getting it, check that Apache has mod_expires and mod_headers enabled and working properly. Borrowed from a comment on PHP.net: $last_modified_time = filemtime($file); $etag = md5_file($file); // always send headers header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT"); header("Etag: $etag"); // exit if not modified if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time || @trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) { header("HTTP/1.1 304 Not Modified"); exit; } // output data
I am using a PHP script to serve files. I would like to be able to send back a 304 not modified header in my http response if the file has not changed since the client last downloaded it. This seems to be a feature in Apache (and most other web servers), but I have no clue how this can be implemented through PHP. I have heard of using $_SERVER['HTTP_IF_MODIFIED_SINCE'], but this variable does not seem to appear in my $_SERVER super array. My question is not how to return a 304 header, but how to know that one should be returned. Edit: The problem is that my $_SERVER['HTTP_IF_MODIFIED_SINCE'] is not set. This is the content of my .htaccess file: ExpiresActive On ExpiresByType image/jpeg "modification plus 1 month" ExpiresByType image/png "modification plus 1 month" ExpiresByType image/gif "modification plus 1 month" Header append Cache-Control: "must-revalidate" <IfModule mod_rewrite.c> RewriteEngine On RewriteCond $1 !^(controller\.php) RewriteRule (.*\.jpg|.*\.png|.*\.gif) controller.php/$1 </IfModule> HTTP_IF_MODIFIED_SINCE still does not appear in the $_SERVER super array.
304: Not modified and front end caching
Expires is a content header. Try this instead: actionExecutedContext.Response.Content.Headers.Expires = DateTimeOffset.Now.AddDays(7);
I'm pretty sure that "Expires" is valid HTTP Response Header type. But when I try to set it in my code: (this is in an ActionFilter.OnActionExecuted method) actionExecutedContext.Response.Headers.Add("Expires", (DateTime.Now + Timespan.FromDays(7)).ToString("R")); I end up with an exception: InvalidOperationException: Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.
How to add an Expires response header to a WebAPI Action response?
This is a known issue in LESS. See the github issue here: https://github.com/cloudhead/less.js/issues/47 I know it doesn't solve your problem directly, there is a workaround listed there, put the following line above your less.js import: <script type="text/javascript">var less=less||{};less.env='development';</script> <script src="less.js"></script> and things should generally work.
Files: listing.less (text/css) style.less (text/css) Tools: Firefox Firefox addon httpFox for inspecting http headers Chrome I have a css file named listing.less that contains the following: @import "/orb/static/less/style.less"; When I call listing.less everything works fine, style.less is imported. Subsequent requests for listing.less results in a 304 cached response. That's fine. However, the imported style.less doesn't show up as a cached response. Instead, I find it in the browser's localstorage. The bigger problem is if I make a change to style.less then hit refresh the browser will not update the style. The style.less will refresh only if I delete it from localstorage or touch listing.less on the server. Is that the nature of @import? Do I need to touch listing.less or delete style.less from localstorage every time I want to update style.less? How can style.less be forced to refresh?
Why does an imported css file get stored in localstorage and not refresh like a linked css file?