TF2 Backpack items not showing up — stuck on loading

Question: I can't access any of my items in my TF2 backpack when I'm in the game. This happens on every page of my backpack:

Is there any fix to this?
Comment: It *could* be because the media.steampowered.com server (which is where all the backpack images are stored) went down while you were checking your backpack.  All I can suggest is to try again later.
Comment: @Powerlord My first page of my backpack shows up, then when I click another page none of the items show up (looks like the picture above) and then when I go back to the first page it looks like the same thing. So none of my items have shown up. I have waited for weeks now and re-installed tf2 but the problem still persists.
Comment: @VishwaIyer - I'd put that down to caching - It's managed to get your first page of items, but not the rest. Is this still an issue?
Comment: Yes it is. I've resorted to re-downloading the game (again), so we'll see what happens.
Comment: @Robotnik Ok reinstalling the game didn't help. The same problem is showing up. It's even worse now, none of my backpack icons will show up.
Comment: I have reinstalled the game a second time. I have removed any custom files (huds, sounds, cfgs, etc.), but the item icons still don't show up. I get the same problem as shown in the picture.
Comment: Any firewalls, proxy's or parental controls installed (or any other app that can block internet access)?
Comment: @aman207 There aren't any.
Comment: Are you able to view your TF2 inventory in your steam profile?  Could you link us to it?
Comment: Here's my inventory: http://steamcommunity.com/id/vishiswoz/inventory/. I can view my inventory there. I can't view it in the game.
Answer: I have also experienced this issue occasionally, and it's highly likely that the TF2 Item servers were under heavy load, not responding or even just simply down at the time you attempted to load your backpack.
If this bug happens again, you can check the status of the TF2 Item servers on the TF2 Trade Lists site or various other TF2-centric sites that regularly check up on the servers. If you continue to experience issues over an extended period of time, try contacting Steam Support.
Answer: I had the same problem with this. While playing a map, I discovered this command that might help you:

Open up Developer console
Now type in tf_time_loading_item_panels 0.0005
It might lag a bit, but it will then load up your items
Answer: I found a fix:

Back up all your custom files or any another files you want to keep.
Delete the TF2 folder ProgramFiles/Steam/steamapps/common/TeamFortress2
Delete local content.
Reinstall TF2 and put back your custom files or anything else.

This will completely reset TF2 and fix your backpack icons.
Enjoy.
Comment: No, this is not a simple reinstall, this is a complete powerwash.
Comment: I have reinstalled tf2 before, but i haven't deleted anything, but i'm still getting this error. are you sure that this will work?
Comment: Removing the local content dose not re install the game, it simply removes the active files being used by steam, deleting the game folder removes it completely on steam. Don't worry, this wont delete your backpack or anything crazy, all that stuff is on the cloud. It will create basically a brand new version of tf2 for you to use. It worked with me. I did have a few problems with the custom folder but that was on me, if it dose not work however then please, be sure to tell me
Comment: Yes this didn't work for me. Still cannot see my backpack items.


mod_rewrite not working correctly locally

Question: I have the following lines in my .htaccess:
RewriteEngine On
RewriteBase /new
Options +FollowSymlinks
Options -Indexes

#Shopping Redirects
RewriteRule ^shopping-bag?$ cart.php
RewriteRule ^checkout?$ checkout.php
RewriteRule ^product/([^/\.]+)/?$ product.php?fine_leather=$1 [NC,QSA,L]

