Number of reference sequences in a SAM file

Question: From a single record, I can get the reference sequence ID from the field rID, but how can I get the total number of different reference sequences stored in the whole SAM file?
It can be simple as just looping through all records, but I need some other solution.
Comment: By `rID` are you talking about `RNAME` (reference sequence name) field? That's in the header.
Comment: rId is the current reference Id of the record and rNextId is the mate pair reference id.
Answer: There are multiple ways. Here are two:

samtools idxstats ‹bamfile›
samtools view -H ‹bamfile› | grep '^@SQ'

Both commands give you a list of the references in the BAM file. To get their number, simply append | wc -l. But note that idxstats also outputs a final entry, *, which doesn't correspond to any reference but to all unmapped reads. So subtract that from the number.
However, beware that while this lists all references associated with a BAM file, not every reference necessarily has records associated with it. So there might be no reads mapping to a given reference. This is the third column in the idxstats output. So, to get only those references with at least one mapped read, we can filter for those:
samtools idxstats ‹bamfile› | awk '$4 != 0' | head -n-1 | wc -l

Oh, and these (and other) commands work on BAM files, not SAM. The idxstats command additionally needs the BAM index, since it's actually reading information from that index file, not the BAM (this also means that it only works on sorted BAM files). Working on SAM would require looping through the whole file, which is quite inefficient. You should generally be working with BAM rather than SAM, so this is hopefully not a restriction.
To do the same on a SAM file, you need to iterate over the file:
awk '{print $3}' ‹samfile› | sort -u | wc -l

Or:
awk '{refs[$3] = 1} END {for (ref in refs) print ref}' ‹samfile› | wc -l

Answer: A SAM file stores alignments to a set of reference sequences.  However, those reference sequences are not usually stored in the file. Instead, they will be in a separate sequence file that is usually in FASTA format. You can get the number of reference sequences stored in that file using the command
grep -c '^>' reference.fasta


What are the concerns of using Crate.io as a primary datastore?

Question: If I am correct, crate (crate.io) is backed by Elasticsearch (Lucene). Weren't there a few articles a month ago that said that ES lost some writes under heavy load? Are there any other concerns?
Answer: You are right, Crate is backed by Elasticsearch. We think that the guys at elasticsearch are doing a great job on improving data consistency. A good read is http://www.elasticsearch.org/blog/resiliency-elasticsearch/ which gives a pretty good overview about efforts towards reliability. We at Crate are confident that this storage engine is safe to use as primary store. We also see, that issues regarding this area are getting actively worked on by the Lucene and Elasticsearch Community.
Answer: I am currently evaluating Crate.io as a primary datastore for work. As the above answer is vague and unspecific, maybe it's time for an update on this question here. There is a Dec.2016 keynote presentation out there from the Jepsen author Kyle Kingsbury on Youtube who investigated Crate.io for some problems with the resiliency in Elasticsearch. The first 8 minutes are introduction, the Crate.io part is from 23:50 till 31:10.
For those of you who don't want to watch the full video, here is a short summary.
First, the test setup. They set up databases and a random pattern of clients with random queries. Also, they voluntarily introduced problems for the databases, like network partitioning. Secondly, the results. According to Kingsbury, there are two issues with ES resiliency. Both of them carry on to Crate.io. Let's get to the details...
Dirty reads
The first one -  ES #20031 - is that ES may cause dirty reads, divergence and lost updates if network partitions occur. As of now - December 2017 - this issue is still open. In my opinion, it is possible for the same problems to occur if a node is unresponsive for extremely heavy duty, like during extensive querying, reindexing or garbage collection.
Lost updates
According to Kingsbury, there is another problem ("Can promote stale binaries") with ES that cause updates to get completely lost when network partitioning occurs. It has been tagged as #20384 and there is kind of a fix which Kingsbury summarizes as "partial". So, ES may still cause lost data upon writing.
What does ES say?
On the official site of ES about resiliency, only one of the two problems - #20384 - is mentioned. It has been marked as solved in the version 5.0 release notes, although the official site says that there is only a partial fix.
What does Crate.io say?
On the Crate.io documentation on resiliency, there is a list of known problems with Crate.io resiliency. The ES bug #20384 is commented as partially fixed and still causing an open problem. The ES bug #20031 is not mentioned. However, there is a paragraph about an issue with networking partition which Crate.io marked as fixed - so the official page is kind of inconclusive here.
Conclusion
Kingsbury concluded in December 2016 that Crate.io should not be used as the primary data store. It could be used of course as a replication of your primary data to benefit from the time series database features that Crate.io offers. He also suggests that for machine data where 5% data loss is not a severe problem, Crate.io is a viable option as primary store.
It is my impression that some bugs Kingsbury reported may have been fixed but not all.


How to prevent exceptions bubbling up in C#?

Question: If I'm writing a class library, and at some point in that library I have code to catch an exception and deal with it, then I don't want anyone using my library to know that it even happened - it should be invisible from the outside world.
However, if they have "Catch Thrown Exceptions" turned on in Visual Studio (as opposed to "Catch User Unhandled Exceptions") then the exception will be visible to them.
Is there any way to avoid this?
Answer: No. This is by design: as a developer, I run with "Catch Thrown Exceptions" turned on, so that I can see exceptions thrown in library code (and hopefully avoid them). The situation you're in applies equally to the .NET framework's own libraries too.
The best way would be to avoid throwing the exception in the first place. As a side benefit, you library code will be faster, since throwing an exception has a noticeable impact on performance (and should only be used in 'exceptional' circumstances).
Answer: The only way you can pull this off is if you put a [DebuggerHidden] attribute on the method that may throw the exception. Like others have pointed out, better to avoid the exception altogether, but this attribute will accomplish what you want.
Comment: Thank you - passing this on to the people at Project White so that I don't have to see an exception every time I call into UI Automation code that destroys the object being called.
Answer: You cannot prevent this. Someone can always attach an debuger to the process and monitor what is going on.
You could just remove the exception and provide the error handling yourself, but I would really not recommend that because it is some kind of reinventing the wheel - recreating the exception handling system.
The said applies of course only if the code throwing and the code catching the exception are far apart and quite unreleated. If they are tightly coupled, you should really check if the call can succeed and only call in this case. Always remeber that exception are intended for exceptional cases - not for normal control flow where you could check if the operation can succeed
Answer: As Tim Robinson suggests there is no way to control someone viewing exceptions thrown from your library.  His answer is good so I won't rehash it.
There are a couple of posts here on SO that you may find helpful when addressing (what sounds like) using exceptions as program flow control:
Catching exceptions as expected program execution flow control?
Why are .Net programmers so afraid of exceptions?


Schedule Mic Recording

Question: Is there a way (automator maybe?) or program to make an iMac record the microphone input on a scheduled time (start and finish). I need it like some kind of security webcam but for audio
Answer: This post explains something similar to what you are trying to do. I think that you can easily modify the workflow so it fits what you need starting from there.
Quote:

Set up your workflow Launch Automator and in the New Template sheet
  that appears, select Service and click Choose. Build a workflow that
  contains these actions: New Audio Capture, Start Capture, and Stop
  Capture (all under Movies). In the Start Capture action enable the
  Wait For Capture To Complete option. In the Stop Capture action enable
  the Close Movie After Stopping option. Configure the top of the window
  to read Service Receives No Input in Any Application. Save your
  workflow and give it an intuitive name such as Voice Memo.
Voice memo window When you activate your workflow, the small Audio
  Recording window will appear. If you now click Automator's Run button,
  QuickTime Player will launch, a new audio recording window will
  appear, and your Mac will start recording from the sound input device
  selected in the Sound system preference (from your iMac or MacBook's
  microphone, for example). When you're finished recording, just press
  the spacebar and your recording will be saved, the audio recording
  window will close, and you'll find your voice memo saved as Audio
  Recording.mov in the Movies folder within your user folder.
  (Subsequent recording will be called Audio Recording followed by a
  number—Audio Recording 1.mov, for example.)

Schedule Mic Recording


Is a soap and water gas leak detecting solution more likely to cause rust than the store's version?

Question: Will a water and soap solution (one tsp of soap in a cup of water) cause a pipe to rust more than BrassCraft Gas Plastic Water Heater Gas Leak Detector?
Comment: Usually also a bit of glycerine for more bubble persistence (take longer to pop, so easier to see.) Which is, of course, also easy to DIY. Or you can get a premade version that comes with a bubble-blowing wand at "mass produced children's toy" pricing.
Comment: I doubt there's a list of ingredients on that bottle (unless it has an MSDS), but I'd be shocked if it were anything _more_ than soapy water... It probably has instructions to _not_ shake it, as that will cause the soap to bubble.
Answer: Neither should cause any problem if the solution is dried off after.
Answer: Absolutely dish detergents with chlorides corrode gas line metal! My lines were installed 5 years ago and the residue the plumbers'"soapy water test" left behind ate holes in the metal.  Use what the gas company recommends.
Comment: Are we talking about black iron pipe here, brass fititngs as you'd find with CSST, or copper tubing?
Answer: Rinse and dry after testing if you are nervous. Dawn attests that it is non-corrosive.


Bug? "Users with less than 100 reputation ..."

Question: Not sure if that's the right place to report this.
I've got 100 reputation on cooking SE. However, when I try to post two questions within 20 minutes, it says "users with less than 100 reputation can only post questions every 20 minutes; try again later". Clearly, that's either a bug in the "Ask Question" module or merely in the error messages.
Answer: right, this was a fencepost error. You needed 1 more rep. I changed > to >= there.


Is there a reason why it was said that the distance between the seat tube and the rear wheel should be as small as possible on a road bike?

