Probability that a 2 was rolled, given an even number has been rolled

Question: I've been learning conditional probability and encountered the problem statement given in the title. We roll the die only a single time:
My method of solving the question:
A: Event that the die rolled a 2
B: Event that the die rolled an even number
P(A) = 1/6
P(B) = 1/2
Then we have P(A|B) = P(A,B)/P(B) = (1/6)*(1/2)/(1/6) = 1/2. In some places, the answer was given as 1/3. Is this method correct? Also how can we find P(A,B) when we only have a single throw of a die.
Answer: Had you not been provided with the knowledge that the die rolled an even number i.e. in case of simple probability, the probability of rolling 2 on single throw of die would have been $1/6$ as there are $6$ possible outcomes. But in this case of conditional probability, there are only three possible outcomes viz. $2,4,6$ once you are told that the die rolled an even number. This makes the required probability $1/3$.
Also the formula for conditional probability $ P(A/B)=P(A\cap B)/P(B)$ gives $P(A/B)= (1/6)/(1/2)=1/3$ as the probability of rolling an even number is $1/2$.
My earlier answer had $P(A)$ in the numerator which was erroneous although that yielded the correct answer as $P(B)$ and $P(A\cap B)$ were same.
Comment: Isn't the formula for conditional probability consisting of P(A AND B) as the numerator? When do we use that formula
Comment: @shawnin damnen $P(A/B)$ means the probability of occurrence of event $A$ given that event $B$ also took place. This has the effect of decreasing the number of possible outcomes and thus increasing the probability as compared to simple probability scenario. You can't use P(A&B) here as here events do not take place one after the other. These two events take place simultaneously.
Comment: @shawnin damnen We use P(A&B) in case of two independent events where the occurrence of one does not have any effect on the occurrence of the second event. E.g. in case of two throws of a die one after other. In the case at hand, both events are connected to the same principal event i.e. single throw of a die. Once you say that the die rolled an even number, numbers $1,3,5$ are precluded from getting rolled.


The Real World - Systems Architect and Systems Administrator - What is the difference\what am I doing?

Question: I realize that terminology in this field can be slightly ambiguous and that there is obviously some overlap in roles, but hopefully some context will help. I had much fun this last six months designing and implementing a new workflow from the developers to the end users, and for the persons maintaining the system for my University.
This consisted of implementing database servers, web servers,a project management system, and a Mercurial repository system. I also have been tying different parts of the system together with some automation to improve workflow and make it easier on the developers. I was basically in charge of most of the systems we chose (I was a developer for the same team for the 1.5 years prior to this), and working out all the details. I am hoping to have time to further upgrade this into a Puppet driven solution with easy support for clustering (fault tolerance) in mind.
Does this fit under Systems Administration, Systems Architecture, or something else all together? I have had a phenomenal amount of fun doing this (it's exciting to goto work every day), and I want to know the proper area to set my sights on.
I've already read the Wikipedia posts. Mainly just want to know what the above duties primarily fall into, because frankly my limited knowledge makes the Wikipedia reference feel ambiguous in the context of the above.
Answer: Well...
In Theory:

Systems Architect interacts with end users and designs the basic architecture of the system. Primarily this is generating requirements, not specifications.
Systems Engineer designs and builds stuff (more like what you described).  This would include the actual specifications.
Systems Administrator keeps it all running later.

In Reality:

The three job titles are frequently used interchangeably in IT and there's usually some aspect of all 3 in the jobs.

I don't hear "systems architect" used outside of sales organizations typically...  Usually "engineer" is somebody that designs and builds for another organization and they later run it themselves; while "administrator" works within the organization.  What you describe absolutely sounds like work a "system administrator" does to me, and specifically sounds like the kinds of things I've done in multiple jobs where I had the title "System Administrator" or something like that.
Note also: "architect" and "engineer" are protected terms in some jurisdictions and their usage by people without the proper credentials can be frowned upon.


Prove: $\int_{0}^{\pi}\frac{x\tan x}{\sec x+\cos x}dx = \frac{\pi^{2}}{4}$

Question: How to prove following?
$$\int_{0}^{\pi}\frac{x\tan x}{\sec x+\cos x}dx  = \frac{\pi^{2}}{4}$$
Answer: Let $I$ denote your integral. Make the substitution $x\mapsto \pi-x$ to get that
$$\begin{aligned}I &=\int_0^\pi \frac{(\pi-x)\tan(\pi-x)}{\sec(\pi-x)+\cos(\pi-x)}\,dx\\ &=\int_0^\pi \frac{(x-\pi)(-\tan(x))}{-\sec(x)-\cos(x)}\,dx\\ &= \pi\int_0^\pi\frac{\tan(x)}{\sec(x)+\cos(x)}\,dx-I\end{aligned}$$
Thus one sees that,
$$I=\frac{\pi}{2}\underbrace{\int_0^\pi \frac{\tan(x)}{\sec(x)+\cos(x)}\,dx}_{J}$$
Now, we can rewrite $J$ as
$$J=\int_0^{\pi}\frac{\sin(x)}{\cos(x)^2+1}\,dx$$
Making the obvious substitution $\cos(x)\mapsto t$ gives us
$$J=\int_{1}^{-1}\frac{-dt}{t^2+1}=2\int_0^1\frac{dt}{t^2+1}=\frac{\pi}{2}$$
Thus,
$$I=\frac{\pi}{2}J=\frac{\pi^2}{4}$$
Comment: +1. Essentially my answer integrates $\dfrac1{1+t^2}$ by writing it as $1-t^2 + t^4 - t^6 \pm \cdots$.
Answer: $$\dfrac{x \tan(x)}{\sec(x) + \cos(x)} = \dfrac{x\sin(x)}{\cos(x) \cdot \sec(x) + \cos^2(x)} = \dfrac{x \sin(x)}{1+\cos^2(x)} = \sum_{k=0}^{\infty} (-1)^kx \sin(x) \cos^{2k}(x)$$
Hence,
$$I = \int_0^{\pi} \dfrac{x \tan(x)}{\sec(x) + \cos(x)} dx = \sum_{k=0}^{\infty}(-1)^k \int_0^{\pi} x \sin(x) \cos^{2k}(x) dx$$
Let $I_k = \displaystyle \int_0^{\pi} x \sin(x) \cos^{2k}(x) dx$. Replacing $x$ by $\pi-x$, we get $$I_k = \int_{0}^{\pi} (\pi-x) \sin(x) \cos^{2k}(x)dx = \pi \int_0^{\pi} \sin(x) \cos^{2k}(x)dx - I_k$$
Hence,
$$2I_k = \pi \int_0^{\pi} \sin(x) \cos^{2k}(x)dx = \pi \cdot \dfrac2{2k+1} \implies I_k = \dfrac{\pi}{2k+1}$$
Hence,
$$I = \sum_{k=0}^{\infty}(-1)^k I_k = \pi \left(\sum_{k=0}^{\infty} \dfrac{(-1)^k}{2k+1}\right) = \pi \cdot \dfrac{\pi}4 = \dfrac{\pi^2}4$$


Hard time with escape character

Question: I need to strip out a few invalid characters from a string and wrote the following code part of a StringUtil library:
public static String removeBlockedCharacters(String data) {
    if (data==null) {
      return data;
    }
    return data.replaceAll("(?i)[<|>|\u003C|\u003E]", "");
}

I have a test file illegalCharacter.txt with one line in it:
hello \u003c here < and > there

I run the following unit test:
@Test
public void testBlockedCharactersRemoval() throws IOException{
    checkEquals(StringUtil.removeBlockedCharacters("a  c\u003e\u003E\u003c\u003C"), "a  b  c");
    log.info("Procesing from string directly: " + StringUtil.removeBlockedCharacters("hello \u003c here < and > there"));
    log.info("Procesing from file to string:  " + StringUtil.removeBlockedCharacters(FileUtils.readFileToString(new File("src/test/resources/illegalCharacters.txt"))));
}

I get:
INFO - 2010-09-14 13:37:36,111 - TestStringUtil.testBlockedCharactersRemoval(36) | Procesing from string directly: hello  here  and  there
INFO - 2010-09-14 13:37:36,126 - TestStringUtil.testBlockedCharactersRemoval(37) | Procesing from file to string:  hello \u003c here  and  there

I am VERY confused: as you can see, the code properly strips out the '<', '>', and '\u003c' if I pass a string containing these values but it fails to strip out '\u003c' if I read from a file containing the same string.
My questions, so that I stop loosing hair over it, are:

Why do I get this behavior?
How can I change my code to properly strip \u003c in all occasions?

Thanks
Answer:
hello \u003c here < and > there

the \u003c in an ASCII file won't do it, you need to put the actual Unicode character in a Unicode encoded text file.
Answer: When you compile your source file, the very first thing that happens--before any lexing or parsing--is that the Unicode escapes, \u003C and \u003E, get converted to the actual characters, < and >.  So your code is really:
return data.replaceAll("(?i)[<|>|<|>]", "");

When you compile the code for the test against the string literal, the same thing happens; the test string that you wrote as:
"a  c\u003e\u003E\u003c\u003C"

...is really:
"a  c>><<"

But when you read the test string from a file, no such conversion occurs; you end up trying to match the six-character sequence \u003c with the single character, <.  If you really want to match \u003C and \u003E, your code should look like this:
return data.replaceAll("(?i)(?:<|>|\\\\u003C|\\\\u003E)", "");

If you use one backslash, the Java compiler interprets it as a Unicode escape and converts it to < or >.
If you use two backslashes, the regex compiler interprets it as a Unicode escape and thinks you want to match a < or >.
If you use three backslashes, the Java compiler turns it into \< or \>, the regex compiler ignores the backslash, and it tries to match < or >.
So, to match a raw Unicode escape sequence, you have to use four backslashes to match the one backslash in the escape sequence.

Notice that I changed your brackets, too.  [<|>] is a character class that matches <, | or >; what you want is an alternation.
Comment: Thanks for all: the explanation, catching my mistake about the brackets, and providing the fix I was looking for.
Answer: Looks to me that the problem isn't with your escaping, but with the fact that you have unicode data you're trying to parse.
Have you tried using the two argument version of readFileToString, replacing your readFileToString(File) call with readFileToString(File, Encoding)?
Resources

FileUtils

Hard time with escape character


Reindexing in R with data.table?

Question: Here is a frequent problem i've come across recently in R with data.table
I have an index table, say DT1. The column x would be a subset of indexes. I would be working with a subtable of a bigger rawtable using these indexes. the subtable typically would be indexed from 1 to N. (thats the column y)
then for example, i would come across a table with pairs of indexes with the original indexing, and i want to know the corresponding new indexing.
Here's what it looks like
DT1 <- data.table(x=c(0,3,5),y= c(11,22,33))
DT2 <- data.table(x=c(3,3,0,0,5),x=c(0,5,0,3,5))
# > DT1
#    x y
# 1: 0 11
# 2: 3 22
# 3: 5 33

# > DT2
#    x x
# 1: 3 0
# 2: 3 5
# 3: 0 0
# 4: 0 3
# 5: 5 5

Here is a tortuous way i found
cbind(DT1[DT2[,1,with=FALSE],on="x"][,2,with=FALSE],DT1[DT2[,2,with=FALSE],on="x"][,2,with=FALSE])
#     y  y
# 1: 22 11
# 2: 22 33
# 3: 11 11
# 4: 11 22
# 5: 33 33

a more basic way to do this with sapply gives the same result
tab=DT1$x
lookup <- function(value){DT1$y[which(tab==value)]}

colnames(DT2) <- c("x","xx")

ans <- as.data.table(cbind(sapply(DT2$x,lookup),sapply(DT2$xx,lookup)))
colnames(ans) <- c("y","y")

However,
the first solution looks a bit ugly to me
I don't like the second one, because I need to define assign a value to tab each time i use the function lookup in lapply.
if I had to lookup in different tables, i would have the choice either to create a new lookup function specific to that table, or to store in memory in a (temp) variable tab.
perhaps there is a way to do the lapply with a function of two variables
 lookup <-function (tab,value) {...} ? that i don't know
I'm sure there are many other ways.
I'm not sure what i'm doing exactly with the first solution. basically the syntax in data.table has to do with (inner and outer) JOINS. but in the final output, i want to keep the original order of the table DT2. setting column x as a key for DT2 would sort that column, making stuff like merge being not adapted to that ?
I'm willing to hear from you what is the best implementation, - i'm sure there are many better ones - and also , the most efficient when dealing with very very large tables.
Comment: `DT2[, lapply(.SD, function(x) factor(x, levels = DT1$x, labels = DT1$y))]`?
Comment: @AnandaMahto - very neat codewise, though this is using `data.frame` syntax in parts. I'm not sure of a neat way around that though.
Comment: @FaguiCurtain, from `?data.table`: *.SD is a data.table containing the Subset of x's Data for each group, excluding any columns used in by (or keyby).* Since we don't specify any "by", `.SD` applies here to all the columns.
Comment: great, thanks ! what does the .SD mean ?
Comment: @thelatemail, are you referring to the use of `$`?
Comment: @AnandaMahto - yep, i feel like there must be a way of doing this with joins, which would be quicker I think. But I'm too dim-witted to know what that answer is :-)
Comment: @thelatemail, do you feel more comfortable with `[[` than `$` :-)
Comment: @AnandaMahto - it was more that `data.table` has first merging that would be quicker than `match` - `setkey(DT1, x); setnames(DT2, c("x1","x2")); setkey(DT2, x1);  setkey(DT2[DT1], x2)[DT1]` was the best I could manage
Answer: The idiomatic data.table approach would be to update DT2 while joining as follows:
require(data.table) # v1.9.6
setnames(DT2, c("a", "b")) # no duplicate names!!
for (nm in names(DT2)) {
    DT2[DT1, paste0(nm, ".val") := y, on = structure("x", names=nm)]
}
DT2[]
#    a b a.val b.val
# 1: 3 0    22    11
# 2: 3 5    22    33
# 3: 0 0    11    11
# 4: 0 3    11    22
# 5: 5 5    33    33