Now, all of this works great on the production server, (last line will appear as http://www.domain.com/product/this-is-a-product) but locally, the first two lines work fine but the last doesn't. It doesn't seem to passing the GET variable :(
Any ideas/suggestions to fix this? I need to get the pretty URL's fixed but don't really want to work on the server until I know that they are working correctly.
Answer: Try this code :
RewriteRule ^shopping-bag?$ cart.php [L]
RewriteRule ^checkout?$ checkout.php [L]
RewriteRule ^product/(.+)$ product.php?fine_leather=$1 [NC,QSA,L]

Comment: still no joy i'm afraid :(
Comment: Just added the first parts, there are a few other redirects going on but all these are simple redirects, nothing that needs slugs etc.
Comment: Sincerely, I don't see where the problem come from.
Comment: Nor do I, another one of my colleagues has the same issue :/ thanks for taking a look though. Appreciate it!


ant calling rake

Question: I think I'm having issues with my ant not knowing where to find my Rakefile
I have the following folder structure.
build.xml
[subfolder]/Rakefile

Within my build.xml I have the following task.
 <target name="client">
    <taskdef name="rake" classname="org.jruby.ant.Rake" classpath="../shared-lib/jruby.jar"/>
   <rake task="jar"/>
  </target>

I'm getting the following error.
build.xml: Could not create type rake due to org.jruby.embed.EvalFailedException: no such file to load -- ant/tasks/raketasks

Any help apprec
Answer: This appears to be a comprehensive article about the combination (both ant from rake and rake from ant):
http://www.engineyard.com/blog/2010/rake-and-ant-together-a-pick-it-n-stick-it-approach/
Do make sure of the following:

the Rake task classpath includes any dependencies that JRuby has
the Rakefile is in root directory (i.e. basedir)

By default when you execute the Rake command from the command line it looks in the current directory for the Rakefile.  If your root Rakefile does nothing other than change directories and call the other Rakefile it should be better.
Comment: I've created a build.xml in the same dir as my Rakefile but still running into the same problems.
Comment: Ok so you put me on the right path. I was using a standard jruby.jar but I needed the the jruby-complete.jar In addition for some reason I needed to set this jar to be in ants command line CLASSPATH. After all that my Rakefile would run.

ant calling rake


problems with spwaning process from within uberjar

Question: When the following Clojure sample program is packed into a standalone uberjar (via boot-clj), the execution of java -jar app.jar behaves different from invoking the -main function from within the development repl.
(ns bat-man.core
  (:require [clojure.java.shell :refer [sh]])
  (:gen-class))

(defn -main [& args]
  (prn (sh "echo" "test")))

What happens, is that the result {:exit 0, :out "test\n", :err ""} is printed immediately to stdout, but after that it takes along time, maybe half a minute, until the program actually exits.
Which is not the case, when the program is modified to just print some output wihtout invoking sh.
Within the development repl, everything is as expected, the function finishes immediately after printing. How can that be explained/fixed?
Update: Here is an excerpt from ps aux taken meanwhile the program is taking its time to finish:
unsername         8730  5.4  2.0 3643576 80052 pts/8   Sl+  13:25   0:01 java -jar /path/to/app.jar

Answer: clojure.java.shell/sh uses a future behind the scenes, so you need to call (shutdown-agents) to shutdown background threads.
Comment: @OlegTheCat Yes, this should work.  See this answer: http://stackoverflow.com/questions/3393497/future-promises-in-clojure-hangs-on-me
Comment: Does this solution work? IIRC futures and agents use different thread pools.
Comment: Seems to remain the same behavior. Maybe helpful, from the docs of shutdown-agents: "Running actions will complete, but no new actions will be accepted"


Real semisimple Lie group with infinitely many connected components?

Question: Is it possible for a real semisimple Lie group to have infinitely many connected components? If so, what is an example?
Thanks!
Comment: What do you mean exactly by semisimple? (For a popular definition, the condition depends only on the Lie algebra, so the number of connected components is entirely immaterial)
Comment: You might have meant a Lie group whose category of finite-dimensional representations is semisimple. This rules out many possible values of $\pi_0$. Anyway, presumably Mariano asked precisely because that definition places no constraints on the connected components whatsoever.
Comment: Yes I was thinking of a semisimple Lie group as that which has a semisimple Lie algebra. Are there other frequently used definitions?
Answer: Yes,
$$\mathrm{SL}(2,\mathbb{R})\times\mathbb{Z}.$$
(Or any real semisimple group times a countably infinite discrete group.) The point is that
$$\mathrm{Lie}(G\times H)=\mathrm{Lie}(G)\times\mathrm{Lie}(H)$$
and $\mathrm{Lie}(H)=\{0\}$ for a discrete group $H$.
Comment: Are there real semisimple Lie groups with infinitely many components that are not of the form $G\times H$ where $H$ is discrete infinite? (I'm trying to understand to what extent one can just think about semisimple groups that are almost-connected.)
Comment: I would love to have an example too.


Could joist bridging prevent movement and noise in my tile floor?

Question: Brand new tiles installed by contractor 4 years ago in kitchen, bathroom and also in a new house extension on pillars.  Tiles started clicking in the extension during first winter.  Now the grout is clearly starting to deteriorate.  Obviously the extension will need to be redone completely.
Since then a few tiles started clicking in the bathroom and in the kitchen but also only winter.
Subfloor information :

The house extension on pillars is brand new so I hope everything is repecting modern standards... which is weird because the problem is worst there!
In the house I have 2x8 joists with plank flooring and plywood on top of it. Don't know plywood thickness.

Since the problem is happening on two different types of subflooring I think the tiler somewhat messed up with the glue!
Questions :

Why it clicks only in winter?  Humidity, temperature?  There is a
big difference between winter and summer temperature here.
If possible I would like to fix the kitchen and the bathroom before it
gets worse.  Since the tiles click only in winter I am wondering if
bridging the joist could help.  If so, should I do it in summer when
it is not clicking?
Comment: @isherwood Well the house extension on pillars is brand new so I hope everything is repecting modern standards... but the problem is worst there! In the house I have 2x8 joist with plank flooring and plywood on top of it. Don't know plywood thickness. Since the problem is happening on two different types of subflooring I think the tiler somewhat messed up with the glue!
Comment: Please put that information in your question.
Comment: "Extension on pillars" does that mean that there's empty space, exposed to the weather underneath the floor (i.e. the posts/pillars are exposed), or does that mean that there were pillars of driven steel or poured concrete acting as foundation footers, and the extension is on a slab/crawlspace? The amount of outside air getting under the floor may be more than the insulation can adequately protect against.
Comment: @FreeMan Yes there is free air flowing under the extension but it should be insulated properly.
Answer: The floor under your tile is moving.  Likely there is enough pressure from the joists in the summer to keep things relatively steady but clearly when things dry out in the winter there is more movement and you get the audible clicking.
The problem is that tile with grout is very intolerant of any movement at all.  The grout will quickly crack and start to pop out of the joints as you have seen.
No easy fix in my opinion.  Your contractor should have ensured that the floor was solid and without any movement before tiling over it.  It seems that was not done.
Now the best you can do without pulling up the tile and fixing the root cause is a band-aid fix.  Remove the grout and re-grout with a more flexible type of grout, such as latex grout. This will just extend the time until you have to do it again but possibly by then you'll be tired of this flooring and can have it done properly.
Some bridging MAY help but there is no guarantee.  It's worth a try at this point.
Comment: And do you think I should try to do that in summer?
Comment: If the problem is the joists moving, then bridging will help.  But you really won't know until you try it.  There is no point in waiting until summer in my opinion.
Answer: No, adding bridging (or blocking) will not stop the movement that is causing your tiles to move and crack. In fact, it could cause more clicking and add noise to your floor. (More pieces of wood deflecting and moving.)
Bridging keeps the joists from laying over on their sides when overstressed. They do not help the deflection which is causing the movement (and cracking).
Obviously you do not have a problem with the joists laying over on their sides or they would have failed.
Often people suggest adding bridging or blocking to "transfer" the floor loads to adjacent joists. This is minimal, especially if you have a subfloor AND underlayment.
Tile floors require a very stiff structural floor system, which means the normal deflection of 1/280 or 1/360 should be increased to 1/720. Bridging will not do that.
You mentioned the noise occurs during the winter and not the summer. This could be due to humidity allowing the "wetter" winter joists to deflect more.
Rather, I'd suggest "sistering" another joist along side the existing joists to help stiffen the floor by decreasing the deflection. You didn't give the composition of your structural floor construction, so I can't tell you how overstressed the joists are currently, but you do not have to extend the new joists onto a support. Rather, I'd add another 2x8 joist to within 12" or so of a bearing point.
Comment: What about 3/4" plywood girdles 3' long in the middle of the span screwed and glued to each side of the joists?  I recently had an 18' 2x10 notched 4" at the top in the middle of the span and the engineer came up with this to bring it back to acceptable.
Comment: @FreshCodemonger Yes, the middle third of the span is where the bending is greatest, but the op has not identified the length of the joists nor spacing.
Comment: @LeeSam About 12 feet span and 14 inches spacing.
Comment: @ForguesR It appears the joists are undersized. Depending on the thickness of the tile and thickness of the mortar bed, the Dead Load could be about 25 lbs. per square foot (psf). If so the total load on each joist could be about 90 lbs. per linear foot. If so, a 2x8 at 16" on center could easily span 12' , depending on the species and grade of the joists, (except for "Utility Grade" ). The problem is the joists are deflecting too much for a tile floor. This floor joist is deflecting about .4" for a 12' span and it should be about .2" to keep the tile from cracking.


C - using pthread and waiting for a return value

Question: I am currently working on a multi-client server that uses select() to handle multiple clients. However, when a client sends a message that needs heavy calculations, I have to create a a new thread using pthread_create() so that my server can remain responsive to other messages from clients. Once the calculation is done for that client, I need to be able to return a message to the client. But I am not sure how I can know if that thread is finished and how to get it's final result. Obviously I cant use pthread_join() as that blocks my server program while running that new thread. So does C offer a function that I can use to get the end result of that child thread? I would like to avoid using Global Variables as well.
Comment: 'So does C offer a function that I can use to get the end result of that child thread?' Yes, select().
Comment: Alternatively, pass the thread the relevant fd and have it reply directly.
Comment: @ThingyWotsit i thought select() only works on file descriptors :|
Answer: You can just check if the thread has finished before joining it from the main thread (which will be non blocking)
You should get how to do it from here : How do you query a pthread to see if it is still running?
Otherwise you can probably just send back the answer from the child thread, you can pass connection information as parameter of the thread function.
Answer: If you want the child thread to wake up the thread that is waiting in select() when it has finished processing, you can use pipe() to create a pipe.  The thread calling select() adds the read side of the pipe to its file descriptor set, and the child thread writes to the write side of the pipe when it has finished its work.
You can even have it send the result over the pipe, if the result isn't too large.


Can I make the contractor redo a roofing job because he didn't replace delaminated plywood?

Question: My wife and I recently moved into our first home.  It's a raised ranch in CT that was built in 1967.  I've been doing a lot of "refreshing" myself inside; however, I hired a roofing contractor to replace our end-of-life roof.  It was a two-layer job, so we had to go with the rip-and-replace method.  The contractor I hired is local and well established (32 years).  He gave us a quote for the full rip and replace including new drip edge, vent boots, tar paper and 6 feet of ice blocker.  He also had as a line item an additional cost for any plywood that would need to be replaced.
The roof has what I assume to be its original 3/8" plywood sheathing and two layers of shingles (sounds about right: if you figure each roof lasted twenty years or so, the math works).  Regardless, we purchased new GAF Timberline shingles and he went to work.  The whole job took him (and his crew of two others) two days to complete.  He told me that all the plywood looked great, there was no rot, and nothing had to be replaced.  "Great", I thought.
That brings us to tonight. I went up into the attic to put some stuff up there and started looking around. It's fairly obvious to my untrained eye that the plywood is delaminated in some areas. I would've gladly paid the extra money to have the plywood replaced (even all of it if need be) to have a solid roof that would last 30–40 more years. I now fear we have great new roofing shingles over old crappy plywood that won't last. Our biggest fear is that if we eventually sell the house the inspector will say that the roof sheathing is no good and needs to be replaced.
I immediately placed a call to the contractor when I noticed this, however it was already 10pm tonight so I was unable to reach him. I assume he'll call me back, but I'm looking here for advice and guidance if anyone has experienced anything like this in the past.  I'm not sure what I should or could expect from him at this point in the game.
I did realize that I had never noticed the delamination in the attic before. I'm thinking that the driving of all the new nails through it, plus the foot traffic on the roof made it much more noticeable. It's not horrible (there aren't pieces of the outside laminate falling off), but there are definite spots where the nails have ripped chunks out, and there are areas you can press on and just feel the spaces between. It's also very flexible and spongy between the rafters, so much that you can deflect it with you hand pressing outwards fairly easily.
Comment: You mentioned you only noticed the delamination from in the attic -  if it was not visible from above, how would the contractor have known? Its unlikely they would "test" every single board...  Usually they only replace them if they are visibly degraded, sagging or otherwise damaged
Comment: If you're just looking for some quick advice, or to discuss a problem. There are usually helpful folks hanging around in [chat](http://chat.stackexchange.com/rooms/111/home-improvement), that might be able to help you out.
Comment: Welcome to the site.  I'm having a difficult time figuring out what you're asking. It sounds to me like the only person that can actually answer your question, is the roofer himself.  Only he can tell you what he's willing to do to make you happy.  In the future if you have any questions about the tools and techniques used to complete a job, we are always willing to help. Just keep in mind this is a question and answer site, not a discussion forum. We tend to favor specific answerable questions, since they are much easier to answer and tend to be more useful.
Answer: I wouldn't worry too much about it.  The plywood is not typically supporting a load of more than the paper and asphalt shingles that were placed, even more so if you have a considerable pitch on your roof to where it would be difficult or impossible for a person to walk on.  It basically serves so that you have something to nail the shingles down securely.
Most newer homes use plywood, I have an older home that used what looks like rough cut deck planks and those are mostly still original.  The last time I had my roof replaced, they had to change out a few boards that were terribly dry rotted and some that were badly damaged from previous water damage by the oh-so responsible homeowners who had the home before me.  Other older boards look noticeably damaged by the most recent nails but they continue to hold down the shingles and I would still feel safe to stand on my roof.
As long as the shingles are doing their job then the plywood will not be exposed to any water, and as long as your attic has good ventilation during the summer time then you should have nothing to worry about for the next 15-20 years at least.
Answer: As much as you probably don't want to hear this, I am quite sure you are stuck with the job as it is. The time to decide if the sheathing needed to be replaced or over sheathed was when the roof was stripped clean.
My first observation is that you said you had 3/8" plywood. 3/8" would be the absolute minimum size, 1/2" or 5/8" T&G would have been better, but it is what it is. The problem with thin sheathing is that you will often see sagging between the rafters over time. If your new roof looks straight and flat, then the roofer did what he said he would do. If you have any waves between rafters, then you may have a legitimate reason to complain.
My advice to any one contemplating a roof job is to discuss with your contractor before the job begins and establish that he/she will evaluate the sheathing inside and out and then show you the conditions and discuss options before moving forward. This means you need to be available so the contractor doesn't have to stop work and waste time waiting for you.
Comment: Thank you for the feedback. I took the days off when the work was being done so I could be there in case there were any issues. We had spoken about replacing any sheeting that needed it, and was quoted on the per sheet price. The contractor specifically stated that none needed to be replaced while the roof was stripped. I took his word for it, as he's been in the business for 32 years vs my 0. He's fully licensed and insured if that makes any difference at all. Would having an inspector check it out give me any more leverage? If the inspector deems it inadequate, wouldn't it have to be fixed?
Comment: sounds like even if an inspector questioned the sheathing, you may have to take this one to court. I guarentee the roofing contractor is not going to strip a new roof because the old sheathing may be marginal. That is a judgement call.  If the roof is straight, not saddled, you are probably done.


Wait until summer to seal?

Question: I have zero home improvement/DIY experience. I got someone recently to carry out an unrelated repair on my porch, and he offered additionally to apply  sealant to the exterior porch window frames, as some patches were exposed to rain as the sealant seemed to have pealed.
He scraped off what was there and said he would apply mastic, and it looked fine at first. However it didn't dry and after a few days had bunched up (as below). (I asked him to come back but have given up there). I assume he used a product intended for indoor use as the vertical sections look ok but the horizontal sections look like this (i.e. similar to how it was before):

Should I scrape off what he applied and put on some caulk? It being December and me being in London, it's been raining, so I assume I'd be locking in some moisture.
Or better to wait? It would have been rained on a fair bit more by then, but perhaps after a dry spell in the summer when the wood's hopefully had time to dry out a little?
(Perhaps I should remove the top few millimetres of wood but don't have the confidence to do that especially as the pane of glass is a kind no longer supplied.)
Answer: It would be best to wait for a couple of dry, sunny days before applying exterior sealant, but if you fear that rain will enter through the window edges it may be necessary to execute an emergency repair. If you have a 2-3 hour window of no rain in the forecast start the repair by removing only the sealant on the window edges that show the easiest routes into the house (lower horizontal edges?). The sealer will remove easier if you slice both edges with a razor knife. Coax the sealer off with a putty knife. Once removed apply (in order of best at sealing): 1) 100% silicone caulking, 2) window putty or glazing and 3) latex caulking. Use a caulk gun for all 3 suggestions. 100% silicone is hard to shape but seals the best. #2 and #3 are the easiest to work with; they seal sufficiently, but need at least 4-6 hours to become rain repellent (a hair dryer will shorten dry time).

Wait until summer to seal?


Call an anchor tag via javascript

Question: I am using thick box 3.1 to load a pop up. It working well by using in the following way:
 TEST

If we click on the TEST now then the popup is working well and good.
Now my prob is: I need to call this popup in form load using JavaScript.
I do something like below:

it's just redirecting to that particular file. But not showing in the pop up.
What is the possible way?
thanks in advance
Answer: Try this:
Test

Comment: thanks simeon, This is what i exactly wan't. Thanks a lot man.
Answer: You can do this without changing your markup, like this:
$(function() {
  $('a[href=filename.php]').click();
});

Answer:  TEST

Comment: @James: Yeah... true. My focus was on using `click()` as the answer to the question, not not on making a standalone fully functional example.

Call an anchor tag via javascript


No ConcurrentList in .Net 4.0?

Question: I was thrilled to see the new System.Collections.Concurrent namespace in .Net 4.0, quite nice!  I've seen ConcurrentDictionary, ConcurrentQueue, ConcurrentStack, ConcurrentBag and BlockingCollection.
One thing that seems to be mysteriously missing is a ConcurrentList<T>.  Do I have to write that myself (or get it off the web :) )?
Am I missing something obvious here?
Comment: ConcurrentBag (https://msdn.microsoft.com/pt-br/library/system.collections.concurrent(v=vs.110).aspx)
Comment: @RodrigoReis, ConcurrentBag is an unordered collection, while List is ordered.
Comment: How could you possibly have an ordered collection in a multithreaded environment?  You would never have control of the sequence of elements, by design.
Comment: Use a Lock instead
Comment: there is a file called ThreadSafeList.cs in the dotnet source code which looks alot like some code below. It uses ReaderWriterLockSlim also and was trying to figure out why use that instead of simple lock(obj)?
Comment: ok i see it's a performance improvement since reader locks don't really lock unless there's a write going on, useful if you have multiple threads reading the same List.
Answer: I gave it a try a while back (also: on GitHub). My implementation had some problems, which I won't get into here. Let me tell you, more importantly, what I learned.
Firstly, there's no way you're going to get a full implementation of IList<T> that is lockless and thread-safe. In particular, random insertions and removals are not going to work, unless you also forget about O(1) random access (i.e., unless you "cheat" and just use some sort of linked list and let the indexing suck).
What I thought might be worthwhile was a thread-safe, limited subset of IList<T>: in particular, one that would allow an Add and provide random read-only access by index (but no Insert, RemoveAt, etc., and also no random write access).
This was the goal of my ConcurrentList<T> implementation. But when I tested its performance in multithreaded scenarios, I found that simply synchronizing adds to a List<T> was faster. Basically, adding to a List<T> is lightning fast already; the complexity of the computational steps involved is miniscule (increment an index and assign to an element in an array; that's really it). You would need a ton of concurrent writes to see any sort of lock contention on this; and even then, the average performance of each write would still beat out the more expensive albeit lockless implementation in ConcurrentList<T>.
In the relatively rare event that the list's internal array needs to resize itself, you do pay a small cost. So ultimately I concluded that this was the one niche scenario where an add-only ConcurrentList<T> collection type would make sense: when you want guaranteed low overhead of adding an element on every single call (so, as opposed to an amortized performance goal).
It's simply not nearly as useful a class as you would think.
Comment: And if you need something similar to `List` that uses old-skool, monitor-based synchronisation, there's `SynchronizedCollection` hidden away in the BCL: http://msdn.microsoft.com/en-us/library/ms668265.aspx
Comment: One small addition: use the Capacity constructor parameter to avoid (as much as possible) the resizing scenario.
Comment: The biggest scenario where a `ConcurrentList` would be a win would be when there isn't a whole lot of activity adding to the list, but there are many concurrent readers.  One could reduce the readers' overhead to a single memory-barrier (and eliminate even that if readers weren't concerned about slightly-stale data).
Comment: @Kevin: It's pretty trivial to construct a `ConcurrentList` in such a fashion that readers are guaranteed to see consistent state without needing any locking whatsoever, with relatively slight added overhead.  When the list expands from e.g. size 32 to 64, keep the size-32 array and create a new size-64 array.  When adding each of the next 32 items, put it in slot a 32-63 of the new array and copy an old item from the size-32 array to the new one.  Until the 64th item is added, readers will look in the size-32 array for items 0-31 and in the size-64 array for items 32-63.
Comment: Once the 64th item is added, the size-32 array will still work for fetching items 0-31, but readers will no longer need to use it.  They can use the size-64 array for all items 0-63, and a size-128 array for items 64-127.  The overhead of selecting which one of two arrays to use, plus a memory barrier if desired, would be less than the overhead of even the most efficient reader-writer lock imaginable.  Writes should probably use locks (lock-free would be possible, especially if one didn't mind creating a new object instance with every insertion, but the lock should be cheap.
Comment: One addition I'd like to add. You can avoid the resizing problem by making a linked-list of "chunks". Of course, this adds a lot of complexity, but allows for relatively close to O(1) lookups and additions, and can also make it so you don't have to lock the entire structure upon an `Insert` or `RemoveAt`.. But again, it's massively more complex to implement and will never meet the performance of List
Comment: @supercat You could synchronize for that scenario using a ReaderWriterLock http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlock(v=vs.110).aspx
Comment: @supercat Re: `ConcurrentList would be a win would be when there isn't a whole lot of activity adding to the list, but there are many concurrent readers` and `especially if one didn't mind creating a new object instance with every insertion`. Exactly for use cases like this, which I've had to deal with increasingly often recently, the `CopyOnWriteSwapper` in my answer is a generic solution that performs locklessly fast for all reads and iterations, and allows the use of arbitrary data structure, i.e. you can keep your O(1) index lookup.
Comment: @EugeneBeresovsky: The `CopyOnWriteSwapper` implementations I've seen generally have O(N^2) behavior for building.  The `ConcurrentList` I'd have liked to have seen would have retained amortized constant `Add` time.  Building it might not have been as fast as building a synchronized list, but reads would avoid synchronization overhead.
Comment: @supercat The one I provide [below](http://stackoverflow.com/a/30769838/709537) is generic in that sense. The cost in my example `new List(existing)` would be O(n). Not as bad as O(n^2), but bad enough if the list is huge, or you modify it often. If you need lockless read access AND something like O(log n) performance for additions, I guess [Immutable](https://msdn.microsoft.com/en-us/library/dn385366%28v=vs.110%29.aspx) it has to be.
Comment: @EugeneBeresovsky: IMHO, .NET would have benefited greatly from "add-only" list and dictionary types, since such types only need can easily be written to allow lock-free read access and O(1) write access; further, dictionaries of such type can cheaply *guarantee* that items will be enumerated in the order they were added (if an enumeration is started just as items are added, behavior will be consistent with the items having been added either before or after the enumeration).  If there's no need to actually remove items from a collection, types that don't need to support removal could...
Comment: ...easily provide useful guarantees (always-consistent state for reading, and in-order enumeration) which cannot be readily satisfied in collections that allow deletions.
Comment: @supercat for what it's worth, ConcurrentDictionary is now lock free for reads, performs essentially the same as a normal dictionary for lookups and allows safe enumeration while being modified.
Comment: @MikeMarynowski: I don't think `ConcurrentDictionary` offers any particular guarantees about enumeration order.  Otherwise, though, it seems like a fine class.  Add-only lists and dictionaries should each include a member not present in current interfaces; `AddAndGetIndex` would add an item and return its insertion order, and for dictionaries there should also be a `GetItemIndex` to yield an insertion order by key.  An immutable wrapper on an add-only dictionary with such a function could simply wrap the original dictionary along with a count of how many items were in it when wrapped...
Comment: ...and treat any items added after that as though they don't exist.
Comment: @supercat That is correct, though I think what is there is sufficient for most uses of a concurrent dictionary, even in read only scenarios. Just curious, what usage scenario would require you to guarantee an enumeration order on a dictionary? If you want an add-only dictionary with "snapshot" enumeration behavior and 100% dictionary read performance I made an implementation of that here:

http://www.singulink.com/CodeIndex/post/fastest-thread-safe-lock-free-dictionary
Comment: @MikeMarynowski: A typical usage scenario would be a live status report of unique items observed thus far.  One could use a concurrent dictionary to establish which items are unique and then add them to a concurrent list, but it should be possible to have one data structure serve both purposes.
Answer: What would you use a ConcurrentList for?
The concept of a Random Access container in a threaded world isn't as useful as it may appear. The statement
  if (i < MyConcurrentList.Count)
      x = MyConcurrentList[i];

as a whole would still not be thread-safe.
Instead of creating a ConcurrentList, try to build solutions with what's there. The most common classes are  the ConcurrentBag and especially the BlockingCollection.
Comment: @dcp - yes this inherently non-thread-safe. ConcurrentDictionary has special methods which do this in one atomic operation, like AddOrUpdate, GetOrAdd, TryUpdate, etc. They still have ContainsKey because sometimes you just want to know if the key is there without modifying the dictionary (think HashSet)
Comment: @dcp - ContainsKey is threadsafe by itself, your example (not ContainsKey!) just has a race condition because you do a second call depending on the first decision, which may at that point already be out of date.
Comment: Henk, I'm not agree. I think that there is a simple scenario where it could be very usefull. Worker thread write in it will UI thread read and update interface accordingly. If you want to add item in a sorted fashion, it will require random access write. You could also use a stack and a view to the data but you will have to maintain 2 collections :-(.
Comment: @Alan: There's no way to implement that without locking the list. Since you can already use `Monitor` to do that anyway, there's no reason for a concurrent list.
Comment: Good point. Still what I am doing is a little more mundane. I am just trying to assign the ConcurrentBag into an IList. I could switch my property to an IEnumerable, but then I can't .Add stuff to it.
Comment: @Henk - I don't follow your argument. Why wouldn't you have the same type of issue with if (!dict.ContainsKey(somekey)) dict[someKey] = someValue. Would there be thread-safety issues with that code as well (e.g. using ConcurrentDictionary)?
Comment: Java has the concept of a ConcurrentList: http://download.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html
Comment: @dcp: You would use TryGetValue() mostly.
Comment: @0A0D: I don't see one. There's a copy on write version but that's not what most people would expect a "concurrent collection" to do.
Comment: @Henk - Ok, but why do they still have the ConcurrentDictionary.ContainsKey method?
Comment: @Billy the point of a ConcurrentList would be to aleviate us all from the burden of locking/unlocking it.  Same reason all of the other concurrent collections exist.
Comment: @Zarat - yes, but that's my point. It seems weird to have non thread-safe methods in a class whose name starts with the word "Concurrent". But I see what you're saying, thanks for the clarifications and explanation.
Answer: With all due respect to the great answers provided already, there are times that I simply want a thread-safe IList. Nothing advanced or fancy. Performance is important in many cases but at times that just isn't a concern. Yes, there are always going to be challenges without methods like "TryGetValue" etc, but most cases I just want something that I can enumerate without needing to worry about putting locks around everything. And yes, somebody can probably find some "bug" in my implementation that might lead to a deadlock or something (I suppose) but lets be honest: When it comes to multi-threading, if you don't write your code correctly, it is going deadlock anyway. With that in mind I decided to make a simple ConcurrentList implementation that provides these basic needs.
And for what its worth: I did a basic test of adding 10,000,000 items to regular List and ConcurrentList and the results were:
List finished in: 7793 milliseconds.
Concurrent finished in: 8064 milliseconds.
public class ConcurrentList<T> : IList<T>, IDisposable
{
    #region Fields
    private readonly List<T> _list;
    private readonly ReaderWriterLockSlim _lock;
    #endregion

    #region Constructors
    public ConcurrentList()
    {
        this._lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
        this._list = new List<T>();
    }

    public ConcurrentList(int capacity)
    {
        this._lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
        this._list = new List<T>(capacity);
    }

    public ConcurrentList(IEnumerable<T> items)
    {
        this._lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
        this._list = new List<T>(items);
    }
    #endregion

    #region Methods
    public void Add(T item)
    {
        try
        {
            this._lock.EnterWriteLock();
            this._list.Add(item);
        }
        finally
        {
            this._lock.ExitWriteLock();
        }
    }

    public void Insert(int index, T item)
    {
        try
        {
            this._lock.EnterWriteLock();
            this._list.Insert(index, item);
        }
        finally
        {
            this._lock.ExitWriteLock();
        }
    }

    public bool Remove(T item)
    {
        try
        {
            this._lock.EnterWriteLock();
            return this._list.Remove(item);
        }
        finally
        {
            this._lock.ExitWriteLock();
        }
    }

    public void RemoveAt(int index)
    {
        try
        {
            this._lock.EnterWriteLock();
            this._list.RemoveAt(index);
        }
        finally
        {
            this._lock.ExitWriteLock();
        }
    }

    public int IndexOf(T item)
    {
        try
        {
            this._lock.EnterReadLock();
            return this._list.IndexOf(item);
        }
        finally
        {
            this._lock.ExitReadLock();
        }
    }

    public void Clear()
    {
        try
        {
            this._lock.EnterWriteLock();
            this._list.Clear();
        }
        finally
        {
            this._lock.ExitWriteLock();
        }
    }

    public bool Contains(T item)
    {
        try
        {
            this._lock.EnterReadLock();
            return this._list.Contains(item);
        }
        finally
        {
            this._lock.ExitReadLock();
        }
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        try
        {
            this._lock.EnterReadLock();
            this._list.CopyTo(array, arrayIndex);
        }
        finally
        {
            this._lock.ExitReadLock();
        }
    }

    public IEnumerator<T> GetEnumerator()
    {
        return new ConcurrentEnumerator<T>(this._list, this._lock);
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return new ConcurrentEnumerator<T>(this._list, this._lock);
    }

    ~ConcurrentList()
    {
        this.Dispose(false);
    }

    public void Dispose()
    {
        this.Dispose(true);
    }

    private void Dispose(bool disposing)
    {
        if (disposing)
            GC.SuppressFinalize(this);

        this._lock.Dispose();
    }
    #endregion

    #region Properties
    public T this[int index]
    {
        get
        {
            try
            {
                this._lock.EnterReadLock();
                return this._list[index];
            }
            finally
            {
                this._lock.ExitReadLock();
            }
        }
        set
        {
            try
            {
                this._lock.EnterWriteLock();
                this._list[index] = value;
            }
            finally
            {
                this._lock.ExitWriteLock();
            }
        }
    }

    public int Count
    {
        get
        {
            try
            {
                this._lock.EnterReadLock();
                return this._list.Count;
            }
            finally
            {
                this._lock.ExitReadLock();
            }
        }
    }

    public bool IsReadOnly
    {
        get { return false; }
    }
    #endregion
}

    public class ConcurrentEnumerator<T> : IEnumerator<T>
{
    #region Fields
    private readonly IEnumerator<T> _inner;
    private readonly ReaderWriterLockSlim _lock;
    #endregion

    #region Constructor
    public ConcurrentEnumerator(IEnumerable<T> inner, ReaderWriterLockSlim @lock)
    {
        this._lock = @lock;
        this._lock.EnterReadLock();
        this._inner = inner.GetEnumerator();
    }
    #endregion

    #region Methods
    public bool MoveNext()
    {
        return _inner.MoveNext();
    }

    public void Reset()
    {
        _inner.Reset();
    }

    public void Dispose()
    {
        this._lock.ExitReadLock();
    }
    #endregion

    #region Properties
    public T Current
    {
        get { return _inner.Current; }
    }

    object IEnumerator.Current
    {
        get { return _inner.Current; }
    }
    #endregion
}

Comment: OK, old answer but still:  `RemoveAt(int index)` is never thread-safe, `Insert(int index, T item)` is only safe for index==0, the return of `IndexOf()` is immediately outdated etc. Don't even start about the `this[int]`.
Comment: And you don't need and don't want a ~Finalizer().
Comment: You say you have given up on preventing the possibility of deadlock - and a single `ReaderWriterLockSlim` can be made to deadlock [easily](http://stackoverflow.com/a/26578074/709537) by using `EnterUpgradeableReadLock()` concurrently. You don't however use it, you don't make the lock accessible to the outside, and you don't e.g. call a method that enters a write lock while holding a read lock, so using your class does not make deadlocks any more likely.
Comment: The non-concurrent interface is not appropriate for concurrent access. E.g. the following is not atomic `var l = new ConcurrentList(); /* ... */ l[0] += "asdf";`. In general, any read-write combo can lead you into deep trouble when done concurrently. That is why concurrent data structures generally provide methods for those, like `ConcurrentDictionary`'s `AddOrGet` etc. N.B. Your constant (and redundant because the members are already marked as such by the underscore) repetition of `this.` clutters.
Comment: Thanks Eugene. I am a heavy user of .NET Reflector which puts "this." on all non-static fields. As such, I have grown to prefer the same. Regarding this non-concurrent interface not being appropriate: You are absolutely right that trying to perform multiple actions against my implementation can become unreliable. But the requirement here is simply that single actions (add, or remove, or clear, or enumeration) can be done without corrupting the collection. It basically removes the need to put lock statements around everything.
Answer: The reason why there is no ConcurrentList is because it fundamentally cannot be written.  The reason why is that several important operations in IList rely on indices, and that just plain won't work.  For example:
int catIndex = list.IndexOf("cat");
list.Insert(catIndex, "dog");

The effect that the author is going after is to insert "dog" before "cat", but in a multithreaded environment, anything can happen to the list between those two lines of code.  For example, another thread might do list.RemoveAt(0), shifting the entire list to the left, but crucially, catIndex will not change.  The impact here is that the Insert operation will actually put the "dog" after the cat, not before it.
The several implementations that you see offered as "answers" to this question are well-meaning, but as the above shows, they don't offer reliable results.  If you really want list-like semantics in a multithreaded environment, you can't get there by putting locks inside the list implementation methods.  You have to ensure that any index you use lives entirely inside the context of the lock.  The upshot is that you can use a List in a multithreaded environment with the right locking,  but the list itself cannot be made to exist in that world.
If you think you need a concurrent list, there are really just two possibilities:

What you really need is a ConcurrentBag
You need to create your own collection, perhaps implemented with a List and your own concurrency control.

If you have a ConcurrentBag and are in a position where you need to pass it as an IList, then you have a problem, because the method you're calling has specified that they might try to do something like I did above with the cat & dog.  In most worlds, what that means is that the method you're calling is simply not built to work in a multi-threaded environment.  That means you either refactor it so that it is or, if you can't, you're going to have to handle it very carefully.  You you'll almost certainly be required to create your own collection with its own locks, and call the offending method within a lock.
Answer: ConcurrentList (as a resizeable array, not a linked list) is not easy to write with nonblocking operations. Its API doesn't translate well to a "concurrent" version.
Comment: It's not only difficult to write, it's even difficult to figure out a useful interface.
Answer: In cases where reads greatly outnumber writes, or (however frequent) writes are non-concurrent, a copy-on-write approach may be appropriate.
The implementation shown below is

lockless
blazingly fast for concurrent reads, even while concurrent modifications are ongoing - no matter how long they take
because "snapshots" are immutable, lockless atomicity is possible, i.e. var snap = _list; snap[snap.Count - 1]; will never (well, except for an empty list of course) throw, and you also get thread-safe enumeration with snapshot semantics for free.. how I LOVE immutability!
implemented generically, applicable to any data structure and any type of modification
dead simple, i.e. easy to test, debug, verify by reading the code
usable in .Net 3.5

For copy-on-write to work, you have to keep your data structures effectively immutable, i.e. no one is allowed to change them after you made them available to other threads. When you want to modify, you

clone the structure
make modifications on the clone
atomically swap in the reference to the modified clone

Code
static class CopyOnWriteSwapper
{
    public static void Swap<T>(ref T obj, Func<T, T> cloner, Action<T> op)
        where T : class
    {
        while (true)
        {
            var objBefore = Volatile.Read(ref obj);
            var newObj = cloner(objBefore);
            op(newObj);
            if (Interlocked.CompareExchange(ref obj, newObj, objBefore) == objBefore)
                return;
        }
    }
}

Usage
CopyOnWriteSwapper.Swap(ref _myList,
    orig => new List<string>(orig),
    clone => clone.Add("asdf"));

If you need more performance, it will help to ungenerify the method, e.g. create one method for every type of modification (Add, Remove, ...) you want, and hard code the function pointers cloner and op.
N.B. #1 It is your responsibility to make sure the no one modifies the (supposedly) immutable data structure. There's nothing we can do in a generic implementation to prevent that, but when specializing to List<T>, you could guard against modification using List.AsReadOnly()
N.B. #2 Be careful about the values in the list. The copy on write approach above guards their list membership only, but if you'd put not strings, but some other mutable objects in there, you have to take care of thread safety (e.g. locking). But that is orthogonal to this solution and e.g. locking of the mutable values can be easily used without issues. You just need to be aware of it.
N.B. #3 If your data structure is huge and you modify it frequently, the copy-all-on-write approach might be prohibitive both in terms of memory consumption and the CPU cost of copying involved. In that case, you might want to use MS's Immutable Collections instead.
Answer: System.Collections.Generic.List<t> is already thread safe for multiple readers. Trying to make it thread safe for multiple writers wouldn't make sense. (For reasons Henk and Stephen already mentioned)
Comment: @Alan - that would be a ConcurrentQueue, ConcurrentStack or ConcurrentBag. To make sense of a ConcurrentList you should provide a use-case where the available classes are not enough. I don't see why I would want indexed access when the elements at the indices can randomly change through concurrent removes. And for a "locked" read you can already take snapshots of the existing concurrent classes and put them in a list.
Comment: I think you are wrong. Saying: safe for multiple readers does not mean that you can't write at the same time. Write would also mean delete and you will get an error if you delete while iterating in it.
Comment: You cannot see a scenario where I might have 5 threads adding to a list?  This way you could see the list accumulate records even before they all terminate.
Comment: You're right -- I don't want indexed access.  I generally use IList as a proxy for an IEnumerable to which I can .Add(T) new elements.  That's where the question comes from, really.
Comment: @Alan: Then you want a queue, not a list.
Comment: @Eric: I never said you could write at the same time. You can either have one writer. Or you can have multiple readers. Not both.
Comment: @Eugene: I never said that it was a "concurrent list". There is no such thing as "thread safe". Thread safety requires understanding the actual thread safety characteristics of a structure. Not every data structure is safe for multiple readers and no writers because many data structures have global shared state they don't tell you about.
Comment: @Eugene: Which is exactly what my answer says. I understand that the question asked for it; but what the question asks for fundamentally doesn't make any sense.
Answer: Some people hilighted some goods points (and some of my thoughts):

It could looklikes insane to unable random accesser (indexer) but to me it appears fine. You only have to think that there is many methods on multi-threaded collections that could fail like Indexer and Delete. You could also define failure (fallback) action for write accessor like "fail" or simply "add at the end".
It is not because it is a multithreaded collection that it will always be used in a multithreaded context. Or it could also be used by only one writer and one reader.
Another way to be able to use indexer in a safe manner could be to wrap actions into a lock of the collection using its root (if made public).
For many people, making a rootLock visible goes agaist "Good practice". I'm not 100% sure about this point because if it is hidden you remove a lot of flexibility to the user. We always have to remember that programming multithread is not for anybody. We can't prevent every kind of wrong usage.
Microsoft will have to do some work and define some new standard to introduce proper usage of Multithreaded collection. First the IEnumerator should not have a moveNext but should have a GetNext that return true or false and get an out paramter of type T (this way the iteration would not be blocking anymore). Also, Microsoft already use "using" internally in the foreach but sometimes use the IEnumerator directly without wrapping it with "using" (a bug in collection view and probably at more places) - Wrapping usage of IEnumerator is a recommended pratice by Microsoft. This bug remove good potential for safe iterator... Iterator that lock collection in constructor and unlock on its Dispose method - for a blocking foreach method.

That is not an answer. This is only comments that do not really fit to a specific place.
... My conclusion, Microsoft has to make some deep changes to the "foreach" to make MultiThreaded collection easier to use. Also it has to follow there own rules of IEnumerator usage. Until that, we can write a MultiThreadList easily that would use a blocking iterator but that will not follow "IList". Instead, you will have to define own "IListPersonnal" interface that could fail on "insert", "remove" and random accessor (indexer) without exception. But who will want to use it if it is not standard ?
Comment: One could easily write a `ConcurrentOrderedBag` which would include a read-only implementation of `IList`, but would also offer a fully-thread-safe `int Add(T value)` method.  I don't see why any `ForEach` changes would be needed.  Although Microsoft doesn't explicitly say so, their practice suggests that it's perfectly acceptable for `IEnumerator` to enumerate the collection contents that existed when it was created; the collection-modified exception is only required if the enumerator would be unable to guarantee glitch-free operation.
Comment: Iterating through a MT collection, the way it is design could lead, as you said, to an exception... Which one I don't know. Would you trap all exceptions? In my own book exception is exception and should not occurs in normal execution of code. Otherwise, to prevent exception, you have to either lock the collection or get a copy (in a safe manner-ie lock) or implement very complex mechanism in the collection to prevent exception to occurs due to concurrency. My though was that it would be nice to add an IEnumeratorMT that would lock the collection while a for each occur and add related code...
Comment: The other thing that could also occur is that when you get an iterator, you can lock the collection and when your iterator is GC collected you can unlock the collection. According to Microsfot they already check if the IEnumerable is also an IDisposable and call the GC if so at the end of a ForEach. The main problem is that they also use the IEnumerable elsewhere without calling the GC, you then can't rely on that. Having a new clear MT interface for IEnumerable enabling lock would do solve the problem, at least a part of it. (It would not prevent people to not call it).
Comment: It is very bad form for a public `GetEnumerator` method to leave a collection locked after it returns; such designs can easily lead to deadlock.  The `IEnumerable` provides no indication of whether an enumeration can be expected to complete even if a collection is modified; the best one can do is write one's own methods so that they will do so, and have methods which accept `IEnumerable` document the fact that will only be thread-safe if the `IEnumerable` supports thread-safe enumeration.
Comment: What would have been most helpful would have been if `IEnumerable` had included a "Snapshot" method with return type `IEnumerable`.  Immutable collections could return themselves; a bounded collection could if nothing else copy itself to a `List` or `T[]` and call `GetEnumerator` on that.  Some unbounded collections could implement `Snapshot`, and those which couldn't would be able to throw an exception without trying to fill up a list with their contents.
Comment: I mostly agree. Snapshot would be very nice. And locking on "GetEnumerator" could easily lead to what you said because people don't expect that behavior. I don't say I have the perfect solution, but having an iterator without lock is dangerous and implementation should prevent that for sure. The problem with snapshot is performance for big collection. I think that ideally, MT collection should be implemented in more than on way according to its wanted usage (main usage). With snapshot (like you said) and also with mechanics enabling modification while iterating (which slow down insert/delete).
Comment: Thanks supercat for your comments. I appreciate.
Comment: Not all collections could implement `Snapshot` quickly, and some couldn't implement it at all, but many collections could implement it far more quickly than could outside code whose only exposure to the type was via public interfaces.  For example, a snapshot of an `AppendOnlyList` would could encapsulate a reference to the list and the number of items it presently contains; even though the list wouldn't be completely immutable, a list which reports itself as containing N items could guarantee that the first N items are immutable.
Comment: Right! I like your idea of AppendOnlyList, it would have solved some of my previous needs.
Comment: I think AppendOnlyList and AddOnlyDictionary would have been very nice types, since they can be cheaply implemented in such a way as to allow any number of readers *simultaneous* with a single writer, allow the construction of immutable snapshots, and (in the case of AddOnlyDictionary), promise to enumerate items in the order they were added (guarantees not made by `Dictionary`, `ConcurrentDictionary`, nor `ConcurrentBag`).
Comment: Totally agreed. I would have use them few times in the course of my projects. I will consider write one next time I will need it. Thanks.
Answer: I implemented one similar to Brian's. Mine is different:

I manage the array directly.
I don't enter the locks within the try block.
I use yield return for producing an enumerator.
I support lock recursion. This allows reads from list during iteration.
I use upgradable read locks where possible.
DoSync and GetSync methods allowing sequential interactions that require exclusive access to the list.

The code:
public class ConcurrentList<T> : IList<T>, IDisposable
{
    private ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
    private int _count = 0;

    public int Count
    {
        get
        {
            _lock.EnterReadLock();
            try
            {
                return _count;
            }
            finally
            {
                _lock.ExitReadLock();
            }
        }
    }

    public int InternalArrayLength
    {
        get
        {
            _lock.EnterReadLock();
            try
            {
                return _arr.Length;
            }
            finally
            {
                _lock.ExitReadLock();
            }
        }
    }

    private T[] _arr;

    public ConcurrentList(int initialCapacity)
    {
        _arr = new T[initialCapacity];
    }

    public ConcurrentList():this(4)
    { }

    public ConcurrentList(IEnumerable<T> items)
    {
        _arr = items.ToArray();
        _count = _arr.Length;
    }

    public void Add(T item)
    {
        _lock.EnterWriteLock();
        try
        {
            var newCount = _count + 1;
            EnsureCapacity(newCount);
            _arr[_count] = item;
            _count = newCount;
        }
        finally
        {
            _lock.ExitWriteLock();
        }
    }

    public void AddRange(IEnumerable<T> items)
    {
        if (items == null)
            throw new ArgumentNullException("items");

        _lock.EnterWriteLock();

        try
        {
            var arr = items as T[] ?? items.ToArray();
            var newCount = _count + arr.Length;
            EnsureCapacity(newCount);
            Array.Copy(arr, 0, _arr, _count, arr.Length);
            _count = newCount;
        }
        finally
        {
            _lock.ExitWriteLock();
        }
    }

    private void EnsureCapacity(int capacity)
    {
        if (_arr.Length >= capacity)
            return;

        int doubled;
        checked
        {
            try
            {
                doubled = _arr.Length * 2;
            }
            catch (OverflowException)
            {
                doubled = int.MaxValue;
            }
        }

        var newLength = Math.Max(doubled, capacity);
        Array.Resize(ref _arr, newLength);
    }

    public bool Remove(T item)
    {
        _lock.EnterUpgradeableReadLock();

        try
        {
            var i = IndexOfInternal(item);

            if (i == -1)
                return false;

            _lock.EnterWriteLock();
            try
            {
                RemoveAtInternal(i);
                return true;
            }
            finally
            {
                _lock.ExitWriteLock();
            }
        }
        finally
        {
            _lock.ExitUpgradeableReadLock();
        }
    }

    public IEnumerator<T> GetEnumerator()
    {
        _lock.EnterReadLock();

        try
        {
            for (int i = 0; i < _count; i++)
                // deadlocking potential mitigated by lock recursion enforcement
                yield return _arr[i];
        }
        finally
        {
            _lock.ExitReadLock();
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }

    public int IndexOf(T item)
    {
        _lock.EnterReadLock();
        try
        {
            return IndexOfInternal(item);
        }
        finally
        {
            _lock.ExitReadLock();
        }
    }

    private int IndexOfInternal(T item)
    {
        return Array.FindIndex(_arr, 0, _count, x => x.Equals(item));
    }

    public void Insert(int index, T item)
    {
        _lock.EnterUpgradeableReadLock();

        try
        {
            if (index > _count)
                throw new ArgumentOutOfRangeException("index");

            _lock.EnterWriteLock();
            try
            {
                var newCount = _count + 1;
                EnsureCapacity(newCount);

                // shift everything right by one, starting at index
                Array.Copy(_arr, index, _arr, index + 1, _count - index);

                // insert
                _arr[index] = item;
                _count = newCount;
            }
            finally
            {
                _lock.ExitWriteLock();
            }
        }
        finally
        {
            _lock.ExitUpgradeableReadLock();
        }

    }

    public void RemoveAt(int index)
    {
        _lock.EnterUpgradeableReadLock();
        try
        {
            if (index >= _count)
                throw new ArgumentOutOfRangeException("index");

            _lock.EnterWriteLock();
            try
            {
                RemoveAtInternal(index);
            }
            finally
            {
                _lock.ExitWriteLock();
            }
        }
        finally
        {
            _lock.ExitUpgradeableReadLock();
        }
    }

    private void RemoveAtInternal(int index)
    {
        Array.Copy(_arr, index + 1, _arr, index, _count - index-1);
        _count--;

        // release last element
        Array.Clear(_arr, _count, 1);
    }

    public void Clear()
    {
        _lock.EnterWriteLock();
        try
        {
            Array.Clear(_arr, 0, _count);
            _count = 0;
        }
        finally
        {
            _lock.ExitWriteLock();
        }
    }

    public bool Contains(T item)
    {
        _lock.EnterReadLock();
        try
        {
            return IndexOfInternal(item) != -1;
        }
        finally
        {
            _lock.ExitReadLock();
        }
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        _lock.EnterReadLock();
        try
        {
            if(_count > array.Length - arrayIndex)
                throw new ArgumentException("Destination array was not long enough.");

            Array.Copy(_arr, 0, array, arrayIndex, _count);
        }
        finally
        {
            _lock.ExitReadLock();
        }
    }

    public bool IsReadOnly
    {
        get { return false; }
    }

    public T this[int index]
    {
        get
        {
            _lock.EnterReadLock();
            try
            {
                if (index >= _count)
                    throw new ArgumentOutOfRangeException("index");

                return _arr[index];
            }
            finally
            {
                _lock.ExitReadLock();
            }
        }
        set
        {
            _lock.EnterUpgradeableReadLock();
            try
            {

                if (index >= _count)
                    throw new ArgumentOutOfRangeException("index");

                _lock.EnterWriteLock();
                try
                {
                    _arr[index] = value;
                }
                finally
                {
                    _lock.ExitWriteLock();
                }
            }
            finally
            {
                _lock.ExitUpgradeableReadLock();
            }

        }
    }

    public void DoSync(Action<ConcurrentList<T>> action)
    {
        GetSync(l =>
        {
            action(l);
            return 0;
        });
    }

    public TResult GetSync<TResult>(Func<ConcurrentList<T>,TResult> func)
    {
        _lock.EnterWriteLock();
        try
        {
            return func(this);
        }
        finally
        {
            _lock.ExitWriteLock();
        }
    }

    public void Dispose()
    {
        _lock.Dispose();
    }
}

Comment: I wanted to go on record saying that I recognize that the usefulness of `IList` semantics in concurrent scenarios is limited at best. I wrote this code probably before I came to that realization. My experience is the same as the writer of the accepted answer: I gave it a try with what I knew about synchronization and IList and I learned something by doing that.
Comment: What happens if two threads get into the beginning of the `try` block in `Remove` or the indexer setter at the same time?
Comment: @James that doesn't seem possible. Read remarks at https://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.enterupgradeablereadlock%28v=vs.110%29.aspx. Running this code, you'll never enter that lock a 2nd time: https://gist.github.com/ronnieoverby/59b715c3676127a113c3
Comment: @Ronny Overby: Interesting. Given that, I suspect that this would perform much better if you removed the UpgradableReadLock from all functions where the only operation performed in the time between the upgradable read lock and the write lock--the overhead of taking any kind of lock is so much more than the check to see if the parameter is out of range that just doing that check inside the write lock would likely perform better.
Comment: This class also doesn't seem very useful, as the offset-based functions (most of them) can't really ever be used safely unless there is some external locking scheme anyway because the collection could change between when you decide where to put or get something from and when you actually get it.
Comment: @James So don't use it.
Answer: In sequentially executing code the data structures used are different from (well written) concurrently executing code. The reason is that sequential code implies implicit order. Concurrent code however does not imply any order; better yet it implies the lack of any defined order!
Due to this, data structures with implied order (like List) are not very useful for solving concurrent problems. A list implies order, but it does not clearly define what that order is. Because of this the execution order of the code manipulating the list will determine (to some degree) the implicit order of the list, which is in direct conflict with an efficient concurrent solution.
Remember concurrency is a data problem, not a code problem! You cannot Implement the code first (or rewriting existing sequential code) and get a well designed concurrent solution. You need to design the data structures first while keeping in mind that implicit ordering doesn't exist in a concurrent system.
Answer: lockless Copy and Write approach works great if you're not dealing with too many items.
Here's a class I wrote:
public class CopyAndWriteList<T>
{
    public static List<T> Clear(List<T> list)
    {
        var a = new List<T>(list);
        a.Clear();
        return a;
    }

    public static List<T> Add(List<T> list, T item)
    {
        var a = new List<T>(list);
        a.Add(item);
        return a;
    }

    public static List<T> RemoveAt(List<T> list, int index)
    {
        var a = new List<T>(list);
        a.RemoveAt(index);
        return a;
    }

    public static List<T> Remove(List<T> list, T item)
    {
        var a = new List<T>(list);
        a.Remove(item);
        return a;
    }

}

example usage:
orders_BUY = CopyAndWriteList.Clear(orders_BUY);
Comment: instead of locking, it creates a copy of the list, modifies the list and set the reference to the new list. So any other threads that are iterating will not cause any problems.
Comment: [My answer](https://stackoverflow.com/a/30769838/709537) has a generic solution, and in N.B #1 I mention that you can (and I think should) return [`List.AsReadOnly(modifiedList)`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.asreadonly?redirectedfrom=MSDN&view=netcore-3.1#System_Collections_Generic_List_1_AsReadOnly) in non-generic solutions like yours. That makes it really thread-safe. Of course you will need to change your interface from using `List` to using e.g. `IList`.
Answer: I'm surprised no-one has mentioned using LinkedList as a base for writing a specialised class.
Often we don't need the full API's of the various collection classes, and if you write mostly functional side effect free code, using immutable classes as far as possible, then you'll actually NOT want to mutate the collection favouring various snapshot implementations.
LinkedList solves some difficult problems of creating snapshot copies/clones of large collections. I also use it to create "threadsafe" enumerators to enumerate over the collection. I can cheat, because I know that I'm not changing the collection in any way other than appending, I can keep track of the list size, and only lock on changes to list size. Then my enumerator code simply enumerates from 0 to n for any thread that wants a "snapshot" of the append only collection, that will be guaranteed to represent a "snapshot" of the collection at any moment in time, regardless of what other threads are appending to the head of the collection.
I'm pretty certain that most requirements are often extremely simple, and you need 2 or 3 methods only. Writing a truly generic library is awfully difficult, but solving your own codes needs can sometimes be easy with a trick or two.
Long live LinkedList and good functional programming.
Cheers, ... love ya all!
Al
p.s. sample hack AppendOnly class here : https://github.com/goblinfactory/AppendOnly
Comment: *"Why has not one mentioned LinkedList?"* This is an impossible to answer question, but if I had to guess I would say because nobody likes to use this class in general, most people have never used it, and so it doesn't popup as a solution in their mind when they have a problem to solve. Another possibility is that anyone who tried to use this class to do anything practical was disappointed by its abysmal performance (compared to array-backed structures like the `List`), so they decided not to waste their time again with this class. But these are just my wild guesses of course.
Comment: :D @TheodorZoulias drat... now you've got me curious and I'm definitely going to have to do that perf comparison. nice thread, I'll post an update if/when I get around to it.
Comment: Do you have any benchmarks that compare your [`AppendOnlyList`](https://github.com/goblinfactory/AppendOnly) class with what seems like its closest immutable competitor, the [`ImmutableQueue`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.immutable.immutablequeue-1) class? How much faster is your class, and how much less allocatey it is? We need to see the numbers!
Comment: they solve different problems. In my case I needed an Immutable append only class, and as per my comment, i was easily able to achieve my design goals by writing a few lines of code on top of a linked list and achieve threadsafety, concurrency and immutability. Go check it out, its just a sample to get you inspired to write something yourself. My comment wasn't about "hey my code is the best", it was .. hey, why hasnt anyone mentioned LinkedList in any of the discussions?
Comment: Your [`AppendOnlyList`](https://github.com/goblinfactory/AppendOnly/blob/master/src/Lib/AppendOnlyList.cs) class supports adding (`AddItem`) and enumerating (`Items`). These two operations are also supported by the `ImmutableQueue` class (`Enqueue`, `GetEnumerator`), so why do you say that these two classes solve different problems? They don't. So the question becomes: which is faster and less allocatey? Do you want me to do the benchmarks?
Comment: In terms of "allocatey" since it's just a linkedList under the covers, you're really asking "how efficient (less allocatey) is LinkedList". Under the covers I'd wager the ImmutableQueue is also using a LinkedList considering the API. But since my particular use case needs a mutable appendOnly list, I can't use ImmutableQueue and had no reason to spend time comparing them. You're welcome to do it, I'll buy you a coffee if it's faster, or "less allocatey" :D cheers, A
Comment: How is it mutable? AFAICS the `AppendOnlyList` has no API that mutates an instance of the class. The `AddItem` method returns a new `AppendOnlyList`, just like the `ImmutableQueue.Enqueue` returns a new `ImmutableQueue`.
Comment: @TheodorZoulias I'd love a benchmark, that would be totally awesome :D
p.s. make sure you include "Length" counts :D (wink)
Comment: Snowcode TBH I am pretty confident that the `ImmutableQueue` is at least as fast as your class, and not more allocatey. And because of this I have no incentive to write benchmarks. Honestly I think that it's a work that you should do yourself, in order to prove that your idea is worthy.
Comment: I am not trying to prove it, I just shared my code as an example of a custom implementation based on LinkedList that's absolutely trivial and encourage folk to consider many other applications of the very versatile and very under-utilised data structure. Yes, ImmutableQueue is also a good base class also to use as a starting block, I never said it wasn't, look at them both.
Comment: Snowcode currently if I have a need for a data structure that support adding items, preserves their insertion order, and is immutable, I am not going to start searching around about whether the `LinkedList` or the `ArrayList` or the `SortedDictionary` or the `BitArray` is a good starting point for creating a *custom* class having these features. With that mindset I'll never get anything done. Instead I'll pick the data structure that offers these features out of the box, and I'll go one with my project. I don't know if anyone is persuaded by your arguments, but I'm certainly not.
Comment: I hear you, and you're absolutely right. I think we are talking cross purposes. The OP cannot use an `ImmutableQueue` as a replacement for `ConcurrentList` for all the reasons the good folk have mentioned above, e.g. insertAt, removeAt etc, which promoted a lot of interesting discussions around both using existing stuff as well as writing new things, which is why I "mused" over the "interesting to me" wondering, why has not one mentioned LinkedList? If even only to debunk it's use in different situations. Your comments on  ImmutableQueue are perfectly valid.

No ConcurrentList in .Net 4.0?


Difference between using these two default constructors?

Question: I was able to pass a secret test with my code, which essentially test the code with certain input and expected output. I kept getting an assertion error which stated, expected<1> but was:<0> Until I changed the code from this:
public Gunner(){
    this.gunpower = 1;
    this.GunnerStrength = 1;
    this.name = "Default Gunner";
}

to
public Gunner() {
    this("Default Gunner", 1, 1);
}

To illustrate further and to give reference points, here are the codes which preceded the above code:
package ship;

public class Gunner {
    private String name;
    private int gunpower;
    private int GunnerStrength;
    private int maxGupower;
    private int maxGunnerStrength;
    private int currentGunpower;
    private int currentGunnerStrength;

    public Gunner(String l_name, int l_gunpower, int l_GunnerStrength) {
        this.name = l_name;
        this.currentGunpower = maxGunpower = l_gunpower;
        this.currentGunnerstrength = maxGunnerStrength = l_GunnerStrength;
    }

    public Gunner(Gunner other) {
        this.name = new String(other.name);
        this.gunpower = new Integer(other.gunpower);
        this.GunnerStrength = new Integer(other.GunnerStrength);
        this.maxGunpower = new Integer(other.maxGunpower);
        this.maxGunnerStrength = new Integer(other.maxGunnerStrength);
        this.currentGunpower = new Integer(other.currentGunpower);
        this.currentGunnerStrength = new Integer(other.currentGunnerStrength);
    }
}

If someone could please explain the differences between the two codes above it would be much appreciated.
Comment: _"pass a secret test "_ -- what is a secret test?
Comment: @JimGarrison, he'd tell us, but clearly he'd have to gun us down.
Comment: Depending upon your "test", the first one did not set currentGunpower or currentGunnerStrength. Basically, make sure you initialize all of your instance variables if they are important.
Comment: what do you mean by "secret test"?  If this is some kind of course I think you would have to clarify with the course instructor.
Comment: They are like a series of unit tests that test the code with certain inputs and expect certain outputs. For this code I kept getting the error, expected<1> but was:<0> that was until I tried the second code and it worked, still unsure why though.
Comment: `name`, `gunpower`, **`GunnerStrength`**, `maxGupower`, `maxGunnerStrength`, `currentGunpower`, `currentGunnerStrength` -- why is one of these not like the others?
Comment: The quoted code won't compile, you have a field called `maxGupower` (note there's no `n` in that), but your code tries to use `maxGunpower` (with the `n`).
Answer: Your original Gunner() constructor attempted to duplicate the logic of the Gunner(String,int,int) constructor, although apparently (as you've passed whatever the "secret test" was), it failed to do so correctly since it filled in different fields: It initialized gunpower, GunnerStrength, and name; but the other constructor initializes name, currentGunpower, maxGunpower, currentGunnerStrength, and maxGunnerStrength. That's quite a different set of fields.
Your revised Gunner() constructor reuses the logic of the Gunner(String,int,int) constructor, rather than attempting to duplicate it. And so it fills in the fields that Gunner(String,int,int) fills in. Presumably the test expected those fields to be filled in.
In general, duplicating logic is a bad idea, because inevitably things change over time, so unless there are convincing arguments to the contrary, reusing rather than duplicating logic is the way to go.

Re your edit:

I kept getting an assertion error which stated, expected<1> but was:<0>

The default value of an int field is 0, so if you don't initialize or assign another value to the field, it will have the value 0. So presumably the unit test was checking the value of one of the fields your original Gunner() didn't fill in (currentGunpower, maxGunpower, currentGunnerStrength, or maxGunnerStrength) but your new Gunner() does fill in (via Gunner(String,int,int)).

Side note:

Difference between using these two default constructors?

There are no default constructors in your code. A default constructor is provided by the compiler if you don't define any constructors for the class. Since you do define constructors for the class, there is no default constructor.
Your Gunner() constructor is a constructor with no formal parameters, sometimes called a zero-params constructor or a zero-args constructor or a no-arg(s) constructor (Java uses "parameter" rather than "argument" to refer to the things you pass into methods and constructors, but they're also commonly called "arguments" informally, hence "args").
Comment: Might also be worth noting the common alternative "no-arg".
Comment: Thank you for your answer.
What I don't understand is why when I googled default constructors only the first version came up. While the second one was much more difficult to unearth. Why is the first default constructor much more common? if from what people tell me the second is much better?
Comment: @FooFighter: There are no "default constructor"s in your code. There is a *zero-parameters* (zero-args) constructor, but no *default* constructor. A *default constructor* is a constructor added by the compiler because you didn't give the class any constructors in the code. Since your class has defined constructors, there is no *default* constructor.
Comment: Well if you want to be all textbook about it sure. So anyway a public Gunner() is technically a zero-parameter constructor, therefore, why wouldn't the first initialize the values exactly like the second?
Comment: It's not "being textbook," it's not surprising that you'd fail to find the information you're looking for if you search for the wrong term. *"why wouldn't the first initialize the values exactly like the second"* Why *would* it? As I said in the answer, your first version doesn't write any value to several fields, so they take their default value, which the test is expecting *not* to be the default value. The second version *does* write non-default values to those fields, by calling another constructor.
Comment: So what's weird is my instructor labeled it as a default constructor, ill be sure to have a talking to with him about this because it certainly confused me when investigating different websites for info.
Comment: @FooFighter: Yeah, unfortunately, sometimes even people who should know what they're doing will use a term incorrectly, sometimes creating quite a lot of confusion.
Comment: Still confused one this. If the idea here was to initialize the values, why didn't saying this.gunpower = 1; work? isn't that setting the value right then and there? And then exactly what is this(x,y,z); is this  type of method here? I did a trial and error and found it out by accident, now I am trying to figure out what it actually means.
Comment: @FooFighter: Please carefully re-read the answer, and the comment above. Setting `gunpower` doesn't set `currentGunpower` or `maxGunpower`. Calling the other constructor, which **does** set those, does set them. (But the other constructor doesn't set `gunpower`; the class has some issues not specifically related to your question, such as why would it need both `gunpower` and `currentGunpower`?)
Comment: @chrylis: Good one, added.


For each Sub Directory write a separate file (csv) with information

Question: I have a situation where I need to write an Output file for each folder with data/information within each folder.
Folder/directory structure:
C:\Logs\15Sec\Ref.Data\Month\Log.Jan\Day.1\
~\Month\~ have folders up to Log.Dec
~\Log.Jan\~ has a folder for 30/31 Days in a month
~\Day.1\~ has files with data

What I could achieve:
I can read data using a script for all Days in a month and can write the info in a CSV file. thanks to @zett42.
This works fine at the given folder/directory structure -
C:\Logs\15Sec\Ref.Data\Month\Log.Jan\

Script:
$targDir = "C:\Logs\15Sec\Ref.Data\Month\";
$subDir = $(Get-ChildItem "$targDir" –Directory );
foreach($sub in $subDir) {
    Get-ChildItem -Path $sub –Recurse *.log |
    Select-Object -Property @(
        'FullName'
         @{ Name = "LineCount"; Expression = {
             (Get-Content -Path $_.FullName | Select-Object -Skip 8 | Measure-Object).Count
         }}
    ) |
    Export-Csv C:\test\output.csv -NoTypeInformation
}

Problem:
When trying to run the script at a higher folder/directory structure, which is
C:\Logs\15Sec\Ref.Data\Month\

The script only writes the Output file for the last folder present in Month for example Log.May. All other folders (Log.Jan, Log.Feb, etc) information will not be written. I don't know how to do this and couldn't trace the correct help on the internet.
Expectation:
A separate file for each Month with the name of the month (Log.Jan.csv, Log.Feb.csv) itself.
Comment: Where do you want to create the csv file? In `C:\test`? If so, change to the export to `Export-Csv "C:\test\$($sub.Name).csv" -NoTypeInformation`
Comment: Why are you using Recurse? Get-ChildItem -Path $sub –Recurse *.
Comment: I read on a webpage that this helps to get through subdirectories.
Comment: @arco44 your suggestion does the job for me.
Comment: You already have the subdirectories using Get-ChildItem.  You do not need to get them again.
Comment: @jdweng looks to me like both `Get-ChildItem`s are required. One to get the 1st level dirs under `Month`, then the second to recursively get all the dirs in each month directory (inside the foreach loop) - this info is processed and added to the csv
Comment: @arco444 : Get child items will get every folder.  So why would use need to get the descendant a second time using recurse?
Answer: Your script currently writes the output for every month, but also overwrites it on every loop iteration - that's why you only see data from the last month. So you just need to update the output path to grab the name from the current month's directory.
Change the export definition to:
Export-Csv "C:\test\$($sub.Name).csv" -NoTypeInformation


Prove that g:R$\to$ (-1,1] defined by g(x)= cos x is surjective or not?

Question: Surjective: a function $f$ from $A$ to $B$ is called onto or surjective, if and only if every element $b \in B$ there is an element $a \in A$ with $f(a)=b$.
Really appreciate if someone explain clearly the above definition of surjectivity then I would able to prove the above statement on question.
Comment: If we specify $(-1,1]$ as the codomain, the function is not well-defined. What is $g(\pi)$, for instance?
Comment: Formatting tips [here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: note that the brackets is written as above (-1,1]. in my opinion i think if the brackets written as [-1,1] then it suits the range of a cosine function which will be a surjective. this is my thought.
Answer: Since your interval is $(-1, 1]$, your function is not well defined for $x= \pi$ since $cos(\pi)=-1$.
However, if you defined the interval to be $[-1, 1]$, you could conclude that the map is surjective since for any real number in $[-1, 1]$, you could find a real number,  $x \in R$ such that $cos(x)$ maps to that number.
Intuitively, think of surjectivity as being able to reach any point on the target space with your map. So if you can reach all possible points in the target space (make sure your function is well defined), the function is surjective.


When is GAE standard python 2.7 runtime going away?

Question: I know, I should port to PY3, but let's say I am unable to.
How much longer, apps written in PY2.7 will remain working on GAE, before support is completely removed and existing 2.7 apps won't work any more?
Answer: I don't work for Google and only they can say, but from what I've seen, I expect that we have at least a few years.
Many people are in your position, and Google likely doesn't want to screw us over, so to speak.
Answer: There is no official statement from Google as of now as to when Python 2 will be deprecated, however, official support for Python 2 has been stopped since January of this year, so it is advised to work with Python 3 as soon as possible, although Google always does give notice in great advance beforehand. So I would advise to start migrating when you can and wait for a communication from Google to have an exact date.


creating a tableau pie chart with no measures data

Question: I have a table (as seen in link below), that has a system assessment that we conduct every year. The assessment is a series of 4 questions (or as we call them 'attributes') and there is only 3 possible outcomes.
Table
Using Tableau, I'd like to have the system as a filter (easy to do), and for each attribute build a pie chart. There are no measures that I capturing.
Any thoughts on how to do this?
Thanks.
Answer: Aliter: Easy solution:
Click on/select number_of_records/count(sheet) and also 'attribute_1field in data pane and clickpie_chartonshow_me` (ctrl +1) tool of tableau and pie chart will be created.
Answer: Once you get to know the power of LOD calculations in Tableau it is not that tough.  Walkthrough-
Step-1 Create LOD calculated field for each Attribute as, Attri_1_Measure
{Fixed [Status of Attribute 1] : COUNT (sheet_name)}

Step-2 Add Attri_1_Measure to angle, size and text measures,  Status_of_attri1 to text and color.  You'll get your desired view.
Step-3 Add System to filters, right click and add filters to context (very important step).
You can repeat these steps for each attribute.
Note: Beginning version 2020 of tableau there is no measure as number of records, but there is a sheet/data_table count measure therein.  Good Luck.


Age calculation Query - optimization return time

Question: My query is mean to:

Filter peoples incorrect date so that it only calculates people that have the correct date "DAY-MONTH-YEAR" (02-Dec-1986)
Calculate their age between 2 parameters.

I don't know if 1.029 SECs is normal for this type of query or I am doing something wrong that make is a bit slow. Could anyone advice me if I've done something that could be optimized?
as it stands my query takes ( 870,968 total, Query took 1.0297 sec)
and the actual query is
SELECT  DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(STR_TO_DATE(m.m_dob, '%d-%b-%Y'))), '%Y')+0 AS age
FROM impressions AS i, mariners AS m
WHERE STR_TO_DATE(m.m_dob, '%d-%b-%Y') IS NOT NULL
  AND m_dob != ''
  AND DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(STR_TO_DATE(m.m_dob, '%d-%b-%Y'))), '%Y')+0 BETWEEN 13 AND 50
ORDER BY `age`  DESC

Comment: Please post your table structures. Do you realize that you are getting a cartesian result between those tables?  You are not actually joining them.  Do you need the `impressions` table? It does not look like you are using that table.
Comment: If i dont put impression table i get less results `( 28 total, Query took 0.0051 sec)` What do you mean by cartesian results?. I have 97 colums there and no index. you want the 97 colums in detail?.
Comment: A Cartesian result takes every row from each table to join, so if each table has 4 rows, your result will have 16 rows. See [Cartesian product](http://en.wikipedia.org/wiki/Join_(SQL)#Cross_join). Do you need both tables to get your result? Do the tables have a column that will allow for joining?
Comment: Yes, I need both tables. I find it weird that it return less results without impression when Impression table doesnt hold DoB. yes i have a colum that would enable me to join them. I would join them `i.SessionID = m.ID ` in a similar query  i need to get the people that have impression =1
Comment: You get less results without the `impressions` table because in your original query you are combining each row from the first table with each row of the each table.  You are multiplying the results.
Comment: if i try `SELECT  DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(STR_TO_DATE(m.m_dob, '%d-%b-%Y'))), '%Y')+0 AS age  FROM  mariners AS m INNER JOIN impressions AS i on i.SessionID = m.ID  WHERE STR_TO_DATE(m.m_dob, '%d-%b-%Y') IS NOT NULL AND m_dob != '' AND DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(STR_TO_DATE(m.m_dob, '%d-%b-%Y'))), '%Y')+0 BETWEEN 13 AND 50 ORDER BY `age`  DESC` I get Showing rows 0 - 29 ( 474 total, Query took 0.0557 sec) but guessing they are still repeated?
Comment: What is the datatype of m_dob?
Comment: No offense, but that stinks to high heaven.  Are you able to change it to date?
Comment: I know. I didnt create the db... I just dont wanna change it to date and then break something :P
Answer: Based on your comments and your current query, you are not actually joining your tables. The two tables need to be joined on:
SELECT DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(STR_TO_DATE(m.m_dob, '%d-%b-%Y'))), '%Y')+0 AS age
FROM impressions AS i
INNER JOIN mariners AS m
  ON i.SessionId = m.ID
WHERE i.impression =1
  AND STR_TO_DATE(m.m_dob, '%d-%b-%Y') IS NOT NULL
  AND m_dob != ''
  AND DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(STR_TO_DATE(m.m_dob, '%d-%b-%Y'))), '%Y')+0 BETWEEN 13 AND 50
ORDER BY `age` DESC

Your current query is returning a Cartesian result of the dates.
Comment: Why when I run this joining Impression (and taking away the `i.impression =1` ) I get  474 total results but when I run the same query but when i take the impression join away i only get ( 28 total, Query took 0.0051 sec) from Mariners table?
Comment: @JonathanThurft I think you are going to have to post your table structure some sample data and then the desired result.  Without seeing these details it will be difficult, it sounds like you have a one-to-many relationship between the to tables that is causing the increase in rows.
Comment: Here is the tructure http://www.seafarersupport.org/dbstructure.pdf. The returning data is the AGE calculation that if taken only from mariners  table returns 28 results. and tehe impressions table has ID, Date, SessionID, Charity, Contacted, Type.
Comment: I've tried `SELECT DISTINCT(m.ID),  DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(STR_TO_DATE(m.m_dob, '%d-%b-%Y'))), '%Y')+0 AS age  FROM  mariners AS m INNER JOIN impressions AS i on i.SessionID = m.ID  WHERE STR_TO_DATE(m.m_dob, '%d-%b-%Y') IS NOT NULL AND m_dob != '' AND DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(STR_TO_DATE(m.m_dob, '%d-%b-%Y'))), '%Y')+0 BETWEEN 13 AND 50 ORDER BY `age`  DESC` trying to get different results but still i get 19 in the new query vs 28
Comment: @JonathanThurft Can you create a [sql fiddle](http://www.sqlfiddle.com/) with the necessary columns from each table and some sample data?


Extending a function to obtain continuity

Question: I am working on a two part problem for studying. Not homework. Not exam prep.
The problem is
Let $f\colon(0,1]\rightarrow\mathbb{R}$ be a uniformly continuous function on $(0,1].$
a.  State the definition of uniform continuity and use it to show that $g(x)=\ln x$ is not uniformly continuous on $(0,1]$,
b.  Prove that $f$ can be extended uniquely to a continuous function on $[0,1]$.
I know how to do part a but don't know how to prove the extenstion portion in part b.
Answer: Take any sequence $\{x_n\}$ convergint to $0$. It is of course Cauchy sequence. Using uniform continuity show that $\{f(x_n)\}$ is also Cauchy sequence in $\mathbb{R}$. Hence it have a limit. Since $\{x_n\}$ is arbitrary $f$ have a limit at $0$. The rest is clear.
In fact the more general result holds. Let $X$ and $Y$ be a metric spaces and $Y$ is complete, then every uniformly continuous function $f:X\to Y$ have unique extension onto the completion of $X$ and moreover this extension is also uniformly continuous.
Answer: Let $(x_n) \in (0,1]^{\mathbb N}$ be such that $x_n \to 0$. We will prove that $(f(x_n))$ converges, as $\mathbb R$ is complete, it suffices to prove that $(f(x_n))$ is Cauchy. Let $\epsilon > 0$, by uniform continuity, there is an $\delta > 0$ such that $|x-y| < \delta$ implies $|f(x)-f(y)|< \epsilon$. As $x_n \to 0$, $(x_n)$ is Cauchy, hence there is an $N$ such that $|x_n - x_m| < \delta$ for $n,m \ge N$. So $|f(x_n) - f(x_m)| <\epsilon$ for $n,m \ge N$.
As for every sequence $x_n \to 0$, $\lim_{n\to\infty} f(x_n)$ exists, the value of the limit does not depend on $(x_n)$. So $\lim_{x\to 0^+} f(x)$ exists, and
$$ \bar f(x) = \begin{cases} f(x) & x > 0\\ \lim_{x\to 0^+} f(x) \end{cases} $$
is the unique continuous extension of $f$.