Question: I recently saw a steel road bike in a road bike shop where the distance was well over 1cm. 99.9% of old road bikes had a very small distance (~5mm). At the time, they thought it was more aerodynamic. Is the distance still a quality feature from today's perspective?
Comment: Lack of clearance limits the range of tires that can be used.  Additionally, lack of clearance prevents the use of fenders.  But low clearance looks sexier, and that is a major design consideration for many bikes.
Answer: The distance will depend on the tyre width you choose for the stage on that day. Today's road bikes allow a wider range of tyre widths partially thanks to the adaption of disc brakes. For time trial bikes this is less of an issue and the manufacturer can count with one particular tyre size.
But the gap could indeed lead to some unnecessary wake behind the seat tube. Aero bikes today will often feature a cutout that will allow even smoother transition.
This picture is a gravel bike, so even bigger range of tyres considered and some mud clearance necessary, but still an aero one.

A pure road racing bike may be much more extreme

The seat tube acts as a sort of fairing (I could not remember the right English word when writing the initial version of the answer). True fairings are not allowed by the UCI competition rules, but can have a strong effect, especially on the front wheel, as shown, for example, by https://www.bikeradar.com/news/null-winds-technology-fairing/ or https://www.renehersecycles.com/aerodynamics-of-gravel-bikes/
Photos from Cervélo official bike photographs.
Answer: This hasn't necessarily always been about aerodynamics, although it can be. There have been bikes with super-short chainstays for a long time; the most extreme example is the Rigi Bici Corta, which predated aero bikes, and used an un-aerodynamic split seat tube to tuck the rear wheel in more closely.
The reason for this is that a short wheelbase gives more responsive handling, and shorter chainstays should be less flexible, which is a benefit in racing.
To some extent, this is probably  a consequence of the time the bike was built, when nearly all frames were made of steel tubes with standard dimensions. Today, racing bikes are often made of carbon fiber, and designers can put more carbon where they need it to compensate for longer chainstays. Also, fashions and philosophies in frame design change over time, and the focus on fast handling that was in the forefront back then is no longer emphasized as much. Bikes today are designed to balance comfort, stability, and responsiveness better.
Comment: Indeed, front wheel rising from the ground when riding steep uphills is "responsive". The bicycle responds to your pedaling by becoming a unicycle!
Comment: That's true, this has been a thing even a long time ago. Even in the 1970s or 1980s one can easily recognize an old Favorit (the only locally available - and with big difficulties - road bike brand) as a racing one (e.g. Favorit F1 Special) or a consumer one from the wheelbase length.
Comment: @VladimirFГероямслава The Favorit frames that made it to Yugoslavia (rebranded to Rog) mostly have _very_ long chain stays.
Comment: @jayded-bee No wonder, the racing ones mostly went to the west or to domestic organized racers and were very hard to obtain. An example: https://www.bike-forum.cz/foto/detail/47804-favorit-f1-special-1979  Still not extremely short, but too short for fenders.
Answer: In addition to Vladimirs answer:
Wider tires are more comfortable and better suited for rough surfaces.
At the same time they can have less rolling resistance than slimmer tires.
But slimmer tires have less air resistance at the same rim depth as wider tires.
The designer of the frame has to balance between aerodynamics and rolling resistance/comfort.
What's best depends on the riding you as rider do. A quality frame will give you the best aerodynamics for a given tire width. But just tire clearance alone is not a quality feature of the frame.
Answer: There is a reason and it's not for your benefit.
Bicycle manufacturers want to sell bikes. The more bikes they sell, the more profit they make.
A general-use bike would be an absolute disaster for them, since all cyclists would buy this general-use bike and not buy more bikes after that.
If a bicycle manufacturer makes the distance between seat tube and rear wheel very small, you can't ride your road bike on forest paths since dirt stuck on the tire will scrape away the paint from the seat tube. Thus, you need a gravel bike or a mountain bike. If the bicycle manufacturer made the distance large, you could ride road bike on a forest path and nobody would ever buy gravel bikes or mountain bikes.
Similarly, if a bicycle manufacturer makes the distance between seat tube and rear wheel very small, you can't fit wide tires. This limits the carrying capacity of the bike, meaning you need a touring bike should you travel long distances with heavy cargo.
Also, if a bicycle manufacturer makes the distance between seat tube and rear wheel very small, it's impossible to fit fenders. Thus, you need a commuter bike.
See? For a job one bike could do (a road bike), they sold four (road bike, gravel or mountain bike, touring bike, commuter bike).
Me myself, I only buy bikes which can fit wide tires WITH fenders and still have enough clearance that the wide tire won't scrape the fender when riding on forest paths. It's getting hard to find these kinds of bikes. My electric bike is irreplaceable, those models are no longer made (and it's not reasonable to build your own electric bike since mid-drive manufacturers have specifically made it hard to build your own to discourage "tuning" the bike which could bypass the 25 km/h speed limit). My non-electric bike I have built from parts.
Comment: *It's getting hard to find these kinds of bikes.* uhhhh, it's never been easier to find this kind of bike.
Comment: In fact manufacturers very often sell generalist bikes: the entry-level ones.
Comment: This answer would be better without the hyperbole. Obviously with a MTB one can do things one wouldn't be able to do with a road bike with wider tires and vice versa. And a "one generalist" bike in between will obviously be a compromise about those functions.
Comment: Let me get this straight, you want a single frame to race on tarmac, do downhill, gravel/XC, tour, haul, and commute? The frame has to be wide and aero, you want fenders, and storage racks. I genuinely don't get it, these parameters can't coexist in one bicycle. I for one prefer owning 3 or 4 bikes that do their jobs well than one "jack of all trades, master of none" frankenbike.


Prevent upvote model from being called for every comment

Question: I have three models: User, Comment and Upvote. User-to-Comment has a one-to-many relation, Comment-to-Upvote has a one-to-many relation and User-to-Upvote has a one-to-many relation.
I want to do something similar to the upvoting done on Stackoverflow. So when you upvote/downvote the arrow will highlight and remain highlighted even if you refresh the page or come back to the page days/weeks later.
Currently I am doing this:
<% if Upvote.voted?(@user.id, comment.id) %>
  <%= link_to '^', ... style: 'color: orange;'%>
<% else %>
  <%= link_to '^', ... style: 'color:black;'%>
<% end %>

where the voted? method looks like this:
  def self.voted?(user_id, comment_id)
    find_by(comment_id: comment_id, user_id: user_id).present?
  end

So if I have 10 comments on a page, this will load an upvote from my database 10 times, just to check if it exist!
There has to be a better way to go about doing this, but I think my brain stopped working, so I can't think of any.
Comment: You probably shouldn't be calling voted on the `Upvote` class. If you think about the action of voting, this isn't something that the `comment` does, but rather the `user`. I would move the method into the `User` class.
Comment: On a side note, instead of doing `find_by().present?`, it might be better to do `exists?()`
Answer: Assuming you have properly set relations
# user.rb
class User
  has_many :upvotes
end

we can load comments, current user and his upvotes:
# comments_controller.rb
def index
  @comments = Comment.limit(10)
  @user = current_user
  user_upvotes_for_comments = current_user.upvotes.where(comment_id: @comments.map(&:id))
  @upvoted_comments_ids = user_upvotes_for_comments.pluck(:comment_id)
end

And then change if condition in view:
# index.html.erb
<% if @upvoted_comments_ids.include?(comment.id) %>
  <%= link_to '^', ... style: 'color: orange;'%>
<% else %>
  <%= link_to '^', ... style: 'color:black;'%>
<% end %>

It will require only 2 DB queries. Hope it helps.
Comment: If you also use a "has_many through" association, and define user --> upvotes --> comments, you can then perform the same as this with a join and a single hit to the db.
Comment: You could also save yourself a map and reduce the size of the database query by doing `@comments = Comment.limit(10).pluck(:id)`
Comment: @williamcodes comments objects are required to be displayed on the page, so we can't use `pluck`
Answer: We can do it the following way if you want it to be handled by a single query.
Lets make sure the relations are proper
# user.rb
class User < ActiveRecord::Base
  has_many :comments
  has_many :upvotes
end

# comment.rb
class Comment < ActiveRecord::Base
  belongs_to :user
  has_many :upvotes
end

# upvote.rb
class Upvote < ActiveRecord::Base
  belongs_to :user
  belongs_to :comment
end

Then in the controller
def index
  current_user = User.first # current_user may come from devise or any authentication logic you have.
  @comments = Comment.select('comments.*, upvotes.id as upvote').joins("LEFT OUTER JOIN upvotes ON comments.id = upvotes.comment_id AND upvotes.user_id = #{current_user.id}")
end

And in view
# index.html.erb
<% @comment.each do |comment| %>
  <% link_color =  comment.upvote ? 'orange' : 'black' %>
  <%= link_to '^', ...style: "color: #{link_color}" %>
<% end %>
# And all of your logics ;)

Answer: If you're limited to N comments per page then you can probably do this in two queries using the limit and offset methods to return the 1st, 2nd, ... ith set of N comments for the ith page, something like (syntax may be off, Ruby isn't my primary language)
comment_ids =
    Comments.select("comment_id")
            .where(user_id: user_id)
            .order(post_date/comment_id/whatever)
            .offset(per_page * (page_number - 1)) // assumes 1-based page index
            .limit(per_page)

This gives you a list of comment_ids which you can use to query Upvote:
upvoted_comments =
    Upvotes.select("comment_id")
           .where(user_id: user_id, comment_id: comment_ids)

If you're sorting the comment_ids by a column that also exists in Upvote (e.g. if you're sorting by comment_id) then you can replace the Upvote set query with a range query.
Put upvoted_comments in a hash and you're good to go - if the comment_id is in the hash then it's been upvoted, else not.
Answer: I'm not sure this will avoid excess queries in this state but maybe you could include the upvotes when you fetch comments:
@comments = Comment.includes(:upvotes).where(foo: 'bar').limit(10)

Then in the view:
<%=
  link_color =  comment.upvotes.map(&:user_id).include?(@user.id) ? 'orange' : 'red'
  link_to '^', ...style: "color: #{link_color}"