You can hide the loop with lapply() perhaps. If DT2 was instead as follows (in long form; see DT3):
DT3 = melt(DT2, measure = c("a", "b"), variable.name = "id", value.name = "x.val")

then you could do:
DT3[DT1, y.val := y, on = c(x.val = "x")]

You can use y.val := i.y to be more explicit that you're referring to the y column from the data.table corresponding to i argument.. (useful when they both have common column names).
Comment: Not with the way you've your `DT2` structured. What's wrong with a for-loop?
Comment: Edited to show how `DT2` should be so as to do it with one join.
Comment: is there a way to avoid the for loop ?
Answer: You can try something like the following:
DT2[, lapply(.SD, function(x) DT1[["y"]][match(x, DT1[["x"]])])]
#     x  x
# 1: 22 11
# 2: 22 33
# 3: 11 11
# 4: 11 22
# 5: 33 33
str(.Last.value)
# Classes 'data.table' and 'data.frame':    5 obs. of  2 variables:
#  $ x: num  22 22 11 11 33
#  $ x: num  11 33 11 22 33
#  - attr(*, ".internal.selfref")=<externalptr>

Comment: thank you all, many useful answers.... actually so many answers now i don't know which one to choose in practice...

Reindexing in R with data.table?


How can I practice clarinet quietly?

Question: How can I practice clarinet more quietly?
Is there a clarinet mute that works well? Particularly good ear plugs? I'd rather not either soundproof a room, or move to the basement / garage.
What I don't want to do is reduce air flow to make the instrument more quiet, as this has gotten me to develop bad habits.

similar questions:

electric guitar answers (unplug, use headphones) not relevant here How can I practice in an apartment without annoying the neighbours?
singing, mostly deals with creating a sound-proof room: How to practice singing quietly
Comment: Why do you ask about earplugs? Are the people who don't want to hear your clarinet playing in your household and willing to wear earplugs? Soft expanding foam earplugs are comfortable, cheap, and very effective. That all being said, this is at least bordering on a product search question.
Comment: Depending on what country you are in, you might have the right to practice your instrument every day, and the neighbours just have to put up with it. Here in Germany there are fixed hours when you can do this. Check your local regulations. Of course you tell the neighbours about this in advance, and offer to play Happy Birthday for them as appropriate.
Comment: @Todd - yes earplugs for the others. Its not a product search; I am more interested in answers  thought of yet.
Comment: Would you consider trying a [wind controller](https://en.wikipedia.org/wiki/Wind_controller)? That's completely quiet.
Answer: Mutes

I would recommend using something like this:
http://www.bill-lewington.com/saxmute.htm
It does soften the sound by about 50% for B flat clarinet.
Unfortunately, I don't believe that there is a mute made for an E flat clarinet.
Another thing you can do is play your clarinet into your closet so that the clothing drowns out the sound.

Earplugs

Cheap earplugs or noise-cancelling headphones can help others in the house avoid hearing clarinet sounds.

Disclaimer

There are definite downsides to playing an instrument at home. If the mute doesn't work for you, there are local music stores and recording studios that make sound proof rooms for this type of thing.
Clarinet mutes are not used as often as brass mutes.
Comment: The sax mute link appears to be out of date.
Comment: I would agree that trying to do all your practicing pianissimo will not only keep you from learning dynamics but most likely will lead to bad physical habits that will be hard to break.  Find a damped location or practice when nobody else is home.
Comment: Driving somewhere relatively secluded and practicing in your vehicle might also be an option.
Answer: Open your wardrobe and play into it. Put the end right in among the clothes.
My music teacher recommended this to me, and it works very well. I take my clarinet with me on long trips, and have practiced in many a hotel without anyone complaining.
Answer: I've suggested this for various instruments - get in the car (only if you have one of course!), drive to a secluded place, play there. Don't be surprised if the law stops to question you, and drives off after, smiling or laughing!
A friend converted the back of his van to contain a drum kit, and did similar - even a small van/estate would be large enough. Singing is an obvious one to do in a vehicle, but it does lend itself nicely to practice time - providing it's not too cold out there.
Comment: In good weather, I'll go out to a park and play, and for the other 51 weeks of the year, the pastor at a nearby church who lets me use their building during off-hours. And as an aside, I got permission from another church where my only connection was through a friend, so if you ask you may be surprised what you can find.

How can I practice clarinet quietly?


android eclipse dynamically set list adapters child TextView width

Question: I have a list that is populated by a listadapter that specifies a layout like so:
SimpleCursorAdapter trips =
new SimpleCursorAdapter(this, R.layout.it_menu_home_row, tripsCursor, from, to);

Inside of that layout is a textview.  I would like to be able to dynamically change the width of that textview through code.  I have tried just referencing the textview ID with findViewById, but when I try to manipulate it, I get a null pointer exception.
Is there a simple way reference the textview of a listadapters layout?
I am trying to reference the text view like I would if it was sitting in the base layout of the activity:
TextView tv = (TextView)findViewById(R.id.myTV);

I don't know if I have to somehow iterate through each of the list items and manually set the textView that way (and if I do I am not sure how), or if I just have to reference it once, etc
Comment: I think you need to put some more code. How are your referencing the TextView in each item in the list view?
Answer: When you use SimpleCursorAdapter you provide the textFields via the constructor itself. In the snippet you have given, to should be an array of id's of the TextView's present.
For example if your layout file has a TextView with the id: "@+id/my_textfield" then you should pass in your constructor an array: int to[]=new int[]{R.id.my_textfield};
Comment: Wow I can't believe I didn't think of that.  I am already referencing that TV to change the text itself...  Dumb thought process on my part, but great point on yours! Thanks!


Creating a custom field module

Question: I am trying to create a custom field module for views, but I keep getting this error when I add the field to the view.

SQLSTATE[42S22]: Column not found: 1054
  Unknown column 'views_report_state_field' in 'field list'

This is the code I am using.
views_report_state.info
name = Views Report State
description = Turns short abbreviated states (ex: TX) into fully readable names (ex: Tx = Texas)
package = Views
core = 7.x

files[] = views/views_report_state_field.inc

views_report_state.module
function views_report_state_views_api($module = NULL, $api = NULL) {
  return array("api" => 3);
}

views_report_state.views.inc
function views_report_state_views_handlers() {
  $handlers = array(
    'info' => array(
      'path' => drupal_get_path('module', 'views_report_state'),
    ),
    'handlers' => array(
      'views_report_state_field' => array(
        'parent' => 'views_handler_field',
      ),
    ),
  );
  return $handlers;

function views_report_state_views_data() {
  $data = array();
  $data['views']['views_report_state_field'] = array(
    'title' => t('CRF: Convert US-State Abbreviations'),
    'help' => t('Converts State Abbreviations to their full name'),
    'field' => array(
      'handler' => 'views_report_state_field',
    ),
  );
  return $data;
}

views_report_state_field.inc
class views_report_state_field extends views_handler_field {

  function render() {
    return "working!";
  }

}

Comment: Try adding an empty `query` method to your handler class
Answer: views_report_state_field.inc
class views_report_state_field extends views_handler_field {
  function query() {
    // Query
  }

  function render() {
    return "working!";
  }

}

Creating a custom field module


puppeteer: document.querySelector works on console but not on pupppeteer

Question: when I use the document.querySelector in Chrome console, I obtain something, however when I use the same query with puppeeter. I get "undefined" or "Promise {  }".
    const text = await page.evaluate(() => document.querySelector('div.tagCloud-slotAble.space--mv-2 > button:nth-child(1)'));
console.log(text)

Thanks
Answer: That is because querySelector returns a node. Try to return innerText,
const text = await page.evaluate(() => document.querySelector('div.tagCloud-slotAble.space--mv-2 > button:nth-child(1)').innerText);
console.log(text)

Comment: Hey, indeed i obtain something with .innertext. How come I can display the node on the chrome console but nothing when I use the queryselector with puppeeter ? Thx
Comment: Because puppeteer runs on node context, but chrome console is on browser context. They are seperate thing.
Comment: How comes "document.querySelector('div.tagCloud-slotAble.space--mv-2 > button:nth-child(1)').innerText" works if puppeteer runs on node context ?
Comment: because you are `evaluating/running` this part in the `page`
Answer: As far as I can tell, the reason you're not able to get your text back and output to your console is happening for two reasons:

You're not returning the value from your evaluate method.
You're retrieving the element but not the text content from the element.

If you do something like the following, this should resolve your problem:
const text = await page.evaluate(() => {
  const uiElement = document.querySelector('div.tagCloud-slotAble.space--mv-2 > button:nth-child(1)'));
  return uiElement.textContent;
});
console.log(text);

An alternative to the above function is to use puppeteers $eval method as follows:
const elementSelector = 'div.tagCloud-slotAble.space--mv-2 > button:nth-child(1)';
const text = await page.$eval(elementSelector, (uiElement) => {
  return uiElement.textContent;
});
console.log(text);

I personally prefer the second option (using $eval) but it's a matter of preference. Both do the same thing.
It should be noted that anything you run in an evaluate or $eval method is executed in your page context ie. it is executed in the web page which is currently open in the remote browser. You can basically use this method to inject new UI elements into your web page during a test, execute JavaScript code inside your web page etc.
Or you can use it, as you are now, to find a UI element and return the text content from it.


Easy way of Compute this limit

Question: Easy way to compute: $$\lim_{x\to \:0\:}\left(\left(\frac{a^x-x\cdot \ln\left(a\right)}{b^x-x\cdot \ln\left(b\right)}\right)^{\frac{1}{x^2}}\right)$$
Comment: are you sure that  the power is $\frac{1}{x^3}$, i guess it should be $\frac{1}{x^2}$
Comment: @EkaveeraKumarSharma Your right it is $1/x^2$, but I still don't know how to solve it, because I get a huge quotient rule and I am sure there is a simpler way
Comment: @EkaveeraKumarSharma Here is a picture: http://i.imgur.com/1ah84ls.png
Comment: @JamesSmith: Of course there is.. never every try L'Hopital's rule unless you do not even know the concrete expression for which you want a limit! Otherwise always use asymptotic expansions such as Taylor series. That is how computer algebra systems do it too.
Answer: Apply $\ln$ to get
$$\tag 1 \frac{\ln (a^x-x\ln a) - \ln (b^x-x\ln b)}{x^2}.$$
Using $e^u = 1 + u + u^2/2 +O(u^3)$ as $u\to 0,$ we get
$$a^x = e^{x\ln a} = 1 + x\ln a + (x\ln a)^2/2 + O(x^3).$$
A similar result holds for $b^x.$ Therefore $(1)$ equals
$$\tag 2 \frac{\ln (1+(x\ln a)^2/2 + O(x^3)) - \ln (1+(x\ln b)^2/2 + O(x^3))}{x^2}.$$
Now $\ln (1+u) = u + O(u^2).$ Therefore $(2)$ equals
$$\frac{(x\ln a)^2/2 -(x\ln b)^2/2 + O(x^3)}{x^2} \to (\ln a)^2/2 -(\ln b)^2/2 .$$
Exponentiating back gives $e^{(\ln a)^2/2 -(\ln b)^2/2}.$
Answer: Basically as $x \to 0$  the function $$\left(\frac{a^x -x \, \ln a}{b^x -x \, \ln b}\right)^{1/x^2}$$ attains the form 1^infinity. As $\lim x \to a  [f(x)]^{g(x)}$ attains $1^{\infty}$ form we can modify limit as $e^{\lim x \to a (f(x)-1) g(x)}$
using the above rule, and after taking LCM your limit transforms to $e^{\lim x \to 0 (1/x^2){(a^x -x\ln a -b^x +x\ln b)/(b^x -x\ln b)}}$
  using expansion of $$a^x = 1 + (x\ln a)/1! + ((x\ln a)^2)/2! +.......$$
                     $$b^x = 1 +(x\ln b)/1!  + ((x\ln b)^2)/2! +....$$
your limit transforms to $$e^{\lim x-->0 (1/x^2){[((x\ln a)^2)/2!..... -((x\ln b)^2)/2!....]/(b^x -x\ln b)}}$$
cancel $x^2$ and then put $x \to 0$ you need not worry about other terms in Nr as they have positive powers of x and become 0
so finally u are left with $e^{{((\ln a)^2)-((\ln b)^2)}/2}$ which is the reqd limit
Answer: For any $a,b > 0$ and as $x \to 0$:
$\def\l{\!\left}$
$\def\r{\right}$
  $a^x = \exp(x\ln(a)) \in 1 + x\ln(a) + \frac{1}{2}(x\ln(a))^2 + o(x^2)$.
  $b^x = \exp(x\ln(b)) \in 1 + x\ln(b) + \frac{1}{2}(x\ln(b))^2 + o(x^2)$.
  $\l( \dfrac{a^x - x\ln(a)}{b^x - x\ln(b)} \r)^\dfrac{1}{x^2} = \exp\l( \dfrac{1}{x^2}\ln\l( \dfrac{a^x - x\ln(a)}{b^x - x\ln(b)} \r) \r)$
  $ \in \exp\l( \dfrac{1}{x^2}\ln\l( \dfrac{ 1 + \frac{1}{2}\ln(a)^2 x^2 + o(x^2) }{ 1 + \frac{1}{2}\ln(b)^2 x^2 + o(x^2) } \r) \r)$
  $ \subseteq \exp\l( \dfrac{1}{x^2}\ln\l( 1 + \frac{1}{2}(\ln(a)^2-\ln(b)^2) x^2 + o(x^2) \r) \r)$
  $ \subseteq \exp\l( \dfrac{1}{x^2} \l( \frac{1}{2}(\ln(a)^2-\ln(b)^2) x^2 + o(x^2) \r) \r)$
  $ \subseteq \exp\l( \frac{1}{2}(\ln(a)^2-\ln(b)^2) + o(1) \r) = \exp\l( \frac{1}{2}(\ln(a)^2-\ln(b)^2) \r) ( 1 + o(1) )$
  $ \to \exp\l( \frac{1}{2}(\ln(a)^2-\ln(b)^2) \r)$.
Comment: Note that this solution is purely mechanical. One may ask how to know how much of each asymptotic expansion to use. The answer is that it does not matter. If you cut off at some order and later find that the significant term cancels, then just go back and increase the order of expansion. This is what happens if we expand $a^x$ and $b^x$ to only first-order, so one the second try we expand to second order and it works. If you want more precise asymptotic behaviour, just expand to higher order.
Answer: Let the desired limit be $L$. Then we have
\begin{align}
\log L &= \log\left(\lim_{x \to 0}\left(\frac{a^{x} - x\log a}{b^{x} - x\log b}\right)^{1/x^{2}}\right)\notag\\
&= \lim_{x \to 0}\log\left(\frac{a^{x} - x\log a}{b^{x} - x\log b}\right)^{1/x^{2}}\text{ (via continuity of log)}\notag\\
&= \lim_{x \to 0}\frac{1}{x^{2}}\log\left(\frac{a^{x} - x\log a}{b^{x} - x\log b}\right)\notag\\
&= \lim_{x \to 0}\frac{1}{x^{2}}\log\left(1 + \frac{a^{x} - x\log a}{b^{x} - x\log b} - 1\right)\notag\\
&= \lim_{x \to 0}\frac{1}{x^{2}}\log\left(1 + \frac{a^{x} - b^{x} - x(\log a - \log b)}{b^{x} - x\log b}\right)\notag\\
&= \lim_{x \to 0}\frac{1}{x^{2}}\cdot\dfrac{a^{x} - b^{x} - x(\log a - \log b)}{b^{x} - x\log b}\cdot\dfrac{\log\left(1 + \dfrac{a^{x} - b^{x} - x(\log a - \log b)}{b^{x} - x\log b}\right)}{\dfrac{a^{x} - b^{x} - x(\log a - \log b)}{b^{x} - x\log b}}\notag\\
&= \lim_{x \to 0}\frac{1}{x^{2}}\cdot\dfrac{a^{x} - b^{x} - x(\log a - \log b)}{b^{x} - x\log b}\cdot 1\notag\\
&= \lim_{x \to 0}\frac{a^{x} - b^{x} - x(\log a - \log b)}{x^{2}}\notag\\
&= \lim_{x \to 0}\frac{a^{x} - 1 - x\log a}{x^{2}} - \frac{b^{x} - 1 - x\log b}{x^{2}}\notag\\
&= \lim_{x \to 0}(\log a)^{2}\cdot\frac{a^{x} - 1 - x\log a}{(x\log a)^{2}} - (\log b)^{2}\cdot\frac{b^{x} - 1 - x\log b}{(x\log b)^{2}}\notag\\
&= (\log a)^{2}\lim_{u \to 0}\frac{e^{u} - 1 - u}{u^{2}} - (\log b)^{2}\lim_{v \to 0}\frac{e^{v} - 1 - v}{v^{2}}\text{ (putting }u = x\log a, v = x\log b)\notag\\
&= \{(\log a)^{2} - (\log b)^{2}\}\lim_{u \to 0}\frac{e^{u} - 1 - u}{u^{2}}\notag
\end{align}
The last limit is easily seen to be $1/2$ either via one application of L'Hospital's Rule or through Taylor's series. Hence $$\log L = \frac{(\log a)^{2} - (\log b)^{2}}{2}$$ and therefore $$L = \exp\left(\frac{(\log a)^{2} - (\log b)^{2}}{2}\right)$$
Comment: Why the downvote??

Easy way of Compute this limit


python how to see data in file object .obj

Question: I would like see data in file .obj, but I keep getting error.
This is my code
infile = open('tfidf_vect_obj.obj','rb'))
print(infile)