%>

Comment: I would be in the same situation hitting my DB 10 times, querying for the existence of an object.
Comment: I liked your change to the view, it's cleaner than what I had.
Comment: I updated it, but I'm wondering if it will cause increased queries still.
Comment: How about

`link_color = comment.upvotes.detect{|upvote| upvote.user_id == @user.id} ? 'orange' : 'red'`


Which method should I use in writing?

Question: When I am writing, should I let my thoughts flow naturally on the paper, or should I meticulously think them through and form full sentences out of them before putting them to paper? I'm really not sure which one I should use since I have a writing test tmrw and im panicking intensly. When I write naturally, I don't even think about the idea  am writing about, I just start writing from the first word that comes to mind even if it doesn't relate then i connect it into the main idea.
Comment: I'm voting to close this question as off-topic because it is not about the usage of English. It is a request for writing advice.
Comment: You should do both.  That's the tricky part about writing.
Comment: Without wishing to be rude, it is fairly obvious to me that, when writing your question, you just "let [your] thoughts flow naturally on the paper" *without* "think[ing] them through and form[ing] full sentences out of them before putting them to paper."  This made your question much longer than it need be; makes it more apparent that you're "panicking intensly"; and makes it harder for someone else to read and thake in.  So, I tgink I have answered your question for you!
Answer: I personally use the scrap paper, which is often available during such tests, to write down my thoughts like you described, in a natural manner. Then after I finished a paragraph I start reorganising my sentences if needed and write it down on the answer sheet.
My method is not said to work for you as well, it works for me and many others. You can give it a try, but you'll have to figure out by yourself what works best for you personally.
Lastly there is no need to panic, based on how you wrote your question I'm sure you'll do just fine.
Comment: Writing is like life, you have to think with someone else's head or its relevance is lost.

Which method should I use in writing?


Question about bias-variance trade off

Question:
This question is from a uni module about machine learning. I'm a bit stuck as I can't relate it to the bias-variance trade-off, to me the question implies all models have something to do with the trade off but I can only think of B being overfitted on its training data implying a low bias and high variance. I don't know how to explain A having both a high error in testing and training, and C I'm lost.
Answer: It seems to me differently:
B. An example of small bias and variance.
A. A large bias (low quality at the training stage).
C. A large variance (losses for different data vary greatly).
But all this is said, assuming that the loss scale does not need to be taken literally. Otherwise, I also don't know how to interpret graphs A and C: absolutely the same losses on the test, which do not depend on the quality of training.
Comment: thanks :), I see where I was I wrong now, these graphs were confusing me for a while and I wasn't thinking about it properly

Question about bias-variance trade off


What application can I use to increase fan speed of MacBook Pro under Windows 7?

Question: On OS X Lion I use smcFanControl to increase fan speed. What application can I use on Windows 7 on MacBook Pro?
Answer: I've used SpeedFan with Windows running in a Bootcamp partitions to access temperature data and control the fan speeds on an iMac. He's very quick to turn around unsupported chipsets and the software tells you if you should report your chipset to the author for addition.
Comment: I can't increase fan speed. I go in Configure -> Fan, and see no fans listed
Comment: Report this to the SpeedFan dev and he can help you out with chipset support.
Comment: Done so, but no feedback. Lubbo's MacBook Pro Fan Control is turning my fans to max rpm and shows 90 C for GPU#2 temperature.
Answer: Macs Fan Control does the job well. There are both Windows and Mac version available for free.


New error when editing membership: Argument 1 passed to CRM_Financial_BAO_Order::setOverrideTotalAmount() must be of the type float, string given

Question: This error seems to be connected with the update to version 5.36 as it just appeared after that.
When editing an existing membership or adding a new membership the following error appears in the logs:
TypeError: Argument 1 passed to CRM_Financial_BAO_Order::setOverrideTotalAmount() must be of the type float, string given, called in C:\wamp64\www\civicrmd8\httpdocs\sites\all\modules\civicrm\CRM\Member\Form.php on line 486 in CRM_Financial_BAO_Order->setOverrideTotalAmount() (line 152 of C:\wamp64\www\civicrmd8\httpdocs\sites\all\modules\civicrm\CRM\Financial\BAO\Order.php).
I feel it could be connected to https://github.com/civicrm/civicrm-core/pull/19476/files
A quick fix I found was to change line 486 of civicrm/CRM/Member/Form.php from
$this->order->setOverrideTotalAmount($formValues['total_amount']);
to
$this->order->setOverrideTotalAmount((int) $formValues['total_amount']);
But I am not quite sure if this really solves the issue or what sideeffects I do not see. Maybe this type casting should be done earlier in the process? or maybe the problem lies somewhere else? In my case the value of $formValues['total_amount'] is an empty string but I do not know where this value comes from.
Comment: thanks Tobias. It also impacted Stripe payment gateway
Comment: I'm seeing this issue too, in civiCRM version 5.36.0
Answer: Just for the record - the issue is solved in CiviCRM version 5.36.1


Clipping with multiple overlapping polygons while maintaining unique IDs and overlap

Question: I've got a series of square overlapping polygons. I want to clip a layer based on these polygons and maintain the unique ID and overlap of the polys. As it is now, if I do a clip using overlapping polygons, the clip will automatically merge all the unique polygons (see attached) by basically assuming the square polygons are one big mask. You can see that many of the square polygons overlap significantly and will have nearly identical clip results-which is exactly what I want. Aside from clipping one polygon at a time (there are 3,000+ of them), I cannot figure out a solution. There don't seem to be any options to tell ArcGIS to turn off the automatic merge.
Comment: Did you try Union and then Dissolve on the Unique ID from each original polygon?  The overlaps will split the polygons more than you want, but if you dissolve the result you should end up with the duplication you want to occur in the overlapping areas.  You should exclude from the dissolve all portions where the blue polygon FID equals -1.
Comment: What do you mean 'maintain unique id'? You cannot keep OBJECTID/FID values - they are controlled by the system that they'e stored in. If you want to keep these values then create a field (long) and field calculate the OBJECTID/FID into it, now that the values are in a static field they wont change during clip/union/intersect. I'd go with the previous comment by @RichardFairhurst, then dissolve by any important attributes - when you dissolve only the dissolve attributes will exist in the output, so if it's important it *must* be a dissolve field.
Comment: Are you wanting to duplicate the blue polygons for each square? Because that's not really just a clip. It's more like a Split, except I don't know that would work with overlapping split features or not. And while I see what Richard is getting at, if you want what I think you do then I don't see how you'd do it without an iterative model running clip for each square and ending up with a *lot* of stacked polygons.
Answer: Use Intersect and then Dissolve.  See the result below of my use of these two tools.  It duplicates the blue polygon for all overlapping square polygons and preserves the FIDs of both layers in new fields.  A dissolve that includes both FID fields ends up with each original square's intersection with each blue polygon it touched. It works.
Comment: Chris W - Actually Union will work exactly the same way for the overlapping portions, but it includes areas that are not needed.  Both tools will duplicate all overlapping portions the same way, and the Intersect portion of the Union output can be isolated with a query.  In my example the Union Output query equal to an Intersect output is FID_FLOOD > -1 AND FID_SQUARES > -1.  But the Union tool also includes all non-overlapping areas, which are not necessary in this case.  I tend to use Union, because often I do need to include the non-overlapping areas for comparisons to the original areas.
Comment: Ah-ha! I was wondering about Intersect vs Union in your comment earlier, and thinking Union wouldn't work because there would be no overlap/duplication like there would with Intersect, so you'd have to use multiple dissolves to generate the desired result.
Comment: You're right - I was either misremembering or had just completely forgotten what happens in a union where there are overlapping features *within* one of the inputs. For some reason I was thinking each piece of overlap became a separate polygon with the id/attributes of the originals, period, but as you say anything in the same fc is actually duplicated (or rather just cut up - not really duplicated since it's all there to start with) so then anything with a match in a different fc would have two polys to union to.


Aligning a button to the center

Question: I have a simple submit button. I am wanting to align it to the center. Here is my code:
<input type="submit" name="btnSubmit" value="Submit" onClick="Submit" align="center">

However, it does not work. What is the best/easiest way to do this?
Answer: You should use something like this:

    <input type="submit" />

Or you could use something like this. By giving the element a width and specifying auto for the left and right margins the element will center itself in its parent.
<input type="submit" style="width: 300px; margin: 0 auto;" />

Comment: This isn't quite right. You posted two different ways of accomplishing the task. One of them is correct, the other wrong. You can use `text-align: center` on the parent which is correct. But he may not want everything in the parent to be centered. Adding it just for centering would be wasteful markup. The addition of `margin: 0 auto;` to this solution is unnecessary. That is a separate method. It requires the submit button to have a `width` defined. You should correct your current answer and probably post the second solution also.
Answer: Here is what worked for me:
    <input type="submit" style="margin-left: 50%">

If you only add margin, without the left part, it will center the submit button into the middle of your entire page, making it difficult to find and rendering your form incomplete for people who don't have the patience to find a submit button lol. margin-left centers it within the same line, so it's not further down your page than you intended.
You can also use pixels instead of percentage if you just want to indent the submit button a bit and not all the way halfway across the page.
Answer: For me it worked using flexbox, which is in my opinion the cleanest solution.
Add a css class around the parent div / element with :
.parent {
display: flex;
}

and for the button use:
.button {
justify-content: center;
}

You should use a parent div, otherwise the button doesn't 'know' what the middle of the page / element is.
If this is not working, try :
#wrapper {
    display:flex;
    justify-content: center;
}

Answer: margin: 50%;

You can adjust the percentage as needed. It seems to work for me in responsive emails.
Answer: Add width:100px, margin:50%.
Now the left side of the button is set to the center.
Finally add half of the width of the button in our case 50px.
The middle of the button is in the center.
<input type='submit' style='width:100px;margin:0 50%;position:relative;left:-50px;'>