Please, help me fix this issue
Comment: Please provide more informaiton
Comment: "*I keep getting error*": What is the error? Please [edit] to post the *full* error message. It's probably related to the extra `)` at the end of `...obj','rb'))`
Answer: With open() you will get the file as an object. Then you can retrieve the data by using methods defined for that file object, like read() for example.
infile = open('tfidf_vect_obj.obj','rb')
data = infile.read()
print(data)
infile.close()

By using a context manager (with statement), you don't have to care about closing the file at the end:
with open('tfidf_vect_obj.obj','rb') as infile:
    data = infile.read()
    print(data)

You can see more about this topic in the official Python tutorials.
Answer: why don't you use ?
with open("tfidf_vect_obj.obj", "rb") as file:
    file = ........

Comment: It would be helpful to the OP if you explain *why* your code works.


Como obter dados deste Json?

Question: Preciso obter o name, a distance, photo e o id, que estão dentro de "data" e também preciso obter o route_id que está dentro de "ride".
Isso será preenchido num listview que contém estes primeiros dados. Ao clicar no btn_go, estes dados serão enviados a activity e também neste momento, o route_id deve ser enviado.
Json:
{
  "data": [
    {
      "id": 4,
      "start_address": "Aveninda Treze, Fortaleza - CE",
      "end_address": "Rua Delta, Fortaleza, Ceará 60713, Brazil",
      "start_lat": -3.7464,
      "start_lng": -38.5326,
      "end_lat": -3.79521,
      "end_lng": -38.5772,
      "user_id": 2,
      "distance": "6.521",
      "user": {
        "id": 2,
        "name": "User Test",
        "departure_time": "07:00:00",
        "arrival_time": "18:00:00",
        "address_lat": -3.7952,
        "address_lng": -38.577,
        "car": true,
        "photo_url": "https://test.com/img/avatar_female.png",
        "profile_mode": 2
      },
      "ride": {
        "id": 22,
        "schedule": "2017-03-22 18:00:00",
        "user_id": 2,
        "route_id": 4,
        "chat_id": 57,
        "channel": "chat.57",
        "disabled_reason": 0
      }
    }

Adapter:
 public class SearchAskPresenter extends BaseAdapter implements AdapterView.OnItemClickListener, SubscriptionEventListener {

        private final SearchAskView searchaskview;
        CommunityRequestView viewR;
        private List<UserCommunity> usersList = new ArrayList<UserCommunity>();
        private List<SearchAskConstructor> usersSearchList = new ArrayList<SearchAskConstructor>();
        LayoutInflater inflater;
        TextView txt_Nome;
        TextView txt_Email;
        TextView txt_Distance;
        ImageButton btnGo;
        private UsersMySQLiteHelper serviceDB;
        private SessionManager sessionManager = new SessionManager();
        JsonObject json = new JsonObject();
        private ProgressDialog progress;
        SearchAskService service;

        public SearchAskPresenter(final SearchAskView view) {
            this.searchaskview = view;

            serviceDB = new UsersMySQLiteHelper(AppController.getAppContext());
            service = new SearchAskService(AppController.getAppContext());
            json = SharedPreferenceHelper.getScheduling(AppController.getAppContext());
    /*
            this.searchaskview.getListView().setAdapter(this);
            this.searchaskview.getListView().setOnItemClickListener(this);
    */
//obtendo o retorno com o Json
RequestManager.UsersSearchAskTest(json, new FutureCallback<String>() {
                @Override
                public void onCompleted(Exception e, String result) {
                    if (e==null || result!=null){
                        usersSearchList = new Gson().fromJson(new JsonParser().parse(result).getAsJsonObject().get("data").toString(), new TypeToken<ArrayList<SearchAskConstructor>>() {
                        }.getType()); //obtendo o Json

                        if (usersSearchList.size() > 0){
                            notifyDataSetChanged();
                        }
                    }else{
                        Toast.makeText(AppController.getAppContext(),"Não há sugestões",Toast.LENGTH_LONG).show();
                    }
                }
            });
           // usersSearchList = serviceDB.getAllUsers(sessionManager.getLoggedUser().getCompany());
        }

        @Override
        public int getCount() {
            return usersSearchList.size();
        }

        @Override
        public Object getItem(int position) {
            return usersSearchList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            inflater = (LayoutInflater) searchaskview.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            //recupera o estado da posição atual
            final SearchAskConstructor searchUsers = usersSearchList.get(position); //TODO verificar onde pegar as informações de email--etc
            //Cria uma instancia do layout .. na view
            View view = inflater.inflate(R.layout.searchask_item_list, null);
            //loadingStart(true,"Carregando...");
            txt_Email = (TextView) view.findViewById(R.id.txt_email_searchask);
            txt_Nome = (TextView) view.findViewById(R.id.txt_nome_searchask);
            txt_Distance = (TextView) view.findViewById(R.id.txt_distance_searchask);
            btnGo = (ImageButton) view.findViewById(R.id.img_btn_searchask);

            txt_Email.setText(searchUsers.email);
            txt_Distance.setText(String.valueOf(searchUsers.distanceSearch));
            txt_Nome.setText(searchUsers.name);

            btnGo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                 /*   new Routes(searchaskview.getContext())
                            .open(URIs.Chat());*/

                    Intent intent = new Intent(AppController.getAppContext(), SearchAskFinishActivity.class);
                    searchaskview.getActivity().startActivity(intent);

                }
            });

            return view;
        }

Criei esta classe:
public class SearchAskConstructor {
    public int id;
    public String name;
    public String email;
    public String photo_url;
    public int route_id;
    public int user_id;

    public int profile_mode;
    public double distanceSearch;

    public SearchAskConstructor(String name, String photo_url, int profile_mode, int route_id, int user_id, double distance) {
        this.name = name;
        this.photo_url = photo_url;
        this.profile_mode = profile_mode;
        this.route_id = route_id;
        this.user_id = user_id;
        this.distanceSearch = distance;
    }

    public SearchAskConstructor() {
        super();
    }

}

Answer: Simples! Primeiro é necessário importar as seguintes libs, no qual é necessário trabalhar com as classes JSONArray, JSONObject e JSONException, para tratamento de exceções. Veja abaixo:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

Depois você pode criar um novo objeto com uma simples string, neste caso seu JSON. Vide comentários:
try {
    JSONObject myObject = new JSONObject(json);
    JSONArray myArrayData = myObject.getJSONArray("data");

    String distance = null, name = null;
    int id = 0, route_id = 0;

    for (int i = 0; i < myArrayData.length(); i++) {
        JSONObject another_json_object = myArrayData.getJSONObject(i);

        // resgata o id
        id = another_json_object.getInt("id");

        // resgata a distance
        distance = another_json_object.getString("distance");

        // resgata o nome dentro de user
        JSONObject obj = new JSONObject(another_json_object.getString("user"));
        name = obj.getString("name");

        // resgata route_id dentro de ride
        JSONObject obj2 = new JSONObject(another_json_object.getString("ride"));
        route_id = obj2.getInt("route_id");

    }
    // mostra na tela os valores resgatados
    Toast.makeText(this,
         "name: " + name
       + "\nid:" + id
       + "\ndistance:" + distance
       + "\nroute_id: " + route_id,
            Toast.LENGTH_SHORT).show();

} catch (JSONException e) {
    e.printStackTrace();
}

Comment: Nesse caso, eu vou gerar uma carga grande no cliente(celuar) podem ser vários dados, o gson, tavez me permita fazer algo mais rapido, não? Ja que ele traz tudo isso, que vc fez sem a necessidade de um FOR.
Comment: Se me está confirmando isso, como não conseguiu fazer?! Qual seria a dúvida então? Você teria que detalhar melhor sua pergunta se caso queria usar alguma lib específica.

Como obter dados deste Json?


Where do Cabal & Stack fetch Hackage packages from?

Question: I am interested in creating a tool for Hackage involving analysis of the various dependencies between Hackage's packages. I am thinking this would involve downloading and syncing a mirror of all Hackage package sources, in particular the *.cabal files, on which I can run the various analyses I have in mind.
How can I access the same repositories that cabal and stack fetch packages from? Is there an API that cabal and stack use to fetch packages that my program could similarly plug into?
Answer: I'm currently working on a library that will give easy (or at least easier) access to this metadata. But the basic rule for getting the metadata on all packages from Hackage is:

Download the 01-index.tar.gz file: https://hackage.haskell.org/01-index.tar.gz
Parse each <code>.cabal</code> file inside of it

Note that, due to Hackage revisions, there may be multiple cabal files with the same name/version combination (known as the package identifier).


sap.ui.table.Table inside of Scroll Container: visibleRowCountMode="Auto" not working

Question: This is a follow-up question to this question. Basically, I have the same problem as described there where the table does not have as many rows as possible, there is more space there but it is unused.
I got it working for my table with the help of the answers in the last question. Now I had to adda horizontal Scroll-Container (the height is fixed) arround this table. Then the problem came up again.

I built a demo version with which you can see the problem and try arround with here.
The wanted result is just like as if you removed the ScrollContainer, then the table fills the entire page.
The same problem occurs when using this table inside of an IconTabBar but I was able to find an ugly work-around which does not work here. After the table was rendered I added the style height: 100% manually to the html-parents of the table (these are generated divs of the IconTabBar). This enabled the Table to receive the full height from its parents. With the ScrollContainer this tactic does not seem to work.
Comment: What is the actual target design? According to the provided plunk (thx btw!), it looks like the text on the right-hand side is supposed to represent some helpful guide for the table. In that case, have you [considered using a **`DynamicSideContent`** instead](https://experience.sap.com/fiori-design-web/dynamic-side-content/)? IMHO going for a `ScrollContainer` is an unfortunate result of [xy-problem](https://xyproblem.info/) as the table already comes with a horizontal scrollbar and displays it if the width doesn't suffice. I'd suggest to look for another control to be more Fiori-aligned.
Comment: The text on the side was just there to test the problem. I have several tables with this problem. In one table it is a legend (a HBox with several color and text entries). In another table the problem is that the buttons in the toolbar are also moved to the right when the table columns are resized. Unfortunately, I am unable to reproduce this problem in the plunk and I am not quite sure why. The idea was to put the table in the ScrollContainer so that only the table moves but the buttons above and below stay fixed. I will try to add a demo again. I'll also add a picture to the answer
Answer: Please have a look at the restrictions of visibleRowCountMode="Auto"
https://ui5.sap.com/#/api/sap.ui.table.Table%23methods/getVisibleRowCountMode
See here the the layoutData definition for the HBox so that it gains the height from its parent
<layoutData>
    <FlexItemData growFactor="1" />
</layoutData>

and also height: 100% style for the ScrollContainer's inner element which also let the table know the height of its container.
Answer: You can fix it like this:
onInit: function () {
    this.oTable = this.byId("TableID");
    this.oTable.onAfterRendering = function () {
      const table = this.getTable();
      const aColumns = table.getColumns();
      for (let i = 0; i < aColumns.length; i++) {
        aColumns[i].setProperty("width", "auto");
      }
      this.setHeight("100%");
    };
}

And you may try these properties:
flexible: true/false,
resizable: true/false,
autoResizable: true/false,
width : "auto"

Comment: Please don't rely on rendering APIs such as `onAfterRendering` in application development (Also do **not** overwrite it!!). There are almost always better options. But for that, we need more information from the question author.

sap.ui.table.Table inside of Scroll Container: visibleRowCountMode=“Auto” not working


Does the left adjoint of the homotopy coherent nerve have a name?

Question: The simplicial nerve $N: \operatorname{Sset-Cat} \to \operatorname{Sset}$ has the left adjoint $\mathfrak{C}: \operatorname{Sset} \to \operatorname{Sset-Cat}.$ Wherever I see it, it is always referred by its symbol (and even that is not consistent: here it is called "$S$"). That's awkward and weird. Is there a (n at least proposed) name for it?
Answer: There is no standard name for this functor.
One could call it the rigidification functor, since rigidification (or strictification) is a recognized name for this type of constructions.
However, such a name can refer to any of the several weakly equivalent models for this functor, see, for example, Rigidification of quasi-categories by Dugger and Spivak.
Answer: Emily Riehl calls it (e.g. in Homotopy coherent structures), homotopy coherent realization, due to "formal similarity" with the realization functor $\operatorname{Top} \to  \operatorname{Sset}.$
Images of standard simplices are called homotopy coherent simplices. There is a related functor $\mathfrak{C}: \operatorname{Cat} \to \operatorname{Sset-Cat}$ which makes a "homotopy coherent" indexing category out of an ordinary one (enabling one to define a homotopy coherent diagram in the evident way), which is called the free resolution functor. A homotopy coherent simplex can be seen as a free resolution of the category $\mathfrak{n}$, or as the homotopy coherent realization of of the standard simplex $\Delta^n$.
The formal similarity mentioned above seems to be that homotopy coherent diagram of a simplicial set is glued from homotopy coherent simplices in the same way the realization of a simplicial set is glued from standard simplices - as a colimit over the category of elements of this simplicial set.


Can SQL Server Express (or any version) run on RPi?

Question: I note that the full version of Windows 10 can be run on a RPI 3.
I wondered whether SQL Server Express (or any other edition) is available for the ARM version of Windows. I can't see it anywhere so I suspect the answer is 'no' but want to check I have my missed a trick anywhere.
Effectively I am testing out working with a large SQL Server database. I don't want my test code to touch the actual site, so my plan was to run a minimal example with some test records locally on my desk. I have an old Atom-based machine I can use - but the RPi is a much more convenient in terms of having a 'portable' demo server.
I am aware any such setup will perform awfully - performance not an issue for the demo.
Comment: The actual question is "is there a SQL Server version for *ARM*"? And I'd guess no. There is an embedded version that does target ARM, SQL Server Compact, that may or may not run on Windows IoT. It was made primarily for Windows Embedded and Windows Phone
Comment: No ARM version - according to the [Operating Systems requirements](https://learn.microsoft.com/en-us/sql/sql-server/install/hardware-and-software-requirements-for-installing-sql-server?view=sql-server-2017#TOP_Principal) SQL Server is only supported on Windows 10 IoT *Enterprise*, essentially a Windows 10 Enterprise version with different licensing
Answer: There are two questions here :

Is there a SQL Server version that runs on ARM?

According to the Operating System requirements no. SQL Server is only available for Windows IoT Enterprise, essentially a Windows 10 Enterprise version with special licensing. It's the evolution of Windows Embedded and only meant for OEMs that produce 1000s of devices.
And the real question

I don't want my test code to touch the actual site, so my plan was to run a minimal example

In that case you can use Windows 10 containers, a VM or a managed cloud version of SQL Server. SQL Server docker images are available for the Express and Developer edition.
Answer: No, in contrast with .net, powershell and other initiatives, up to this point there is no ARM version of SQL Server. And by knowing how existing version was ported, we hardly can expect that it will appear soon on this platform.
Comment: SQL Server Compact targets ARM. I'm not sure how well it will run on Windows IoT though
Comment: Good point, however it is deprecated, very much different from regular versions and hardly will ever run on linux..


Created 3D object , but it doesn't rotate in cocos3d

Question: I created one 3D object using Blender 2.66 and PowerVR Graphics SDK. I added the pod file and   altered the hello-world project simply by replacing pod file name and node name.But the 3D object is not rotating. Is there any other changes tat i have to do in code? Is there any chance of error in pod file creation ? Thanks .
Comment: Please show us your specific code
Answer: when you create a project in cocos3d the default pod file syntax is
[self addContentFromPODFile:@"hello-world.pod"];
you replace it with
where u use any node name

withName:@"HelloText"

[self addContentFromPODFile:@"hello-world.pod" withName:@"abc"];
And where you fild cc3meshnode replace getnodenamed with you set above
CC3MeshNode* hellotext = (CC3MeshNode*)[self getNodeNamed:@"abc"];


How to create a taxonomy terms dropdrown with Views

Question: I need to achieve a block containing a dropdown list of vocabulary terms (called topics). Each topic describe one or many of the content articles. Each topic which is assigned to no articles should not be displayed. When selecting the topic from a dropdown list a page with assigned articles should be displayed.
It seems like achieving a dropdown list of terms from within a view is harder than expected.
Here my steps:
I created a View with display page and exposed form in block: Yes
I selected the term ID and term Name fields; then I expose the filters as "Operator: Is one of," and I selected all. It seems like nothings happens.
Comment: what exactly is your expectation?
Comment: You question is incomplete, what is your requirement?
Answer: There are several approaches:
A. Create a View out of Taxonomy Terms with a Page Display.
For fields add: term id, term name
For filters: Term name (with widgets) and expose the filter
Choose then:

Dropdown,
Vocabulary (of your choice)
Expose this filter to visitors...,
'Is one of' then select all terms from the vocabulary
Remove duplicates

In Views UI, on Advanced Tab

Exposed form in block: Yes
Exposed form style: Basic | Settings
Adjust settings to have autosubmit

B. Create a View out of Content and choose Taxonomy Terms among fields, similar to above.
C. Create a View with Block display from Taxonomy Terms and at Format Tab choose Jump Menu. If you need to overwrite the Jump Menu path you need to add a custom text field and create your desire path out of Replacement Patterns.
Than select the created custom text field from Jump Menu path settings


ABNewPersonViewController using contact framework

Question: - (void)addContact {
    // Creating new entry
    ABAddressBookRef addressBook = ABAddressBookCreate();
    ABRecordRef person = ABPersonCreate();

    NSString *phone = self.data.phone;
    NSString *cellphone = self.data.cellPhone;
    NSString *fax = self.data.fax;
    NSString *email = self.data.email;
    NSString *firstName = self.data.firstName;
    NSString *lastName = self.data.lastName;

    ABRecordSetValue(person, kABPersonFirstNameProperty, (__bridge CFTypeRef)(firstName) , nil);
    ABRecordSetValue(person, kABPersonLastNameProperty, (__bridge CFTypeRef)(lastName), nil);
    ABRecordSetValue(person, kABPersonJobTitleProperty, (__bridge CFTypeRef)(title), nil);
    ABRecordSetValue(person, kABPersonDepartmentProperty, (__bridge CFTypeRef)(dept), nil);
    ABRecordSetValue(person, kABPersonOrganizationProperty, (__bridge CFTypeRef)(org), nil);
    ABRecordSetValue(person, kABPersonNoteProperty, (__bridge CFTypeRef)(unit), nil);

    // Adding phone numbers
    ABMutableMultiValueRef phoneNumberMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    ABMultiValueAddValueAndLabel(phoneNumberMultiValue, (__bridge CFTypeRef)(cellphone), (CFStringRef)@"iPhone", NULL);
    ABMultiValueAddValueAndLabel(phoneNumberMultiValue, (__bridge CFTypeRef)(phone), (CFStringRef)@"Work", NULL);
    ABMultiValueAddValueAndLabel(phoneNumberMultiValue, (__bridge CFTypeRef)(fax), (CFStringRef)@"Fax", NULL);
    ABRecordSetValue(person, kABPersonPhoneProperty, phoneNumberMultiValue, nil);
    CFRelease(phoneNumberMultiValue);

    // Adding emails
    ABMutableMultiValueRef emailMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    ABMultiValueAddValueAndLabel(emailMultiValue, (__bridge CFTypeRef)(email), (CFStringRef)@"Work", NULL);
    ABRecordSetValue(person, kABPersonEmailProperty, emailMultiValue, nil);
    CFRelease(emailMultiValue);

    // Adding person to the address book
    ABAddressBookAddRecord(addressBook, person, nil);
    CFRelease(addressBook);

    ABNewPersonViewController *c = [[ABNewPersonViewController alloc] init];
    [c setNewPersonViewDelegate:self];
    [c setDisplayedPerson:person];
    CFRelease(person);
    [self.navigationController pushViewController:c animated:YES];
}

what is the similar code using contacts framework? How to load detail from person (ABRecordRef person = ABPersonCreate();) into *contact (CNMutableContact *contact = [CNMutableContact new];)?
Answer: I'd suggest using ContactsUI framework rather than the old AddressBookUI framework. So, don't use ABNewPersonViewController, but instead use CNContactViewController:
@import ContactsUI;

@interface ViewController () <CNContactViewControllerDelegate>
@end

@implementation ViewController

- (IBAction)didTapButton:(id)sender {
    CNMutableContact *contact = [[CNMutableContact alloc] init];
    [contact setGivenName:@"John"];
    [contact setFamilyName:@"Doe"];
    ...

    CNContactViewController *controller = [CNContactViewController viewControllerForNewContact:contact];
    controller.delegate = self;

    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
    nav.view.backgroundColor = [UIColor blueColor];
    [self presentViewController:nav animated:true completion: nil];
}

- (void)contactViewController:(CNContactViewController *)viewController didCompleteWithContact:(CNContact *)contact {
    [viewController.navigationController dismissViewControllerAnimated:true completion:nil];
}

@end

Nowadays, use Contacts and ContactsUI frameworks rather than the deprecated AddressBook and AddresssBookUI frameworks.
Comment: Is [self presentViewController:nav animated:true completion: nil]; will have Done and Cancel option ?   Is there any way I can copy all data from person object into contact  object of how can I load data into contact object for above code?
Comment: controller.delegate = self;   returns error Assigning to 'id _Nullable' from incompatible type 'QuickContactsViewController *const __strong'
Comment: Now it display the data but It doesn't display cancel and Done button .
Comment: i have added to @interface QuickContactsViewController : UIViewController   but same error
Comment: I would like to keep  both so i can support IOS 7 and IOS 10.  Looks like cancel and done button display but its transparent. If i click on top right and top left the page close successfully.
Comment: I am planning to put the check for iOS > 9 used used new method else used method which seems working but on iOS 11 the save contact doesn't have cancel and done Butt it. Button seems there but looks like it's transferent because if I click on  top left corner it seems working but buttons are not visible.  right
Comment: #import

@interface ViewController
I'm getting error Class 'ViewController' defined without specifying a base class
Comment: `@interface ViewController: UIViewController `. In my example above, I assumed you had already declared the `@interface` for the `ViewController`, so I just declared a private class "extension", but both techniques work.
Comment: Pop up header navigation bar , cancel and Done button are white and cannot see the buttons.


Where can I find the link within admin for running the cleaner module, and how to install it?

Question: I want to run 'Cleaner' (provided by the Cleaner module).
But when I go to administer > site > configuration, nothing related to  Cleaner is listed.
I have searched Drupal.org, where I learned that this is this link is what I need. Maybe this information is out of date?
Any suggestions?
Edit: I am new to Drupal. Can you tell me, how I install the Cleaner module?
Comment: What information are you referring to?
Answer: The Cleaner module must be installed before you can use it.
Comment: Many thanks for quick response. I am new to drupal as a user and I am not happy with the company that built the site. Can you tell me, please, how I install cleaner.
Comment: Like anything, there is a learning curve. Drupal is a powerful and extensible system. As such configuring it for your particular needs can be a daunting process. You should review the getting started and after installation sections to start to understand how it works. In particular, [Installing contributed modules (Drupal 5 and 6)](https://drupal.org/documentation/install/modules-themes/modules-5-6). Good luck.


Easiest way to map objects attributes into Java Maps

Question: There are easy to use tool to serialize java class into JSON strings (gson), does any mainstream library, or java language feature, provide a similar functionality to map objects into java Maps?
The natural way to do that for class C1:
class C1
{
  private int x;
  private int y;

  public int getX() { return x; }
  public void setX(int x) { this.x = x; }

  public int getY() { return y; }
  public void setY(int y) { this.y = y; }
}

And object o1:
C1 o1 = ...

... could be:
Map<String, Integer> result = new HashMap<>();
result.put("x",o1.getX());
result.put("y",o1.getY());

The way gson works is quite straightforward (from gson website):
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);

I understand I can develop that tool by myself using something like:
Class.getDeclaredFields()

but I wonder if this functionality has already been included in any mainstream library.
Comment: http://www.javacoffeebreak.com/articles/serialization/
Comment: `json4j` is used in Apache Wink. I used it and is ok.
Comment: @MacConan I don't want to serialize my object in a string or a file. I just need to generate a map where each entry key is an attribute name of the object and contains the object value for this attribute.
Comment: @Areo I don't need a tool to work with json, I just used gson as an example of the kind of interface that the tool I am looking for should have.
Comment: Ok. Iunderstand: Check this:
Answer: Finally, I decided to implement my own mapper:
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class Serializer {
    static public Map<String, Object> object2Map(Object o)
    {
        Class co = o.getClass();
        Field [] cfields = co.getDeclaredFields();
        Map<String, Object> ret = new HashMap<>();
        for(Field f: cfields)
        {
            String attributeName = f.getName();
            String getterMethodName = "get"
                               + attributeName.substring(0, 1).toUpperCase()
                               + attributeName.substring(1, attributeName.length());
            Method m = null;
            try {
                m = co.getMethod(getterMethodName);
                Object valObject = m.invoke(o);
                ret.put(attributeName, valObject);
            } catch (Exception e) {
                continue;
            }
        }
        return ret;
    }
}

A silly use example:
public class JavaUtilsTests {

    static public class C1
    {

        public C1(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public int getX() { return x; }
        public void setX(int x) { this.x = x; }

        public int getY() { return y; }
        public void setY(int y) { this.y = y; }

        private int x;
        private int y;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        C1 o1 = new C1(1,2);
        Map<String, Object> attributesMap = Serializer.object2Map(o1);
        System.out.printf("x=%s\ty=%s\n", attributesMap.get("x"), attributesMap.get("y"));
    }
}

My "mapper" method requires input objects to present getters and setters named by the following pattern:
(get|set)attributeTitledName
Answer: Here is a solution with Jackson. Jackson is mainly used to convert objects to/from json.
Maven
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.7</version>
</dependency>

Java Example
class C1 {
    private int x;
    private int y;

    public int getX() { return x; }
    public void setX(int x) { this.x = x; }

    public int getY() { return y; }
    public void setY(int y) { this.y = y; }

    public void main(String[] args) {
            C1 obj = new C1();
            obj.setX(10);
            obj.setY(20);

            Map<String, Object> map = new ObjectMapper().convertValue(obj, Map.class);
            System.out.println(map);
    }

}

Comment: I wish I could upvote this some more. This is a great solution! Thanks a lot!
Answer:
Use this:commons-beanutils

File  file = new File();
PropertyDescriptor[] fileObjectDescriptors =
                         PropertyUtils.getPropertyDescriptors(file);
List<PropertyDescriptor> filePropertyList =
                      Arrays.asList(fileObjectDescriptors);
for(PropertyDescriptor fileProperty:filePropertyList){
    attribute = fileProperty.getName()
    value = PropertyUtils.getProperty(file, fileProperty.getName());
 }


Relief from cart path on a hill

Question: I sent this question to the USGA, based on a situation from my last round; we'll see what they say in about a month (if that), but I thought I'd let you guys have a try as I'll be playing the same course before the USGA's likely to get back to me.
EDITED:

A player's ball has come to rest in bounds against the outside edge
(opposite to the fairway) of a formed concrete cart path running
roughly parallel to the line of play, which is an immovable
obstruction. This cart path travels perpendicular to the incline of a
hill rising away from the fairway, such that the nearest point of
relief from the current lie (the closest point perpendicular to the
desired line of play at which the cart path no longer impedes the
player's stance or swing) is further up the incline. The player takes
relief under Rule 24-2b(i) by dropping the ball at this nearest point
of relief. The ball hits the turf and rolls back down the incline,
again coming to rest against the outside of the cart path, thus
requiring a re-drop under 20-2c. This has the same result, and again under rule 20-2c, the ball is required to be placed at the spot; it still rolls, and rolls again when replaced under 20-3, and no suitable point within a clublength of the nearest point of relief can be found where the ball will remain where it is placed.
The player and his fellow-competitors concede that attempting to take
relief at the determined point is futile. So, the player determines a new "nearest
point of relief" to be on the opposite side of the cart path, and
drops a ball at that point. The ball then rolls down the incline onto
the fairway (not nearer the hole), coming to rest more than two
clublengths away from the point of relief, and thus requiring a
re-drop under 20-2c; however, the situation is similar, as whether dropped or placed the ball is almost certain to roll into a position violating 20-2 or 20-3. A fellow-competitor also says that this is a violation of Rule 13-2 as, in taking relief, the player has moved his ball from the rough to the fairway, thus dramatically improving its lie and the line of play beyond what is reasonable to allow in taking relief from the obstruction.
The player and fellow-competitors decide on two solutions they feel to
be equitable: first, to allow the player to play the ball as it now
lies under penalty of one stroke; or second, to return the ball to
its original lie, and then use the procedure under Rule 28b
(determining a point on a line between the lie and the hole and behind
the current lie) to define the "nearest point of relief" at which the
player may take relief under 24-2b(i) without penalty. The player is
given the choice and chooses the latter, and the ball is dropped
successfully at a point 25 yards behind the initial lie, inside the
cart path, and played from that spot to completion of the hole.
Did the players proceed correctly? Would it also have been correct to
choose the first option?

EDIT: edmastermind29's answer to the question as originally stated is completely true and correct; the ball should be placed at the nearest point of relief if after both a drop and re-drop the ball comes to rest in a spot where the obstruction interferes.
However, Rule 20-3d states:

If a ball when placed fails to come to rest on the spot on which it was placed, there is no penalty and the ball must be replaced. If it still fails to come to rest on that spot:
(i) except in a hazard, it must be placed at the nearest spot where it can be placed at rest that is not nearer the hole and not in a hazard;

We may assume, for the purposes of this question, that the hill is steep enough that the ball will roll when placed as well as when dropped; that the crest of the hill is out of bounds; and thus that the "nearest spot where the [the ball] can be placed at rest that is not nearer the hole" is at the edge of the fairway near the bottom of the incline (this really was the situation; the hill, being mostly in the rough, was not being watered due to drought conditions, and as a result what grass there was was thin, dormant and providing virtually no rolling resistance). Thus, the situation would have been the same after the correct procedures were followed.
Rule 13-2 states:

A player must not improve or allow to be improved:

the position or lie of his ball
Comment: "(i) except in a hazard, it must be placed at the nearest spot where it can be placed at rest that is not nearer the hole and not in a hazard;" -- I interpret this to mean that the "nearest spot," although on the fairway, is the "nearest point of relief" and it may be placed on the fairway as the spot satisfies both not being near the hole and not being in a hazard.
Answer: If the ball is re-dropped at "the closest point perpendicular to the desired line of play at which the cart path no longer impedes the player's stance or swing" but once again satisfies rule 20-2c of when to re-drop, the end of rule 20-2c states:

If the ball when re-dropped rolls into any position listed [in rule 20-2c], it
  must be placed as near as possible to the spot where it first struck a
  part of the course when re-dropped.

Then, the ball must be placed given the following:

A ball to be placed under the Rules must be placed by the player or
  his partner.

Did the players proceed correctly? Would it also have been correct to
  choose the first option?

No. The options should have not been considered, let alone determining a new "nearest point of relief," as the ball would have been placed "as near as possible to the spot where it first struck a part of the course" after a re-drop.
Comment: +1 because you are absolutely correct, but see edit.
Comment: @KeithS Did the USGA answer your inquiry yet? I am interested to hear what they say.
Comment: Exactly the same as you. However, I didn't give them the same update as I made here, so I'm still interested in what would be the proper procedure if neither dropping nor placing, neither above nor below the cart path, results in a situation that follows either of the major Rules.

Relief from cart path on a hill


Linear regression, good and bad controls, omitted variable error, and causal graphs

Question: This is my first post on this site, and I would really like to thank everyone who engages in this community. I have learned a lot from reading both the questions and answers. My questions are at the bottom of this post, but I provide some motivation first, hoping to make clear where they come from and what has been my thinking so far.
I'm trying to reconcile what I've learned from the literature on causal graphs with my knowledge from textbook econometrics which is mostly based on the excellent "Introductory Econometrics: A modern approach" by Jeffrey Wooldridge.
In his textbook Wooldridge introduces in "Chapter 2: The simple linear regression model" the model $y=b0+b1*x+u$ where $b1$ "does measure the effect of $x$, holding all other factors (in $u$) fixed" and $u$ is the error term including "all factors affecting $y$ other than $x$". He then explains that we can only interpret our estimator of $b1$, i.e., $\hat{b1}$, causally (as ceteris paribus effect), if the zero conditional mean assumption $E(u|x)=E(u)=0$ holds. The relevant part of this assumption is that the error term $u$ is mean independent of $x$, i.e., $E(u|x)=E(u)$. Most often, we think of this in terms of the implication that $x$ and $u$ should not be correlated, i.e., $cov(x, u)=0$.
The classical example concerns the effect of education on wages. The respective model is $wage=b0+b1*education + u$. Here it is argued that the error term $u$ includes the innate ability. Because individuals with a higher innate ability will have higher education (due to innate ability causing education), the error term $u$ and education will be correlated, meaning that the zero conditional mean assumption is violated. In other words, we have an omitted variable error, and $\hat{b1}$ cannot be interpreted causally (as ceteris paribus effect). The solution (I know there are different ones, but that's not my point here) would be to measure innate ability (leaving discussions of whether this is possible aside), moving it from the error term $u$ into our model by making it an additional $x$ variable. In this case, the innate ability would be a "good control variable".
Later in the chapter "6-3c Controlling for Too Many Factors in Regression Analysis", Wooldridge discusses another example where interest is in the causal effect of a beer tax on fatalities. He then explains that we should not include beer consumption in our respective model, because the effect of a beer tax on fatalities will be mostly due to beer taxes reducing beer consumption and the latter is causing fatalities. In this case, beer consumption "would be a bad control variable". I, of course, agree with this explanation and I understand it intuitively as well as when I consider what I've learned from the literature on causal graphs (i.e., adjusting for beer consumption would violate the backdoor criterion).
But I'm wondering how Wooldridge would formally justify his very clear statement "Are we committing an omitted variables error? The answer is no" (as he does not refer to criteria such as the backdoor criterion as a justification). Consider the model $fatalities = b0 + b1*beertax + u$. If we think about it the same way as for the model relating wages to education, I would think that beer consumption is included in the error term $u$ as it is among all factors affecting fatalities other than beer tax. And because beer tax and beer consumption are correlated (due to beer tax causing beer consumption), the error term $u$ and beer tax will be correlated and, therefore, the error term $u$ will not be mean independent of beer tax violating the assumption. In other words, we have an omitted variable error.
So, my question is how to reconcile this. Are we formally really not committing an omitted variable error, and, therefore not violating the mean independence assumption? If so why is this case and where am I wrong?
I can think of two ways to reconcile it myself, but I'm not really sure about either:
First, we are not committing an omitted variable error in the second example, because beer consumption is, against my current thinking, not part of the error term $u$. Then the error term $u$ would not be correlated with beer tax and everything would be ok. But then my question really would be, why beer consumption, which from my understanding does have an independent effect on fatalities, would not be part of the error term $u$. Would it be because all the variation in beer consumption that is caused by beer tax does not represent an independent effect on fatalities and the remaining variation in beer consumption (coming from any other sources of beer consumption and representing an independent effect) is indeed mean independent of beer tax? If so, how would we show this formally using the notation of Wooldridge?
Second, we are committing an omitted variable error, but the mean independence assumption as presented in Wooldridge formally refers to the direct causal effect rather than the total causal effect, so it would be related to the single door criterion instead of the backdoor criterion in the language of causal graphs. This seems unlikely to me as Wooldridge is really clear in stating that we are not committing an omitted variable error and therefore the mean independence assumption should not be violated.
I hope my questions are articulated clearly enough, but let me know if I should edit certain parts. Thank you for your answers!
Edit based on Michael's answer:
Thanks, Michael. Your answer below is already very helpful. Allow me to follow up on it, just to make sure I understand you correctly.
Wooldridge defines the error term $u$ as "The variable $u$, called the error term or disturbance in the relationship, represents factors other than $x$ that affect $y$." when discussing the simple linear regression model and as "Just as in simple regression, the variable $u$ is the error term or disturbance. It contains factors other than $x_1, x_2, ..., x_k$ that affect $y$." when discussing multiple regression. To me, this definition is the same as what you state to be not quite the interpretation of the error term. So, because this definition of the error term is not precise, I wrongly assumed that beer consumption would be included in the error term, which, in fact, it is not. To show this you pointed me to the "chain rule". Let me try to illustrate your argument in detail. We can think of the example concerning beer taxes ($x_1$), beer consumption ($x_2$), and fatalities ($y$) as a system of linear structural equations:
$x_1 = e_{x_1}$
$x_2 = a_0 + a_1*x_1+e_{x_2}$
$y = g_0 + g_1*x_1+g_2*x_2+e_y$
Now I can rewrite the equation for $y$ by inserting the equation for $x_2$
$y = g_0 + g_1*x_1+g_2*(a_0 + a_1*x_1+e_{x_2})+e_y$
Rearranging this equation gives
$y = (g_0 + g_2*a_0) + (g_1+a_1*g_2)*x_1 + (g_2*e_{x_2}+e_y)$
Redefining the terms $(g_0+g_2*a_0)=b_0$, $(g_1+a_1*g_2)=b_1$, and $(g_2*e_{x_2}+e_y)=u$ gives us the familiar looking model
$y = b_0 + b_1*x_1 + u$
Here it can be seen that $u$ does not include $x_2$ (only its independent part $e_{x_2}$) and that $x_1$ is not correlated with $u$, as it is not correlated with any of the components of $u$.
In contrast, if we think of the example concerning education, innate ability, and wages as a system of linear structural equations the same "trick" of chaining equations will not be possible and ultimately, $x_2$ (innate ability), will be part of the error term after having redefined the terms.
So, after all, the first "solution" in my original post would be right?

First, we are not committing an omitted variable error in the second example, because beer consumption is ... not part of the error term $u$.

If what I have written here is correct, the question is what a more precise definition of the error term would be. Should it be something like this?
"The variable $u$, called the error term or disturbance in the relationship, represents factors other than $x$ that affect $y$ and that themselves are not affected by $x$?"
With such a definition, I would not have made the mistake to think that beer consumption is part of the error term.
Edit
In a comment below Michael suggest rephrasing the more precise definition to "The variable $u$, called the error term or disturbance in the relationship, represents factors other than $x$ that affect $y$ and that themselves are not channels of the effect of $x$ on $y$?"
Comment: That is very good, except you need to move $g_2*a_0$ into the intercept, so the error term in the final regression has mean zero (another reason to always include an intercept term). Your phrase "...and that themselves are not affected by x..." is too strong a requirement. It also excludes "correlated with x", which is the definition of omitted variable bias. Indeed in your wage on education regression, there's a bias b/c the omitted variable---part of $u$---is correlated with education. One can rephrase that as, e.g. "variables which are not channels of the effect on x on y".
Comment: Thanks, I see! I have edited this in the post above.
Concerning the more precise definition of the error term. I think "... and that themselves are not affected by x." and "are not channels of the effect of x on y" are the same, no? I think it does not preclude correlated with x because it still allows x and u to be correlated due to u causing x?
Comment: It is a point of empirical semantics. The point here is that if $y(z(x))$ describes the relationship between $x$, $y$, and $z$, then $z$ is a bad control in the regression of $y$ on $x$. You provided an example above where all function forms are linear. Some of the partial effect of $x$ would be mistakenly captured by the coefficient on $z$, whose partial effect derives solely from that of $x$.
Comment: Not sure I understand exactly what you mean by "It is a point of empirical semantics" but since what I believe I'm trying to say is the same as your rephrasing, I added the latter to the edit in the original post, so your suggested rephrasing can be directly seen. Thanks again!
Comment: Do you know a reference that uses a more precise definition of the error term along the lines you suggested?
Comment: Not really, no. (Perhaps someone else does and can share.) Starting with precise general first principles is usually not the style/priority of empirical econometrics. Rather it's communicated through empirical examples. You can find more discussion on bad control in Section 3.2.3 of "Mostly Harmless Econometrics". There, "...Bad controls are variables that are themselves outcome variables in the notional experiment at hand" is offered as a type of empirical description of bad control.
Comment: I understand the pedagogical points and I think Wooldridge is excellent. I know the bad controls section in MHE, thanks. I'd also recommend this [paper](https://ftp.cs.ucla.edu/pub/stat_ser/r493.pdf)  offering a nice overview. I agree with what is written in these references, I just wanted to understand it from the notation of intro econometrics textbooks, and here I apparently took the definition of the error term too literally. In their Primer Pearl et al. (2016, p. 81) define the error term as "factors ... that influence Y and are not themselves affected by X" which confirms our rephasing.
Answer:
But then my question really would be, why beer consumption,
which...does have an...effect on fatalities, would not be part of the
error term u?

The error term in the linear model is not interpreted to contain quite "...all factors affecting fatalities other than beer tax" (although you can see why it's not unreasonable for make this initial claim for pedagogical reasons).
If the regressor $x$ channels its effect on $y$ through $z$, and that is the only way $z$ influences $y$, you can see why the model
$$
y = \beta_0 + \beta_1 x + \beta_2 z + u
$$
would not make sense---the partial effects of $x$ and $z$ on $y$ are not additive. Rather, the functional form that incorporates both $x$ and $z$ would be a type of composition (e.g. $y(z(x))$) and the partial effects operate via a chain rule. Therefore adding $z$ would be adding bad control. That is Wooldrige's point in the example where $x =$ beer tax and $z= $beer consumption. Empirically, some of the partial effect of $x$ would be mistakenly captured by the coefficient on $z$, whose effect on $y$ derives solely from that of $x$.
Notice this is not the case for your example of omitted variable bias,
$$
wage=\beta_0 + \beta_1*education + u.
$$
The effect of education on wage is not channeled through the omitted variable. It is reasonable to assume the partial effects of education and omitted variable are additive.
Another situation where a variable that has an effect on $y$ but is not contained in $u$ is simultaneous equations. The classic example is demand function estimation. Consider the demand-supply system
\begin{align*}
q &= \beta_{0,d} + \beta_{1,d} p + \epsilon_d \\
q &= \beta_{0,s} + \beta_{1,s} p + \epsilon_s.
\end{align*}
The supply shock---error term $\epsilon_s$ in the supply equation---has an effect on quantity $q$ but is not contained in the demand shock $\epsilon_d$. In this case, this can be exploited---an instrumental variable can be extracted from the supply shock to instrument $p$ in the demand equation.

...the backdoor criterion...

I believe neither the back-door nor front-door criterion describes the case of bad control.
The backdoor adjustment corresponds to adding controls for omitted variable bias, while the front-door adjustment covers IV as a special case.
(Other folks more familiar with do-calculus would be able to comment more precisely on this.)
Comment: Thank you, Michael! This is a very helpful answer. I hope I upvoted it correctly. In order to make sure that I understand you correctly and to ask a follow-up question, I've added an "Edit" to my original post. I hope this is the right way to do this. I will check your answer as right, once you have confirmed my understanding in the "Edit".


Get lasting permission to write to a specific directory with the new Sandbox requirements

Question: I need a way to get & keep permission to write to a specific directory in OS X. How can that be done while abiding with the new Sandbox requirements?
Answer: The recipe:

Ask the user to select the directory - use a standard open dialog limited to directory selection. Apart from a few special directories (music, pictures etc.) there is no way to gain access apart from asking the user.
Create a security-scoped bookmark using the URL returned by the standard open dialog, just search the Apple docs for "security-scoped bookmark".
Persist that bookmark, either in user preferences or in the Application Support folder for your app.
On application launch, or before you need access, read in the saved bookmark and activate - you'll find out how to do this in the Apple docs as above.


Splitting functionality on a server

Question: Hi I was wondering the best way to setup my current application. Here is the general rundown.
I have a phone application that uploads and downloads photos from a vps that will store the files statically on it.
The phone application does a webrequest to a script which queries a local database for a photo filepath which then gets returned which then after the phone makes another request back to the same server for photo.
This server is also used to house the website.
I was wondering what is the best way of splitting off the functionality. From what I understand I should get another server which just houses the database and have scripts on the vps which query the database server. Should I store the photos on the database server as well or should that be on the server that houses the database?
Also would I be needing a ec2 server or would a general vps like thrust work for something like this?
Comment: It depends what you want to achieve. To improve performance? To ensure scalability? For security reasons? Because the new VP read about it in Information Week?
Comment: To ensure scalability you should make them separate processes, and keep an eye out for storage, but there's no reason you have to have several servers from day 1, except maybe to prevent a SPOF.
Comment: It's to ensure scalability. I am about to do a trial run which will involve roughly 600 phones and I just want to ensure it doesn't crash.
Answer: Yes, general web scalability practices use separate web, database and file servers. However, don't just blindly do it now without knowing where your performance and scalability bottlenecks are.
You need to benchmark and profile your app before you start making changes. Make it work, then make it fast.
Also, you can probably handle a reasonable load on one server with appropriate caching and tuning of each layer (web, database, file system).
Comment: Thank you for the response. What is a good method to test performance / bottle necks with php? I've only used apache bench to see what the server can handle and it seems alright. Are there any standard methods to test these things?
Comment: Use xdebug and webgrind (http://xdebug.org/, http://code.google.com/p/webgrind/) for PHP profiling. They will show you exactly where your code spends most of its time.

Splitting functionality on a server


Customize days that can be clicked on a Calendar popup

Question: I am creating a form in Drupal 7 with the form API. Right now, I can create an ordinary calendar input field with the following code:
   $form['services_tab']['schedule_datepicker'] = array(
    '#title' => t('Pick the desired date'),
    '#type' => 'date_popup',
    '#date_year_range' => '0:0',
    '#date_format' => 'Y-m-d',
    '#prefix' => '
',
    '#suffix' => '
',
  );

Right now I can get the beautiful calendar popup to appear. What I am trying to achieve is enable or disable certain dates based on a rule like: disable all Saturdays and Sundays; or even remove the click state from specific dates based on a list of national holidays...
Is this something that can be achieved with PHP coding, or does it need to be done with jQuery? In case jQuery is the solution, I would appreciate any hints on how to do that... The calendar is a table, but table cells don't have an ID or something that could help me find and disable them based on a rule...
Thank you.
Comment: This "[How to disable weekends][1]" answer will help you for disabling weekends and some days.

  [1]: http://stackoverflow.com/questions/501943/can-the-jquery-ui-datepicker-be-made-to-disable-saturdays-and-sundays-and-holid
Answer: You can pass some Datepicker options from php to the date_popup element through the '#datepicker_options' key:
<?php
$form['date'] = array(
  '#title' => t('Pick the desired date'),
  '#type' => 'date_popup',
  '#datepicker_options' => array(
    'minDate' => 0,
  ),
);

With this method you can pass almost any option but those that accept a function as value, as beforeShowDay, the one needed to restrict weekends or holidays according to the answer referenced by Nikit: https://stackoverflow.com/questions/501943/can-the-jquery-ui-datepicker-be-made-to-disable-saturdays-and-sundays-and-holid
Hence, javascript is required. First you need to include a custom js file from your module code:
<?php
drupal_add_js(drupal_get_path('module', 'FOO') . '/FOO.js');

and provide some code in FOO.js to extend the settings set by date_popup module with our own options.
Here's an example that add the basic option to disable weekends for all datepicker widgets in the page:
(function ($) {
Drupal.behaviors.FOO = {
  attach: function (context) {
    for (var id in Drupal.settings.datePopup) {
      Drupal.settings.datePopup[id].settings.beforeShowDay = $.datepicker.noWeekends;
    }
  }
};
})(jQuery);

Extend to holidays is left as an exercise to the reader :)
Note: the three occurences of FOO in my examples doesn't need to be the same literal, ie: you can provide a BAZ behaviour in BAR.js from FOO.module.
Update: to extend the above for custom days availability, just add a function returning true/false for the day received by parameters.
(function ($) {
Drupal.behaviors.FOO = {
  attach: function (context) {
    for (var id in Drupal.settings.datePopup) {
      Drupal.settings.datePopup[id].settings.beforeShowDay = checkDate;
    }
  }
};

function checkDate(date) {
  if ((date.getDate() % 2) == 0) {
    return [false, 'Even days not available'];
  }
  else {
    return [true, 'Odd days are fine'];
  }
}
})(jQuery);

You can find a more complete example in Date Restrictions module.
Comment: yes, there's also a maxDate: http://api.jqueryui.com/datepicker/#option-maxDate
Comment: Thank you, Jonhattan! I have successfully set the minDate and it disables all the past days. This is a great beginning for me. I wonder if I can set something like a maxDate, as I want to keep only a range of some 15 days enabled. I can see there is a 'fromTo' attribute, but have no clues on what it is going to do. My idea is to disable all dates in the past (done) and all dates in the future (some 15 days from now()). In the middle, I will check the date pickeer javascript documentation to see how to individually disable some of the open days.
Comment: Thanks, for some reason, when I was looking into the documentation of the date_popup field I couldn't find information on the maxDate option. This worked for me and restricted the calendar to a maxDate: '#datepicker_options' => array(
      'minDate' => 0,
      'maxDate' => 30,
    ),
Comment: jonhattan, I am sorry to ask again. I am pulling my hair trying to execute a custom function. I have implemented your model and it works great for me. But now I want to execute a custom function to allow only specific dates. I see you have suggested the holidays as an exercise for the reader ;-) This reader is almost crazy trying to solve this problem. If it isn't a huge additional work for you, do you mind posting how you would solve this? Don't bother about details, I just need an overall help to do the call to customFunction(date). Thank you!
Comment: Marcos, I've updated my answer with a simple example of the usage of a custom function.
Answer: I have used Date Restrictions module. This provide and option to restrict date on number of parameters like fixed date, Relative date, etc.


Apache log to database

Question: I'm in the middle of setting up various web servers for my company that hosts several websites.  Some of the sites could be hosted on any server at any point in time (floating IPs).
For ease of use, I'd like to send all the Apache log information to a database.  I have experience using cronolog for rotating logs on a daily basis, but I'd like to update the database more often than that.  It seems as though cronolog or just straight Apache, both stream to the log file (probably for performance reasons).  If I were to move the file for database processing, they continue writing to said file.
Has anyone done this and have any advice for setting something like this up?
Answer: You need to look into using logtail and grab what you need.

Apache log to database


is the intersection of subgroups a subgroup of each subgroup

Question:
Suppose $G$ is a group, take $H,K$ as subgroups of $G$ so $H,K\leqslant G$. I know that $H\cap K\leqslant G$ but is it the case that $H\cap K\leqslant H$ and $H\cap K\leqslant K$?

I am guessing this does not hold but why?
Also I tried with the case that $H=\langle g \rangle,K=\langle h \rangle$ where $g$ and $h$ are the elements in $G$ ($\langle h \rangle$ means the minimum subgroup that contains the element $h$ if you haven't seen this notation before). I used the subspace test and I think that $H\cap K\leqslant H$ and $H\cap K\leqslant K$ hold unless I make a mistake somewhere.
Much thanks in advance!
Comment: A subgroup is just a subset which behaves as a group under the same operation. The intersection of two subsets is a subset of both. The operation does never change, so subgroups behave like subsets in these aspects.
Answer: It is indeed true that $H \cap K$ is a subgroup of both $H$ and $K$. For the sake of clarity, we recall the definition of a subgroup below:

Definition. Let $(G, \odot)$ be  group with identity $e$ and let $H$ be a subset of $G$. We say that $H$ is a subgroup of $G$ if each of the following hold:

$e \in H$,
if $h_1,h_2 \in H$ then $h_1 \odot h_2 \in H$,
for all $h \in H$, its inverse element $h^{-1}$ with respect to $\odot$ is also in $H$.

These axioms make it so that $(H, \odot)$ is a group in its own right with the very same group operation $\odot$ and identity $e$. We also point out that these properties have less to do with the set $G$ than the operation $\odot$ that $G$ comes equipped with.
Now, let $G$ be a group and let $H,K$ be subgroups of $G$. You have already verified that $H \cap K$ is a subgroup of $G$. Why must it also be a subgroup of $H$ (and $K$)? First, it's clear that $H \cap K \subseteq H, H \cap K \subseteq K$ and that $H \cap K \ni e$. Moreover, because $H \cap K$ is a subgroup of $G$, it is satisfies properties 2. and 3. above. Thus, by replacing $G$ with $H$ or $K$ in the definition above, it's immediate that $H \cap K$ is a subgroup of $H$ (and $K$) as well!
In short, as long as $H$ is a subset of a group $G$ and $H$ satisfies the properties listed above, it will be a subgroup of $G$.
Answer: The subgroup test is:

$H$ is a subgroup of $G$ if and only if for each $x,y\in H$ we've $xy^{-1}\in H$.

Applied to a collection of subgroups $\{H_s\}$, let $x,y\in\bigcap_sH_s$ be a pair of elements. Then $x,y\in H_s$ for all $S$ and since $H_s<G$ then $xy^{-1}\in H_s$ for every index $s$, so $xy^{-1}\in\bigcap_sH_s$, hence $\bigcap_sH_s$ is a subgroup too.
Answer: The intersection of two (or any quantity of) subgroups is always a subgroup of all the intersecting subgroups. Indeed, this is a particular case of the following general remark.

Remark. A subgroup $H \leqslant G$ is also a subgroup of any subgroup $K \leqslant G$ containing $H$. More precisesly, if $G$ is a group and $H \subseteq K \leqslant G$ then:
  \begin{equation}
H \text{ is a subgroup of } G
\Leftrightarrow
H \text{ is a subgroup of } K \,.
\end{equation}

Recall that a subset $H \subseteq G$ is a subgroup of $(G,\cdot)$ if and only if $H$ is a group with (the restriction to $H$ of) the operation in $G$. But,  if $H \subseteq K \leqslant G$, then the restriction of $G$ to $H$ is the same as the restriction of $K$ to $H$. Hence, the condition for $H \leqslant G$ is exactly the same as the condition $H \leqslant K$.
Your question just corresponds to the case: $H \cap K \subseteq H,K \leqslant G$.


How to add samples in Asset Store?

Question: I cannot add an instance to my asset in the Asset Store. I looked at the documentation but couldn't succeed. Where am I making a mistake?

MyPackage
  ├── package.json
  └── Samples~
        ├── StarterAssets

package.json
{
    "samples": [
        {
            "displayName": "StarterAssets Example Scenes",
            "description": "Contains demo scenes with StarterAssets.",
            "path": "Samples~/StarterAssets"
        }
    ]
}

Comment: Hello, might want to include more information, such as any error/warning logs within your unity engine. Though, I would recommend you post your questions here instead: https://gamedev.stackexchange.com/
Answer: I solved the problem. When I moved the project from the Plugins folder to the Packages folder, samples started to appear.

How to add samples in Asset Store?