Aligning a button to the center


Ajax submissions using SproutForms

Question: I need to submit a form, using SproutForms, via AJAX, so i can get the response and then show some "gated" content on the page. The content (i.e. PDF link, etc) is tied to a particular entry page, so i'd like to stay on that page and not doing a normal POST to a generic success page. I can't find any info on the SproutForms plugin page on how to do this, just that it's supported (noted in the change log). Please help
Answer: I figured it out (edited with my FORM mark-up as well):
I'm actually rendering the FORM using the SproutForms method:

    {{ craft.sproutForms.displayForm(block.gatedContentForm.first().handle) }}

and then my JS looks for any form submissions from a ".submit-via-ajax" block
// process the form
$('.submit-via-ajax form').submit(function(event) {

    // get the form data
    var formData = $(this).serialize();

    // process the form
    $.ajax({
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url         : 'sproutForms/entries/saveEntry', // the url where we want to POST
        data        : formData, // our data object
        dataType    : 'json', // what type of data do we expect back from the server
        encode          : true
    })
        // using the done promise callback
        .done(function(data) {

            // here we will handle errors and validation messages
            if (data.success == true)
            {
                // show/hide content/elements
            }
            else
            {
                // show an error
            }
    });

    // stop the form from submitting the normal way and refreshing the page
    event.preventDefault();
});

Comment: Glad you figured it out. We'll consider adding an example to the docs. As you've shown here, the general principles of submitting Sprout Forms over ajax are the same as any other form you'd submit over ajax, we aren't doing anything fancy there and Sprout Forms will give you back a response in json to work with as necessary.
Comment: carbonjoetunis, would you be willing to share your Form code, as I am attempting the same (just Ajax submission at this stage) but having some troubles.
Comment: edited the original post to include how i'm rendering the FORM mark-up.

Ajax submissions using SproutForms


Arch linux can't login

Question: My problem is that I can't login. If I try to loggin with correct username and password it doesn't do anything. I have error message on boot failed to create static device Nodes in /dev . This happened after sudo pacman -Sy xterm and restart of the system. My kernel version is 4.1.6-1-ARCH This is not my image but by this I mean loggin session..
Comment: Has your OS a ready-to-use emergency/recovery mode? Even if it hasn't, playing with kernel boot parameters in the bootloader, one can say the kernel to run at the `s` (single user mode) runlevel, or even without a genuine init (`init=/bin/bash`). Then examine the root file system for damage.
Comment: "can't login" isn't a problem report usable for experts.
Comment: @IncnisMrsi better?
Comment: @IncnisMrsi i have added two images.
Comment: It seems you have something really, really wrong with your shared libraries. What did you do prior to this happening?
Comment: I have installed xterm.
Answer: Libncurses was recently updated from /usr/lib32/libncursesw.so.5 to /usr/lib32/libncursesw.so.6. There would have been a matching bash update, but you don't have it.
In fact, I just found this in my own pacman.log:
[2015-09-19 23:45] [ALPM] upgraded ncurses (5.9-7 -> 6.0-3)
[2015-09-19 23:45] [ALPM] upgraded readline (6.3.008-1 -> 6.3.008-3)
[2015-09-19 23:45] [ALPM-SCRIPTLET] /usr/bin/bash: error while loading shared libraries: libncursesw.so.5: cannot open shared object file: No such file or directory
[2015-09-19 23:45] [ALPM] upgraded bash (4.3.042-1 -> 4.3.042-3)

This is why you should update everything or nothing.
You should get a LiveCD, mount the drive, and do the updates like this:
pacman --root=/path/to/mounted/root -Suy

Comment: I have fixed it :) but thanks :) .
Answer: I had this exact same issue after doing a full system upgrade.
Installing the updates with pacman --root=/mnt -Syu as described by "ams" did not resolve the problem for me; instead I had to symlink the library, i.e.
cd /usr/lib
ln -s libncursesw.so.6 libncursesw.so.5

However, after doing this, I can't run gnome-terminal (I have this issue: gnome-terminal stopped working). That's probably not related to the ncurses issue, though.
Comment: Linking the two together is unlikely to work properly because the two libraries have different binary interfaces.
Comment: If you need nurses 5, use the [AUR version](https://aur.archlinux.org/packages/ncurses5-compat-libs/)
Comment: Ignore what I previously wrote about xterm input being messed up. I had recompiled xterm ages ago with some... let's just say experimental modifications, left it in /usr/local/bin, and forgot about it. Upon moving that binary elsewhere, xterm is absolutely fine.
Comment: and do a `pacman -Syu` after that.

Arch linux can't login


How to open regular Firefox after Firefox portable has been open

Question: I noticed when Firefox portable is opened, then the regular Firefox is launched, it actually launches Firefox portable again. For example say Firefox portable has the add on No Scripts and the regular Firefox (installed in Program Files or wherever) has Ad Block Plus installed, then if I open the portable Fire Fox, and then the normal Firefox, I am certain the computer just opened a new window for the portable Firefox because it doesn't have Ad Block Plus and does have No Scripts. Is there a way to have both versions of Firefox opened at the same time? Is this bad to do?
Answer: Haven't tried it, but I think you'd be better off with two portable folders, both configured  to AllowMultipleInstances  in the FirefoxPortable.ini file in FirefoxPortable\Other\Source.
After editing the file, save it and give it another shot.
Answer: Have you tried using -no-remote and a -profile <path> as parameters for that second call. (doing it from command line resp. creating and editing a respective windows shortcut).
Without -no-remote, any 2nd, 3rd "opening" just opens a new window of the already-open firefox profile, no matter what it is, no matter, what -profile says...  (I believe, also no matter if portable or installed version(s)).
Also see here.


Is there any AMPscript live editor available?

Question: I am constantly checking my AMPscript code using the subscriber preview in Contact Builder. Any way to make my life a bit easier?
I'm already using Sublime Text + syntax highlighter.
Answer: The best way I have found for this is to have a third party server that hosts the AMPScript file you are working on.  From there you put a HTTPGET inside of a Cloud Page that is aimed at that file's URL.
This way you can work on the file on your server via Sublime or whatever editor you choose, save it then refresh the Cloudpage to 'Live Preview' your edits without needing to go back into the SFMC UI.
Now this does come with drawbacks as it requires a Cloudpage view ($$$) every time you refresh and it requires you to have access to a third party hosting server to save your file ($$$), but it can be a life saver and much more efficient workflow if used responsibly.
Answer: There's no live editor. You have to compile the AMPscript -- just as the OMM does in the platform.  To reduce the time between iterations, I like to use drive-letter access on a web server and edit locally.  (You can do it with Dropbox if you know a few URL tricks.)
I use the HTTPGET() AMPscript function to pull in the content from the web server like this:
<code>%%=TreatAsContent(HttpGet(Concat("http://example.com/your-page-or-email.html?x=",GUID())))=%%</code>
Then when everything is functional, then I copy the code from the web server back into the Cloud Pages and publish it.
This method also works for email development.
As part of writing The AMPscript Guide, I reworked the AMPscript Highlighter package for Sublime Text 3.  You can download it through Package Manager: AMPscript Syntax Highlighter
Answer: Uhm, unfortunately no.
The only thing i do is:
Having a dataextension with all columns with all possible values and use a for loop inside a cloudpage to lookup "subscriber data" and evaluate all ampscript i write with it.
But some stuff cannot be tested there like personalization strings like emailaddr or _messagecontext ofc.
I believe there is no great way. Often i do it exactly like you (sublime text3 with ampscript highlighting and then copy it to a newsletter).


What are some debugging helpers or tips/tricks in your Mathematica toolbag?

Question: I am a novice so imagine my confusion with Mathematica's very poor error and trace messages. Debugging should be an easy thing to do even for beginning programmers but not with Mathematica. What are some tricks/tips or tools you use for debugging especially for beginners?
Comment: A few interesting tools in the [Tuning and Debugging Guide](https://reference.wolfram.com/language/guide/TuningAndDebugging.html) as well.
Comment: Similar: [Mathematica Debuggability](https://mathematica.stackexchange.com/q/2230/142)
Answer: One of the easiest debugging methods all beginners do is drop Print[var] statements throughout code. Sometimes it is difficult to interpret the output when many Print statements are used so beginners often do something like Print[Row[{"x: ",x}]] rewriting the variable name twice. However this is unnecessary if you know how to access a variables symbol name. For that reason I created a simple short function that only requires writing the symbol once as an argument.
SetAttributes[{prt}, HoldFirst];
objectName = Function[Null, SymbolName[Unevaluated[#]], {HoldFirst}];
objectName::usage =
  "objectName@# returns Unevaluated shortened SymbolName.";
prt[symbol_] := Print[Row[{objectName[symbol], symbol}, " \[Rule] "]];

it is used like this...
x=123;
prt[x]

should output...
x -> 123

if x is nested inside a function, block, module, etc. and it doesn't work you may need to add fnname to the SetAttributes[{prt,fnname},HoldFirst] in the first line above.
Comment: Yes, but Print has many disadvantages also. The main is that it clutters the code, so the code becomes harder to read with many call to print in the middle of the algorithm. Mathematica needs an easy to use debugger. In Matlab, I never needed print() to debug. If there is a problem, I tell the debugger to stop at an error, or break point at some function and very quickly find the error. In Mathematica debugging is much much harder specially as the program getting larger.
Comment: `Print` also has the disadvantage that it returns `Null`. I like to add [`Echo`](https://reference.wolfram.com/language/ref/Echo.html) instead, which returns its input as output as well as printing it out, so it acts as a convenient "pass-through" that can typically be added almost anywhere. You can also label its output using the two argument syntax of `Echo`.
Comment: `statements are only temporary` and the minute you think the code is OK and you remove them, you'll find a new problem, and then you end up wasting time typing them all over again. I've been there and done that. And if you put too few print statements, then you find you need more since the ones you have do not give enough information. Overall, using print for debugging is so 1980's these days. Notice that I am not talking about logging here. That is different thing. Logging is very important, and used for example by web servers all the time and that serve different purpose.
Comment: The way I do things now, if have print statements, that I can turn on/off by a flag. But keep them there. But as I said, the code becomes hard to read, since there are many of them, and I do not know when I might need them again so I keep them but turned off when not needed to see. For small program, debugging is easy. I am talking about large programs here, with 10's of functions or more and and complex algorithms in many places.  When the program gets over about 1,000-1,500 lines is the tipping point for me when I might need a good debugger.
Comment: ... but I agree with @Nasser 's sentiment: a decent debugger would be very nice indeed.
Comment: @MarcoB `Print[...]` statements are only temporary and only placed in strategic locations of interest. But I like your suggestion of using 'Echo[...]`.


Capacitor, stored energy versus reactive power

Question: When an AC voltage U is put onto a loss less capacitor C the capacitor will require a certain reactive power Q (current 90 degress out of phase with the voltage):
$Q=UI = \omega C U^2$ in VAr (Only reactive power, no real power)
I can also determine the reactive power strating from the stored energy in a capacitor:
$E= (1/2) C U^2$
With $ Q=dE/dt $ using Fourier transformer to go to the frequency domain: $ Q=\omega E$
Filling in the equations results into: $Q=(1/2) \omega C U^2$
You can now see my problem. Deriving the reactive power of a capacitor from voltage / current / capacitance results in factor 1/2 difference compared to deriving reactive power derived starting from energy stored in a capacitor.
Can you help me with what I'm missing or doing wrong.
Answer: When you use complex notation, you have to use a 1/2.
The energy stored in a capacitor is given by:
$$
E = \frac{1}{2} Re(U I^{*})
$$
with * the complex conjugate and $Re$ denote the real part.


How does one interpret the meaning of a stochastic derivative?

Question: My understanding of derivatives is in the difference quotient limit sense... How does one interpret the meaning of a stochastic derivative?  How can one possibly differentiate a random variable?  What is its physical meaning, if it has any?
Comment: What are you differentiating your random variable with respect to?
Comment: Then it could sound like what you're looking at is actually a continuous-time stochastic _process_, which is formally a random variable that takes values in a function space, interpreted as a function of time. One can certainly speak about differentiating the particular function that is the value of the process in one experiment, which will give you another function-valued random variable. (I'm not saying that _is_ what you're looking at -- you're providing precious little context for your question, so it's impossible to be sure of anything).
Comment: Let's say that it's a derivative with respect to time...
Comment: And if it were a derivative with respect to space?  How different would its meaning be?  Can we still think of it as an instantaneous rate of change?  If it is a truly random variable, it's instantaneous rate of change can take on an infinite number of possible values (i.e. it's not unique)...  Thus, how can one use this information meaningfully?
Comment: I think you'll need to disclose more context if you want any truly satisfying explanation. The best I can say without more is that if you have given a random _function_ $F$ (formally a map from the sample space into a space of functions), then they derivative of that function is another random function $G$, such that for each particular point in the sample space the $G$ at that point in the sample space is the derivative of the $F$ at that point in the sample space. This is not a priori meaningless.
Comment: For example one could speak of "a random smooth temperature distribution in the plane" (and one would then have to specify a particular probability distribution for that choice) and then ask what is the probability that the temperature gradient at some particular point is greater than 5 kelvin per meter. This question is about a random variable (the temperature gradient) that arises as the derivative of the random temperature distribution.
Answer: As pointed out in the comments, there is some context missing in your question, so I'll just guess to fill it in: Let's talk about one-dimensional Brownian motion, which is a stochastic process: It is a family of random variables indexed by a continuous parameter, which is usually called "time" and is written as $B_t$.
Another point of view is that Brownian motion is a probability measure on a suitable set of functions. Since it can be shown that Brownian motion has continuous sample paths with probability one, we can think of it as probability measure on the set $C[0, T]$, the set of of continuous functions
$$
f: [0, T] \to \mathbb{R}
$$
In addition, one can prove that Brownian motion has with probability one sample paths that are not differentiable and not even of bounded variation. This means it is not possible to define a Riemann-Stieltjes integral with respect to the sample paths. This is why one needs to develop a new concept of an integral with respect to Brownian motion, for example the Ito or the Stratonovich integral. It is possible to give precise meaning to the expressions like this one:
$$
X_T = \int_0^T f(t, x) d B_t
$$
and prove (with appropriate assumptions for $f$) that there is a unique stochastic process $X_T$ satisfying this relation. These integral equations are usually abbreviated, with an abuse of notation, as
$$
d X_t = f \; d B_t
$$
but one has to keep in mind that the symbol $d B_t$ is actually undefined. Only the integral with respect to Brownian motion is defined in the Ito- or the Stratonovich calculus. This means that there is no "stochastic derivative", and that the notion of "velocity" is undefined for Brownian motion. There just is no room for the interpretation of a "velocity" in physical terms in the theory.
Comment: The question was about "stochastic derivatives". What you described in a few paragraphs is Ito/Stratonovich *integration*, and ended up with the unhelpful "there is no stochastic derivative".
Comment: Continuity of paths of the Brownian motion is the definition, what do you mean it can be proven?
Answer: There is some ambiguity associated with the term "stochastic derivative". It can mean "Nelson derivative" and "Malliavin derivative", for example.
The definition I use is the following:

A real-valued stochastic process $\{ X(t) \}$ is said to be stochastically differentiable (differentiable with probability one, differentiable in the $L_p$ sense) at a point $t_0$ if there exists a random variable $\eta$ such that, for $t \to t_0$,
$$ \frac{ X(t_0) - X(t) }{t_0 - t} \to \eta$$
in probability (with probability one, or in $L_p$ respectively). The random variable $\eta$ is called the stochastic derivative of the process at the point $t_0$, and is denoted $X'(t_0)$.

In other words, even though $\{X(t)\}$ may not be differentiable, there is an $\eta$ from which we can make the approximation
$$ X(t) = X(t_0) + (t_0 - t) \eta + r(t) $$
where $r(t)$ is a remainder small enough in probability or in a $L_p$ sense.
For differentiability in probabiliy, we have
$$r(t) = op(|t_0 - t|)$$
which means that for any $\epsilon > 0$,
$$\lim_{t \to t_0} P\left( \left|\frac{r(t)}{t_0 - t}\right| \ge \epsilon\right) = 0$$


Desire2Learn API does not return data

Question: I'm using D2L's API sample site to test out their API before I begin any development and I have noticed a few issues. When I request to be authenticated, I am redirected to our D2L instance to login. However, I am not redirected back to the sample site after authenticating. If I return to the sample site and authenticate again, then the user id and key are populated because of my D2L session. But when I request "get versions", no data is returned or if I request "who am I", I get a "Invalid JSON primitive" because the sample site is expecting to format a string from the response but there is nothing in the response. Anyone out there have a solution for this?
Comment: Can you please let us know which language version of the API sample you're using?
Answer: Your report seems like it could indicate that your back-end service is not respecting the <code>&x_target=appURL</code> parameter passed in at the end of the first stage of the authentication process. Perhaps your back-end service needs to support the deep linking required to redirect back to a passed in target parameter URL?

Desire2Learn API does not return data


How to develop website for mobiles using asp.net(C#)

Question: Is there any tool available for developing mobile websites using asp.net (C#)...
or else any other tool???
Answer: The same tools as you develop any other websites in C#: typically, Visual Studio.  A mobile website only differs in presentation and in some capabilities (eg: javascript/css may be limited), but functionally it's the same as a "non-mobile" site.
There's no fundamental difference between regular cross-browser development and mobile development.  You're still writing the same code, the same markup, etc.  You probably need to be more aware of the limitations of the browser than usual, but that doesn't change the tooling or process.
Is there a particular problem you're having that you can't solve?
Answer: If you are going to develop a website for mobiles (as opposed to a native app), then the server side language does not matter that much. It's more a matter of the css and client-side framework (if any) you are using.
One option would be to use asp.net mvc on the server side and jQuery Mobile or http://jQtouch.com for the client side. There are also other options, but these are the best I have found for my own use.
Answer: As other people have said, if it's a website you're developing then the tools are the same as any non-mobile website.
Another option for the client side is Sencha Touch.
Answer: Take a look at Mobile Device Browser File (http://mdbf.codeplex.com/). Actually that particular project is no longer supported, but it used to work quite well. It basically automates a lot of the leg work of identifying the mobile client and rendering the right styles and script. You may be able to find something similar with a bit of searching.


Cookie Behavior

Question: If cookies are disabled in a browser, can we create a non persistent cookie which will get destroyed when the browser is closed?
Answer: go through below links, will clarify your doubts.
1) Session Cookies.
2) Persistent Cookies.
3) Managing Cookies.
4) Creating Session Cookies.
Answer: No. What the browsers do with your cookie is up to them. You can only offer them one, not dictate what they do with it.
My browser is set up to ask me if I want to accept cookies, and if I want to I can override their expiration to browser exit.
Answer: Persistent cookies are permanent cookies.They are stored as a text file in the hard disk of the computer.
Non-persistent cookies are stored in browser processor in temporarily. Its also called in memory cookies. Non-Persistent cookies are otherwise called as temporary cookies.They are active as long as the browser remains active.They are also called as session based cookies.Once the browser is closed the cookies vanishes automatically.
Non-persistent cookies are cookies in any way. So if cookies are disabled, it includes disabling all types of cookies i.e locking the browser out of writing any data to the main memory or the file system.
However if you wish to store session information you can use cookie less sessions, which obviously use the alternative of adding a session key to the address.

Cookie Behavior


How to get entity manager or transaction in jpa listener

Question: I was using Hibernate event listener like PostDeleteEventListener, PostInsertEventListener, PostUpdateEventListener to do some operations during insert, delete and update. Now I would like to use JPA listener to do this because if I like to move from Hibernate to any other JPA provider my listener should work. Hibernate listener gives me event from which I can get the transaction and check whether its committed or rollback. JPA listeners only provides me the entity object. Now how can I get the transaction or session or entity manger in the JPA listener?? Thanks in advance!! I am using Jboss as my CMT.
Answer: This is not supported as of JPA 2.0.
In JPA 2.1 (slated to be in Java EE 7), the persistence provider will treat entity listeners as CDI beans when in a managed environment (such as the JBoss app server). From the Proposed Final Draft of the JPA 2.1 spec, page 96:

Entity listener classes in Java EE environments support dependency
  injection through the Contexts and Dependency Injection API (CDI) [ 10 ]
  when the containing archive is a bean archive. An entity listener
  class that makes use of CDI injection may also define lifecycle
  callback methods annotated with the PostConstruct and PreDestroy
  annotations. These methods will be invoked after injection has taken
  place and before the entity listener instance is destroyed
  respectively

So in JPA 2.1, if you create a CDI producer that provides EntityManager (simply by annotating a @PersistenceContext field with @Produces), you can just @Inject the EntityManager into the listener.
In the mean time, I'm not aware of any clean or pleasant workaround. The "least worst" thing I can think of would be to configure the EntityManager to be bound in JNDI, then obtain it through a JNDI lookup from within the listener.
Answer: In my case I'm using this code:
ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();
auditLogService = (AuditLogService) ctx.getBean("auditLogService");

This works well to me.
The code of this application is available to download at https://bitbucket.org/macielbombonato/apolo
I hope that this can help you.
Comment: this should be noted as "an answer", but the explicit answer (for the general case) would be, obtain the entityManager via JNDI lookup, but the specific binding to use would be container specific (JBoss, Glassfish, Weblogic, etc.)
Answer: You can use all pre/post load, insert, update or delete listener in JPA by using two ways:

By using annotation.
An simple example of using a Listener could be where an entity has a transient variable that needs to be populated after the entity has been persisted, updated or loaded, like:
public class AvailableCreditListener {
    @PostLoad
    @PostPersist
    @PostUpdate
    public void calculateAvailableCredit(Account account) {
        account.setAvailableCredit(
            account.getBalance().add(
            account.getOverdraftLimit()));
    }
}

The entity class would be annotated with @EntityListeners:
@EntityListeners({AvailableCreditListener.class})
public class Account extends BaseEntity {
    private BigDecimal balance;
    private BigDecimal overdraftLimit;
    @Transient
    private BigDecimal availableCredit;
    // getters and setters
}

By using persistence.xml configuration file.

Finally, instead of annotations, an XMl mapping file can be used and deployed with the application to specify default listeners. (This mapping file is referenced by the persistence.xml file.) But an entity can use the @ExcludeDefaultListeners annotation if it does not want to use the default listeners.
@ExcludeDefaultListeners
@Entity
public class Account extends BaseEntity {
    ....
}

In your persistence.xml:
<persistence-unit-metadata>
    <persistence-unit-defaults>
      <entity-listeners>
        <entity-listener class="samples.AvailableCreditListener"/>
      </entity-listeners>
    </persistence-unit-defaults>
  </persistence-unit-metadata>

Comment: My question is how to get the entityManager in AvailableCreditListener  class
Comment: i have same question


Accounts in serverside JavaScript (node.js)

Question: I'm making an online game and I was wondering - how can users create accounts? Do I need a database, and if yes, which one? Also how do I get information from the users? I believe by using html  tag, but how exactly? I'm not using PHP for the serverside, but node.js.
Answer: There are so many answers to this question it's tough to begin at one place.
I'll just suggest some technologies because that seems to be what you're looking for. Ultimately I recommend you research this area and make up your own mind on what you'd like to use.
You can use a database to store the user information. NoSQL is popular nowadays so I'll go for a MongoDB solution http://www.mongodb.org/
You don't exactly need to use HTML tags as there are template solutions written for node.js. I recommend jade https://github.com/visionmedia/jade
There are frameworks and middleware created to make all of this easier. Check it out here https://github.com/joyent/node/wiki/modules
Comment: @bane You certainly can, but you may not want to. Take a look, for example, at [this question](http://stackoverflow.com/questions/2356851/database-vs-flat-files) or [this question](http://stackoverflow.com/questions/2392017/sqlite-or-flat-text-file) or [this question](http://stackoverflow.com/questions/1499239/database-vs-flat-text-file-what-are-some-technical-reasons-for-choosing-one-over), etc.
Comment: Hey, thanks for the answer, but databases seem a little bit too complicated, can't I just create a file that contains all the passwords and usernames along with the information?
Comment: http://stackoverflow.com/questions/7292477/node-says-jade-has-no-method-renderfile-why

Take a look at this question please, I have some problems with Jade.
Comment: Nothing wrong with flat files. As of node v0.5.x you can require JSON files so having a quick and easy JSON store may be a good solution. There's more flexibility with a database though so you may want to consider that.


Can I prove my app uses randomness right way?

Question: We are developing an iOS app which employs Shamir Secret Sharing algorithm. We made all possible steps users can trust us. We can't remember their secrets nor we can save encoded fragments. But they still may not trust us with randomness. Is there any cryptographic method how user can verify we are using random number generator honestly and have no malicious interests?
Comment: In the end the user must trust the app developer... Code is too complex to fully trust. Having code reviews and some way to securely deliver the code to the device does help; security isn't black or white.
Comment: If there's sharing going on, is it possible for the user to supply the randomness?  I guess that you still can't prove that the app would use it though.
Comment: Yes. User can supply the randomness. I was also thinking this way.
Comment: ...I was also thinking this way. If there is some way how user can supply his own randomness and then verify on different machine that we have used it.
Comment: Literally 1000s of truly random bits are generated from sensor noise when you take a low light photo on a webcam/phone.  There's your user randomness.  It's a huge TRNG built into every phone and most laptops.  I fear verifying it's use is impossible.
Answer: Nothing you show the user within the app could prove that the numbers were truly generated randomly and that the numbers weren't leaked maliciously or accidentally.
In general, you could make your application (or the module that does the cryptography, assuming it's built into a separate binary like a library or an executable used by the main app) open source and use a reproducible/deterministic build process so that users can compile the source themselves and verify that it matches what they've installed. I'm not sure how feasible or convenient this may be on the iOS ecosystem though. (Users might need a rooted phone to be able to view the app's binary installed from the app store, etc.)
Answer: A real-life example that's relevant is Diceware, where users generate strong, uniform random passphrases by rolling dice and looking the results up in a numbered wordlist.  Diceware's virtue is precisely that it's understandable and auditable by people who grasp very little beyond the elements of probability theory.  But of course it doesn't wholly remove the requirement that the user audit or trust the cryptography because the passphrase still has to be input into some software.
So one thing you could do is offer the users the option to enter random inputs that are under their control, like dice rolls, passphrases, or the old PGP trick of asking them to mash keys "at random" on the keyboard and measure the timings. The program would then apply a key derivation function (salted with values from the system RNG) to these inputs to obtain a master key or seed, and drive the random choices off that.  There are some challenges that I think you would need to solve, like:

User experience.  None of this sounds awesome for usability, to say the least.
Depending on the details of the problem, whether to use a password-based key derivation function or a fast one like HKDF.
Comment: This isn't really the issue though.  There are many  ways for the user to enter strong entropy into an app (simply take a low light photo).  This issue is that the app can just ignore that input and do it's own thing anyway.  Look the lies and deceit that Google uses to track users.  Apps have form on this, especially if there is financial or law enforcement encouragement.
Comment: Exactly. Those user inputs may fool inexperienced user but not experienced one who knows we can just ignore all user inputed data and used our own non-random.
Comment: @PaulUszak: I thought of that while I was writing this response.  What I concluded in the end is that the analogy to Diceware still is valuable in this context.  The same criticism could be raised of Diceware—why bother rolling dice to come up with a strong passphrase when the program that you enter this passphrase into might be backdoored?  The answer is it eliminates *one*, not all things that could go wrong for the user.  And don't forget that the one case we do know of a secret NSA cryptographic backdoor is an RNG; if there's any place where such procedure is merited, this might be one.


Difference between width and device-width in CSS media queries

Question: What is the difference (in simple terms) between height and width and device-width and device-height?
Comment: related: http://stackoverflow.com/q/5725838/399317
Answer: device-width is the...

width of the output device (meaning the entire screen or page, rather than just the rendering area, such as the document window).

Source.
The width...

describes the width of the rendering surface of the output device (such as the width of the document window, or the width of the page box on a printer)

Source.
Answer: More than a late answer Hopes it will help Some one

In CSS media the difference between width and device-width can be a
  bit muddled, so lets expound on that a bit. device-width refers to the
  width of the device itself, in other words, the screen resolution of
  the device. Lets say your screen's resolution is 1440 x 900. This
  means the screen is 1440 pixels across, so it has a device-width of
  1440px. Most mobile phones have a device-width of 480px or lower,
  including the popular iPhone 4 (with device-width: 320px), despite it
  technically having a 640 x 960 resolution. This is due to iPhone 4's
  retina display, which crams two device pixels into each CSS pixel on
  the screen. This is true for the Ipad 3 as well; its reported
  device-width is 768px just like its predecessors, even though its
  actual screen resolution is 1536px x 2048px. In general width is more
  versatile when it comes to creating responsive webpages, though
  device-width is useful when you wish to specifically target mobile
  devices (and not desktops with a small browser window for example)

as from developer.mozilla.org ,

width :
  Value:  Media: visual, tactile
  Accepts min/max prefixes: yes
The width media feature describes the width of the rendering surface
  of the output device (such as the width of the document window, or the
  width of the page box on a printer).
Note: As the user resizes the window browser switches style sheets as appropriate based on media queries using the width and height media features. !!!

i found this article very interestingly from  javascriptkit :
http://www.javascriptkit.com/dhtmltutors/cssmediaqueries2.shtml
Comment: Thank you for such detailed explanation, it really helped.
Comment: Thanks. This explains the whole topic quite nicely.
Answer: If you define device-width means your particular css is call when you open your page in iphone, ipad ,ipod & mobile device . for example :
@media only screen and (max-device-width:480px){
        body{
          color:red;
        }
    }

or if you define width which means your particular css is call when your window is resize .
for example :
@media only screen and (min-width: 481px) and (max-width: 1024px) {
        body{
         color:yellow;
        }
    }

for more info please check http://webdesignerwall.com/tutorials/css3-media-queries , http://x7.fi/2010/02/12/how-to-fit-your-website-for-the-apple-ipad/
Comment: @CengizFrostclaw width & device-width both apply on mobile devices but when we add "device-width" then the css only apply on the device not on desktop version.
Answer: If you are making a cross-platform app (eg. using phonegap/cordova) then,
Don't use device-width or device-height. Rather use width or height in CSS media queries because Android device will give problems in device-width or device-height. For iOS it works fine. Only android devices doesn't support device-width/device-height.
Answer: The device-width describes the height of the output device (meaning the entire screen or page, rather than just the rendering area, such as the document window).
Whereas the height CSS property specifies the height of the content area of an element. The content area is inside the padding, border, and margin of the element.
Source: https://developer.mozilla.org/en/CSS/
For more on media queries, see: http://www.w3.org/TR/css3-mediaqueries/


Can you move over difficult terrain with only 5 feet of movement?

Question: Assuming a character or creature with very little speed - say, 15 feet. It gets hit with a ray of frost, reducing its speed to 5 feet. It is attempting to move through difficult terrain. Can the creature in question move through the difficult terrain without dashing?
Comment: Hey there! I've edited the question to try to make the title more in line with the question. If you feel I've portrayed it wrong, feel free to roll back.
Comment: @BlakeSteel thanks, it does suit the question better.
Answer: Yes, normally - but not when using the Playing on a Grid variant rules
The basic rules say of difficult terrain:

Every foot of movement in difficult terrain costs 1 extra foot.

The default presumption of the rules is not that you are playing using a combat grid. If a creature can only move two and a half feet in one turn, they still move two and a half feet; they don't have to snap to an arbitrary grid, they can still make progress moving.
However, the Playing on a Grid variant rules state:

Rather than moving foot by foot, move square by square on the grid. This means you use your speed in 5-foot segments. This is particularly easy if you translate your speed into squares by dividing the speed by 5.
[...]
If a square costs extra movement, as a square of difficult terrain does, you must have enough movement left to pay for entering it. For example, you must have at least 2 squares of movement left to enter a square of difficult terrain.

Under these rules, a creature with only one square of movement available (because it has a movement speed of only 5ft) cannot move into a square of difficult terrain unless it Dashes (or otherwise gains extra movement), because it must have 2 squares of movement available to enter the space.
As a DM, I would probably let a creature in such circumstances move one square every other round rather than forcing them to use an action to Dash in order to make any progress. They're still considerably slowed, but they don't suffer any extra penalty compared to the default case of not using a grid.
Comment: Oh, I didn't realize that the 5-foot step isn't a thing in 5e.


Is there a way to summon Dogmeat to you?

Question: I've recently started playing Fallout 4, and I've acquired Dogmeat. Long story short, I told him to stay in a small building so I could down a few raiders quietly but I forgot about him and I can't find him. Is there a way to call Dogmeat back or do I have to retrace my steps until I'm reunited with him?
Comment: Funny, I've found my biggest hassle is making sure he stays away from me.
Answer: If you are playing on the PC, you can move him to you. I had to do this once because he clipped in a wall and never came with me when I fast traveled away.
You can do it by following these steps.
Open up the Console by typing Tilde (~)
Type 'prid 0001d162'
Hit Return/Enter
Type 'moveto player'
Hit Return/Enter
Hit Tilde (~) again to close the console
Dogmeat will shoot to you like he is being magically summoned and be next to you!
Travel the Commonwealth with your Dogmeat
Comment: I like the answer with a 100% success rate
Comment: @leinaD_natipaC Thanks, I find that this is the only way to make a follower to come to you when you need them to.
Answer: You can ask another companion to join you, at which point you should have an option to tell dogmeat to go back to one of your bases.
Answer: If you fast travel he will follow you again.
If you get another companion you will be asked where to send dogmeat.
Comment: If Dogmeat was told to "Stay", then I don't believe he'll fast travel with you.
Answer: Found out that if you do part of the quest Reunions, he will wait at Fort Hagen, even if you use 'moveto' he will instantly run there.
Comment: Welcome to Arqade! You haven't really laid it out, but it sounds like you're suggesting starting the quest to get Dogmeat to show up. That doesn't help if the player is past that quest, and is more involved than the currently accepted solution of getting another companion to follow you, even if they aren't.
Answer: If you try all of these and they don't work(especially the switching companions hint), dog meat automatically can be found again at red rocket if you didn't assign him to a settlement.
Answer: Use the Vault-Tec Population Management System console from the Vault-Tec Workshop DLC, which allows you to point companion positions on the radar and map. Or try to look at his last assigned settlement (which means where you sent him the last switch) or his first encounter spot, usually at the Red Rocket truck stop or Diamond City.
Answer: You can use a command to summon him:
1d162.moveto player


Check constraint on geometry column is not working as expected

Question: I am going through the QGIS Training Manual (16.5.2) and could not figure out why the streets table throws a violation check error as trying to update a geometry column. I checked a very similar question at violates check constraint but couldn't get any clue. I understand "GeometryType" has been upgraded to "ST_GEOMETRYTYPE".
Answer: Look closely at both your CHECK constraint definition and the function docs: ST_GeometryType returns the actual type (following the ST_ prefix) formatted in PascalCase, i.e. ST_LineString!
You'd want to recreate that CHECK like so:
ALTER TABLE streets
  DROP CONSTRAINT enforce_geometry_chk
;

ALTER TABLE streets
  ADD CONSTRAINT enforce_geometry_chk
    CHECK (ST_GeometryType(geom) = 'ST_LineString'::TEXT OR geom IS NULL)
;

However:
While you may get some insights in managing table CONTRAINTs following that tutorial, PostGIS type enforcing mechanisms have evolved significantly since it was written (which, apparently, was a looong time ago...), and by now the suggested table set-up violates best practices.
The two PostGIS specific types GEOMETRY and GEOGRAPHY allow for an explicit definition of the geometry type when used as column definition, as well as the SRID you want to enforce[¹] on your geometries, e.g. [²]:
CREATE TABLE streets (
  id     INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
  "name" VARCHAR(50),
  geom   GEOMETRY(LINESTRING, 4326)
);

While in the early versions of PostGIS this was indeed realized by adding CHECK contraints during table creation, it now is implemented via the PostgreSQL type modificator system - an addition to core data types that allows direct enforcement of dynamic, type specific restrictions (see e.g. VARCHAR(50))
The above set up follows current best practices, and has the intended behaviour - except that it also checks the SRID of the INSERTed/UPDATEted geometries. In your case, since you use the EWKT string representation with attached SRID, it will just work.

[¹]: enforce really means checked against: it will not do anything to solve issues - it just raises an error like yours
[²]: Note here that, except for "name" which is wrapped in ", all other identifiers and SQL keywords are case insensitive, so the above is equivalent to
create table streets (
  id     int generated by default as identity primary key,
  "name" varchar(50),
  geom   geometry(linestring, 4326)
);

Answer: I could figure out this issue on my own. ST_LineString is case sensitive and must be typed exactly as it is.
CHECK(ST_GeometryType(geom) = 'ST_LineString'::text

And I guess that so are all of this type of constants.
I still do not understand why it is not throwing an 'invalid geometry' error when typed with the right spelling but without the proper case.(ie. ST_Linestring)
Comment: Because that `CHECK` constraint really **only compares two strings** for equality! There is no geometry check involved, the geometry doesn't get toughed by this update at all - and the actual geometry is totally valid.


Sync only a single group of tabs in firefox

Question: I usually have multiple groups of different tabs open up in firefox. When I am working on a project across multiple computers I would like to be able to sync only a single group of tabs which are relevant to my project, and not personal tabs that I have open at home. Is there a way to do this with firefox?
Answer: Until Firefox Sync handles tab groups (that's not the case in v29), maybe you can try https://chrometabcloud.appspot.com


Why does my kitchen sink not drain properly after I don't use it for a while?

Question: I can't figure out why my kitchen sink drain keeps clogging.  I've bought several bottles of Draino type stuff and they work for a day or two.  But if I don't use my sink much in 2 or 3 days and then finally get around to hand washing my dishes (since I don't have a dishwasher) I find my sink won't drain again.  Why is it clogging when it's not being used?
Comment: What type of dwelling?  Single family home, apartment, high rise apartment?  How long has this been happening?  Also I highly recommend you don't use chemicals for unclogging sinks but instead use a hand auger.  It's better for your pipes and the environment.  Also if your trap can be easily removed, take if off and give it a good clean (just make sure you have a bucket under it when you take it off).  When you take it off, you will also get an idea of what is clogging it.
Comment: It's a one story house built in early 70s.  The sink has a built in metal cross at the drain hole that makes it impossible to get a snake through it.  I doubt it's the trap.  I believe something is growing in the pipes beyond the trap.  But other than mold what could it be?
Comment: How long does the sink run before it backs up?  Can you run the water for a minute or does it back up right away?
Comment: It doesn't back up immediately. It takes a minute. Once after I used some draino product I noticed it seemed be better at first but then eventually water backed up to the sink again.
Comment: You might want to get a plumber out to clear your line.  Could be grease build up or even roots in your line.  They will be able to tell you for sure and they will have to power auger to reach the trouble spot since it doesn't sound like it is next to the sink.
Answer: Although it's rare, it could be that the Kitchen Vent pipe is clogged, thus causing slow draingage, or now drainage.  Could be that leaves have collected there, or bugs have built a next.  Google "Kitchen Vent Pipe Clogged" and see if the articles there are helpful.
Comment: A symptom of this would be that it would drain alright with a bit of water (such as if the tap was running), but not if a large quantity of water was put down the drain at once (such as when draining the whole sink). This may help @Lauren diagnose the issue. (Also in addition to clogged vent, consider: improperly installed vent, or vented using a 'cheater valve' which is now malfunctioning)
Answer: If I were to guess and this is just a guess.  I would say you have cast iron drain.  I would say that it is rusting on the inside and that the drain itself is just a microbe of the width it used to be.
Given that it is rusting on the inside, it will get a little prickly when dry.  It will catch some food and grease and quickly clog.  I have seen this happen in dozens of homes.  I guess this because your house is at that magical 40+ years where almost all homes with cast iron start having issues.


Access to student records/grades

Question: Is it common practice within colleges/universities to allow all faculty within a division access to all student records within that same division?  (i.e., all Health Science faculty having access to all Health Science student records)
Wouldn't this violate FERPA?
Comment: @Omen:  FERPA is the Family Educational Rights and Privacy Act of 1974; it provides privacy protections for student information/records, and contains stipulations regarding the dissemination of such information.
Comment: What is 'FERPA'?
Comment: @Omen [FERPA](http://www2.ed.gov/policy/gen/guid/fpco/ferpa/index.html)
Comment: Ah okay, it is an American law
Answer: Reading FERPA, this clause states that it is appropriate given certain circumstances.

However, FERPA allows schools to disclose those records, without consent, to the following parties or under the following conditions (34 CFR § 99.31):

School officials with legitimate educational interest;
Specified officials for audit or evaluation purposes;
Appropriate parties in connection with financial aid to a student;
Organizations conducting certain studies for or on behalf of the school;

These would be closest to those that matched what you asked.
So if, for example, your HS faculty wanted to average everyone's GPA individually, he could potentially do that, as long as he doesn't post all the names in public.
Comment: @JAnderson I'm not saying all faculty do have a legitimate educational interest. I'm saying that those who do, are permitted. If a faculty member wants to do an average GPA for a class, he could potentially look at the names on an Excel sheet (even though IDs is more likely in modern day).
Comment: @JAnderson: if you are asking whether it is unacceptable under FERPA for professors to "have access" to a student's information, even if they never actually use that access, you would need to consult with a lawyer about that, because the fine details of the particular situation will be very important.
Comment: The key phrase here is, "legitimate educational interest."  All faculty, across the board,  cannot have a, "legitimate educational interest" in each student.
Comment: I have inquired, and was informed this is the way it is set up.
Comment: @JAnderson it may be argued that any professor may be interested in doing statistics on the whole student body, and that _could_ be "legitimate educational interest". If that is enough under the law, consult a lawyer.
Answer: FERPA allows for "school officials" to access confidential records when they have a "legitimate educational interest". From the U.S> Deprtment of Education web site:

One of the exceptions to the prior written consent requirement in FERPA allows "school officials," including teachers, within a school to obtain access to personally identifiable information contained in education records provided the school has determined that they have "legitimate educational interest" in the information. Although the term "school official" is not defined in the statute or regulations, this Office generally interprets the term to include parties such as: professors; instructors; administrators; health staff; counselors; attorneys; clerical staff; trustees; members of committees and disciplinary boards; and a contractor, volunteer or other party to whom the school has outsourced institutional services or functions.

So it is not on its face a violation of FERPA for professors to have access to student records.
In practice, many schools impose their own restrictions tighter than FERPA. Sometimes the school describes these restrictions as "FERPA requirements", when they are actually just the (conservative) advice of the school's own lawyers, rather than literal mandates from FERPA.
Due to these local policies, at a particular school, other faculty may not have unrestricted access to a student's grades. You'd have to inquire with a particular institution to find out their internal policies about such things.

Access to student records/grades


How to survive the curse-frogs in Dark Souls?

Question: I am in the depths, fell down a hole and died to a curse when three frog things pounced. Is there a way to block the fog, or do you just have to kill them before they burp it up?
Answer: Fog is unblockable, those frogs are nasty, I got so scared the first time I feel down that hole (there are several btw).
I don't know if they are accessible at that time, but Paladin armor and Cursebite ring helps out A LOT! Also, humanity and being in human form improves your curse defence (meaning that the meter takes longer to fill up).
They have two methods of fogging you:
Either they stay stationary and you can clearly see that they are inhaling, in order to exhale their weird fog. This is the best time to attack them, attack them from the side while they are charging up their attack.
I don't think that they will trace you once they started the animation (that is, it will face the same direction during the whole animation).
Alternately, they do a nasty jumping attack, which has a somewhat longer range. It can be kind of tricky in the way that they kind of spit out a projectile of fog, which expands around it's point of origin. Just take note where their projectile landed, and move away.
Mobility is the key here.
Remember, it's always easier with one monster at a time.
If they got you, that means that you are cursed, and that means that now is a great time to farm the frogs (I think they are called Basilisk), since getting cursed a second time won't do anything (unless you lifted the curse status, which you can do by going to the tower where you rang the first bell, and talk to the black clad NPC standing close the ladder leading up, residing in the room you enter directly after defeating the Gargoyles and buying a curse stone from him, OR by buying it (curse stone) from the dead lady behind the grates in the aqueduct between Lower Undead Burg and Firelink Shrine).
Find the bonfire in the Sewers, and then go down the stairs to the right, then climb down the ladder into the cage (inside the same room where the giant rat was), go out of the cage and walk down the stairs and then go left, trailing the waterway. If you go the right way, you should be attacked by some giant rats before you find the frogs.
Good luck, and don't let them get to you.
Comment: In the original version of Dark Souls (pre-patches), curses stacked. That means you could go from 1/2 health to 1/4 health, then 1/8 health etc if you kept getting cursed over and over. Aren't we glad it isn't like that anymore!
Comment: Nice answer, comprehensive and helpful. I shall attempt to take them down soon.
Comment: I did not know that. That's harsh, though I kind of like it better. When I was farming the frogs, before Gaping Dragon (?), and occasionally got cursed again, I was a bit disappointed in that it was no punishment. I am glad that they got the giant rats before the frogs, so that you really feel that your hp is halved, they got me more times than the frogs, due to the curse.
Answer: In addition to Apeforce's answer, there is a ring in the new londo ruins at the very end where the ladder to the top of the church is. On the bottom floor behind the building off to a ledge there is an item. A ghost ambushes you when you try to take it but the ring gives you around 100+ curse resistance making you basically immune to curse while wearing it. I have personally basked in the awful curse gas of the frogs and had nothing happen to me using that ring.
In case you don't know, to kill ghosts you need to be either A: Actually cursed or B: Use a transient curse item (You get three at the start of new londo from a corpse). After that you're free to kill ghosts who drop more of the item.
It's a fairly hazardous journey but once you know the path and all the ghost ambushes, you can easily grab the ring and enjoy immunity from curse.
Comment: I don't know if I am up for new londo yet - it just about takes it out of me when I (am forced to) take on more than one zombie dog, let alone ghosts - but the freedom from curses sounds great.
Comment: It is very dangerous unless you're use to it, even then I can die a few times before I get the ring if I try to rush through. Fair warning though, that church is CRAWLING with ghosts. At least 10+
Comment: not entirely sure as i haven't played the game in a while, but isn't the holy sword (that you can find in front of an undead dragon out on the cliffs, as well as a shield and something else) able to kill ghosts, or am i just remembering that incorrectly? i know it is extremely useful in the catacombs since if you play the rogue(?) you can get to it very early with the universal lockpick thingie. also note that you can get to the cliffs via the same area you go to to get to the ruins.
Comment: I know divine weapons don't inherently kill ghosts (I main a dex/faith user). That specific weapon may have special attributes. No idea.


Finiteness of Hausdorff measure of balls

Question: Let $(X,d)$ be an arbitrary metric space and let $\Bbb B(x,r)$ denote the closed ball with center $x \in X$ and radius $r>0$. For $p\geq 0$, let $H^p$ denote the $p$- dimensional Hausdorff measure. Under which assumptions on $X$ and $p$ is $H^p(\Bbb B(x,r))< + \infty$? Is this always the case even if the Hausdorff dimension of $X$ is infinite?
Answer: As a counterexample, let $X$ be an infinite-dimensional normed space. For $\varepsilon<r/2$ it follows from Borsuk-Ulam that you need more than $n$ closed sets of diameter $\varepsilon$ to cover the intersection of the boundary $B(0,r)$ with an $n$-dimensional subspace (because these sets are free of antipodal points). Hence, the Hausdorff measure of $B(0,r)$ (actually already of its boundary) is infinite for every $p\ge0$.
Comment: @JohnD: If your space is countable, then take counting measure.  If it is uncountable and separable, then you can pull back Lebesgue measure via a Polish-space isomorphism to $\mathbb{R}$.  If it is inseparable, then that sounds like a hard problem.  (Do you consider a nontrivial measure on a separable strict subspace trivial?)
Comment: An infinite-dimensional normed space is a famous example where no natural approach is known. In practice, all "usable" measures on such spaces have the property that most sets have infinite measure. If you want to have a ball with a finite measure in such a space, the measure becomes very unnatural (not translation invariant, extremely weighted, most sets have measure 0, etc.).
Comment: Thanks for the answer! Follow up question: are you aware of a general method to define a finite(nontrivial) measure on the Borel sigma algebra of an arbitrary metric space?