user/login page - no access to it

Question: I want to add a Login link in the user menu. When I give it the path 'user/login', I get the message:
The path 'user/login' is either invalid or you do not have access to it.
If I give it a path of 'user', it works.  However, that's not the path I want, because it will still be visible to the logged-in user.
If I give it a full path, http://mysite.com/user/login, it works BUT isn't hidden from the logged-in user.  Puzzling.
Any ideas?  I am pretty sure I could use a module to handle this, but it seems like overkill.
Comment: You cannot see `user/login` path after logged in. In fact there is nothing a logged in user can do.
Comment: Right, but I can't put that path into the User menu.  I get the error above when I enter it as a link.
Comment: If you use proper menu or drupal `l()` function to print the link, it will not be there for logged in users. Means it will follow Drupal permissions.
Answer: If you are using the Sub-pathauto module simply:

Disable the subpathauto module.
Add your menu item(s) for user/login.
Re-enable the subpathauto module.
Answer: Thank you to everyone who answered.  I was not asking about whether or not the login link was visible, but was instead asking how to enter the user/login path on the user menu or in the URL aliases without getting an error.
I solved it by using the path user/login? instead of user/login.  So simple, so much time wasted.
Comment: wow, too clever. It worked and can't be anymore simple.
Answer: How about wrapping it in a conditions like these?
if (user_is_logged_in()) {
  // Do something.
}

or
if (user_is_anonymous()) {
  // Do something.
}

A useful link - https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_menu_site_status_alter/7
Comment: Thanks for the hint, so I no longer user !user_is_logged_in() anymore :)
Answer: That error message is show from the form validation handler used by the form that allows you to add a menu item, or edit it; it calls drupal_valid_path(), which contains the following code.
return $item && $item['access'];

As @Nikhil M said in his comment, logged-in users don't have access to that menu item, which means $item['access'] is FALSE.
The only way I found to add that link was first creating a path alias (e.g. user-login) to /user/login, and then using the path alias when creating the menu item.

Apparently it works.

Once logged in, the menu item doesn't appear.

I have also tried with a different menu (e.g. the Main menu) and it works.

At first, it seemed not to work, since the link was not shown when I logged out. To see the login link, I had to clean the Drupal cache, and refresh the page from Firefox after logging out.
Comment: This is a great-looking solution, and I was hopeful, but the URL alias is giving me the same error message when I enter /user/login, so I can't make the alias either.
Comment: I am not having a problem with whether it shows up if you are logged in or not.  I know it will work if I can just get either the menu or the URL alias config to accept user/login.
Comment: I didn't have any problem for the path alias to accept user/login as existing system path of the alias. If that makes any difference, I used the user 1 account to set the path alias.
Answer: One of my colleagues came up with a simple solution that I'm sharing in case it helps others. "Basically, you can't edit an existing menu item that links to user/login, you have to create a whole new one. I did that and it's working now!"
So you can create a menu item with the path in question (user/login), but you'll never be able to edit it. If you want to change the text down the road,create a new menu item and delete the old.

user/login page - no access to it


HTML added with .append() is not triggering events

Question: I have some jQuery appending HTML from a PHP script.
jQuery
$.ajax({
    type: "POST",
    url: "newPage.php",
    data: data,
    cache: false,
    success: function(html)
    {
        $('.item1 ul').append(html);
    }
});

PHP
    echo"
".$pages["title"]."
";

After appending, no jQuery events work on the new HTML.
Answer: You need to delegate your events with .on()
You can read specifically about this here
But basically you need to attach the listener higher up in the DOM heirarchy.
so instead of this...
$('.selector').on('event', function(e) {...});

do this
$('.item1 ul').on('event', '.selector', function(e) {...});

Why?
This works because the dynamic elements that are not yet on the page when you bind the events, still fire the events, they just don't have the handlers.
Thanks to event bubbling all DOM elements up the tree will hear their descendant's events (unless propagation has been stopped), and can act on them accordingly.
In this example, when '.item1 ul' hears that an 'event' has been triggered from one of it's child elements, if it was '.selector' that triggered it, the handler will fire.
Comment: Brilliant! At first it didn't work so I added event to the function.  `$('.item1 ul').on('click', '.del-page', function(event) {...});` thanks
Answer: You're probably binding your events to the elements:
$('button').click(function() {
    ...
});

This works only if the $('button') selector returns the elements you want. Your problem is that the selector is called once. It won't update to account for elements that were created after your selector has been called.
You should use the event delegation syntax to bind the event to an already-present parent element:
$('#parent').on('click', 'button', function() {
    ...
});

That way, when the #parent receives a click event, it'll look for elements matching button and pass the event off to them.


Write $\in$ or $\subset$ for a domain in $\mathbb R^2$?

Question: I think $\subset$ mean a subset of set, i.e. $D \subset \mathbb R^2$ . and $\in$ mean an element of a set, i.e. if $a$ is an element in $D$, we write $a\in D$.
But in the following $D$ is a domain  in $\mathbb R^2$, writing $D\in \mathbb  R^2$.
Isn't it wrong? Is it not more correct with $D\subset \mathbb R^2$?

Denoted $D\in \mathbb R^2$ for a two-dimensional domain bounded by the closed smooth contour $\Gamma$. $u$ is definied on the domain $D$ and satisfies Laplace's equation:
  $$
\nabla^2 u(x_1,x_2)=0, \quad \text{in }D$$
Comment: You're absolutely right, it should be $\subset$.
Comment: I would guess this is simply a typo, since the error is so elementary. But if many other errors are also present in whatever publication this is from, then maybe it is not a typo, but instead it is an error. [My diplomatic terms: "typo" --- author would recognize it as incorrect but due to an oversight, the author did not notice the error during proofreading; "error" --- author would not recognize it as incorrect and intentionally used the incorrect notation.]
Answer: To supplement Arnaud Mortier's comment:
$\Bbb{R}^2$ is a set of ordered pairs. Therefore, if you say $D\in\Bbb{R}^2$, then you are implying that $D$ is itself an ordered pair.
By contrast, the subset relation $\subset$ compares, naturally, two sets. If you say $D\subset\Bbb{R}^2$, then you are implying that $D$ is a set. (Assuming $D\neq\varnothing$, it will contain at least one ordered pair.)
The explanation in the block quote is definitely wrong in this regard.
Comment: @JDoeDoe No . . . $D$ is the **domain** in question, meaning it's the set of values that the **independent** variables $x_1$ and $x_2$ can take. Because of the ancillary information given in the block quote, you can describe $D$ thusly: $$D=\left\{(x_1,x_2)\in\Bbb{R}^2:\nabla^2u(x_1,x_2)=0\right\}$$ meaning $D$ is all this points where the Laplacian is zero. In univariate calculus ($y=f(x)$), the domain refers to a set of $x$-values.
Comment: Hi, thanks! With "in $D$" after the equation "$\nabla^2 u(x_1,x_2)=0$", does it mean $u$ is in $D$? If so, I guess we write $u(x_1,x_2)\in D$ (or $u\in D$), "the function $u$ is an element of the set $D$"?


Mapping a Drive to File Server (Win2008) results in incorrect password / username error after Reboot or Logoff/in

Question: Here is the setup.  Very small network.  Windows 2008 with a single folder shared as 'Data'.  Win2k8 server (called Server) has user account called Staff that is part of Users group.  On a network attached laptop, when I go to map a network drive to \Server\Data using the Staff username and password - Server\Staff as username I can connect to the mapped drive.
Once the user reboots or logs out and back in I get an error saying: Incorrect Password Or Unknown Username and it has the password field blank.  I am putting in the SAME password I originally did for the mapped drive and I am then able to see the contents.
How do I fix it so that I don't have to put in the password every time a client machine reboots?
FYI - the is no AD on the 2k8 server, just a workgroup with local user accounts.
Comment: Why aren't you using AD?
Answer: Check in Stored User Names and Passwords (If I remember correctly that it was called that in XP) in Control Panel for the entry. If you find it there try deleting it and recreating it.
Comment: Not visible, I think this is only available on XP machines connected to a domain, there is no domain here.
Comment: You can check for mapped drives with "net use" then. Delete any that exist and recreate them.


Mean Squared Error random variable

Question: I'm reading Elements of Statistical Learning (2nd edition, 12th printing) and there are two things that are bothering me.
Regarding Equation 2.25, one is the training set Τ. I'm assuming that it is a function of two random variables X and Y, so when calculating the expected value, would the underlying probability density function be the joint distribution of X and Y?
Another thing is whether I should be interpreting y0-hat as a constant or a random variable? I know that it is an estimate of the test input point. If y0-hat is a random variable, what would be the underlying probability distribution?
I understand the derivation of decomposition of mean squared error into variance and bias, but when I look at Var(y0-hat), I can't help thinking that y0-hat is a constant and hence Var(y0-hat) = 0. What's wrong with my thinking?
Similar confusion arises for expected prediction error (equation 2.27), where the expected value is calculated with respect to y0|x0, which seems to me that y0 is a random variable and x0 is an event.
Sorry, I don't know how to format. Apologize if this was already posted. Any help would be greatly appreciated!
Answer: Yes, $X$ and $Y$ are random variables. Let me fill in some of the technical details.
For convenience, let $Z_i = (X_i,Y_i)$ be i.i.d. and define $\mathbf{Z} = \{Z_1,\ldots,Z_N\}$.
The estimator $\hat{y}$ is a function of all the observations in the training data (which is random) and $x$ (which is deterministic). In other words,
$$\hat{y}= g(\mathbf{Z},x)$$
For example, the linear prediction fits this form
$$ \hat{y} \equiv \hat{y}(x) = x \hat{\theta}_{OLS}$$
where $\hat{\theta}_{OLS}$ is the ordinary least squares estimate using all the observations in the training sample. In this case, $x$ is just a user-input whereas $\hat{\theta}$ needs to be estimated (with uncertainty). The true prediction is $f(x) = x \theta$.
This basic notation allows us to answer your question

The expectation is taken over $\boldsymbol{Z}$, which includes all the $(X,Y)$ values in the training sample.
The estimator $\hat{y}$ depends on the realizations of all the $Z_i$. You would get a different result if you randomly selected another training sample. Therefore, $Var(\hat{y}) > 0$.
Yes, the MSE is a function of a deterministic input, $x$. However, remember that $\hat{y}$ is a function of both $\mathbf{Z}$ and $x$. The expectation integrates over $\mathbf{Z}$. There is no need to compute a conditional expectation.

Mean Squared Error random variable


Copy only one variable from one R data.table to another after matching on a variable

Question: I can conduct a matched copy of a column in a data frame into another by something like
DF2$y <- DF1[match(DF2$id2, DF1$id1), "z"]  # DF1 and DF2 are data frames

where DF2$id2 is matched to DF1$id1. I would like to know what I can do with data tables for this kind of operation. My data tables have millions of rows and hundreds of columns. I've done setkey(DT1, id1) and setkey(DT2, id2).
This works:
DT2[, y := DT1[match(DT2$id2, DT1$id1), "z"]]  # DT1 and DT2 are data tables

but I am afraid that the match part might take long than necessary. (Or is it inevitable?)
I understand that I can also use column selection, merge, and renaming:
tmp <- DT1[, c("id1", "z")]  # column selection
DT3 <- merge(DT2, tmp, by.x = "id2", by.y = "id1", all.x = TRUE, suffixes = c("", ".y")) # merge
setnames(DT3, "z.y", "y")  # rename

(where the first two lines can be written on one line) but this seems a bit too complicated. Would there be a simpler and fast solution?
Thanks.
Example:
library(data.table)
DF1 <- data.frame(id1=2:4, x=LETTERS[1:3], z=11:13)
DF2 <- data.frame(id2=1:4, x=LETTERS[5:8], z=21:24)
DF1
#   id1 x  z
# 1   2 A 11
# 2   3 B 12
# 3   4 C 13
DF2
#   id2 x  z
# 1   1 E 21
# 2   2 F 22
# 3   3 G 23
# 4   4 H 24

DT1 <- data.table(DF1)
DT2 <- data.table(DF2)
setkey(DT1, id1)
setkey(DT2, id2)

DF2$y <- DF1[match(DF2$id2, DF1$id1), "z"]
DF2  # correct
#   id2 x  z  y
# 1   1 E 21 NA
# 2   2 F 22 11
# 3   3 G 23 12
# 4   4 H 24 13

DT2[, y := DT1[match(DT2$id2, DT1$id1), "z"]]
DT2
#    id2 x  z  y
# 1:   1 E 21 NA
# 2:   2 F 22 11
# 3:   3 G 23 12
# 4:   4 H 24 13
DT2[, y := NULL]

tmp <- DT1[, c("id1", "z")]
DT3 <- merge(DT2, tmp, by.x = "id2", by.y = "id1", all.x = TRUE, suffixes = c("", ".y"))
setnames(DT3, "z.y", "y")
DT3
#    id2 x  z  y
# 1:   1 E 21 NA
# 2:   2 F 22 11
# 3:   3 G 23 12
# 4:   4 H 24 13

## Simpler alternatives?

Comment: `merge` is the simple. It's annoying about this particular example that the names of your ID columns don't match, and the name of the column you want to add needs to change, but renaming is a one-liner that is very efficient.
Comment: Or a little more simply, `merge(DT2, setnames(DT1[, c("id1", "z")], c("id2", "y")), all.x = TRUE)`
Comment: And I would agree with your worry - I would expect `data.table::merge` to be much faster than `base::match`, especially on keyed tables. But I disagree with your assessment that renaming a couple columns is too complicated.
Comment: @GregorThomas Sure. Thanks. I wondered if there are other solutions, and I am glad to learn I need not look for other solutions. I've been wandering around with this issue so long.
Comment: @GregorThomas Thanks. But I want to "merge" only one variable, not the full data set. For this I need to do column selection, merging, and then renaming as I explained in the question. Are there simpler ways?
Answer: If I understand correctly, the OP wants to append column z from DT1 to DT2 as column y where the id columns match.
With data.table, this can be solved using an update join:
library(data.table)
DT2[DT1, on = .(id2 = id1), y := i.z]
DT2

   id2 x  z  y
1:   1 E 21 NA
2:   2 F 22 11
3:   3 G 23 12
4:   4 H 24 13

Note that DT2 is updated by reference, i.e., without copying the whole data object. This might be handy for OP's large production datasets of millions of rows.
Caveat
This works because id1 and id2 are unique which is the case for the sample use case. So, make sure that you get what you want when you do update joins on duplicate values.
Let's see what will happen if there are duplicate values in the id1 column, e.g.
In case DT1 has id1 == 4 duplicated
(DT1 <- data.table(id1 = c(2:4, 4), x = LETTERS[1:4], z = 11:14))

   id1 x  z
1:   2 A 11
2:   3 B 12
3:   4 C 13
4:   4 D 14

then
DT2[DT1, on = .(id2 = id1), y := i.z][]

returns

   id2 x  z  y
1:   1 E 21 NA
2:   2 F 22 11
3:   3 G 23 12
4:   4 H 24 14

So, the update join

has not created additional rows in DT2 (which is probably what you may want to avoid copying of large datasets),
has picked the last occurrence of z in case of multiple matches.
Answer: I have two possible ideas:

Using merge and select the columns and do the renaming there

DT3 <- merge(DT2, DT1[, .(id1, y = z)], by.x = "id2", by.y = "id1", all.x = TRUE)

Using data.table's on syntax. I based this solution directly off of the answer here, which shows how to do a full outer join:
https://stackoverflow.com/a/46904676/9244371

unique_keys <- unique(c(DT1[, id1], DT2[, id2]))
DT3 <- DT2[DT1[.(unique_keys), .(id1, y = z)]]


Unclassifiable statement in an equation in Fortran

Question: So far my code is working properly except I am now getting a compiler error error like this:
std =std +((x(I) -xbar))**2)
 1
Error: Unclassifiable statement at (1)

Here is my code:
program cardata
implicit none
real, dimension(291) :: x
intEGER I,N
double precision date, odometer, fuel
real :: std=0
real :: xbar=0

  open(unit=10, file="car.dat", FOrm="FORMATTED", STATUS="OLD", ACTION="READ")
  read(10,*) N
  do I=1,N

  read(10,*) x(I)
  xbar= xbar +x(I)

  enddo
  xbar = xbar/N
  DO I =1,N
std =std +((x(I) -xbar))**2
  enddo
  std = SQRT((std / (N - 1)))

  print*,'mean:',xbar
  print*, 'std deviation:',std
  close(unit=10)
  end program cardata

I am fairly new to this, any input will be greatly appreciated.
Comment: Your () aren't balanced.
Comment: Well thanks!! that compiled without errors! but now nothing is being printed, so I don't know if I should write another question as to why my code is not doing the operations it should. However, can I ask for your opinion? Is my code look right? there is 3 columns in the files and I want to average each column and take the std.
Answer: Count the parentheses.
std =std +((x(I) -xbar))**2)

There are three of these: (
There are four of these: )
Comment: UPDATE: I've been able to fix the parenthesis error. However, Is my code look right? there is 3 columns in the file i'm reading and I want to average each column and take the std.The code compiles now, but nothing is being printed.
Comment: Sorry, but my knowledge of FORTRAN dates back to more than 30 years ago. I'm not going to try to debug your code just by looking at it. I will say that if it is printing nothing at all, no error message and not the words 'mean:' and 'std deviation:', then my best guess is that it's never getting out of one of you loops, so that's where I'd focus my attention if I were you.
Answer: Since this is likely a course I will help you how to debug.
Basically start with some write statements... Check your answers...
program cardata
implicit none

...
read(10,*) N
WRITE(*,*)' I read N as ',N

WRITE(*,*)'XBar starts as ', Xbar
do I=1,N
...
! was XBAr ever set to start at 0!
xbar= xbar +x(I)
...

WRITE(*,*)'Syd starts as ',Std
DO I =1,N
  std =std +((x(I) -xbar))**2
enddo
WRITE(*,*)'Std starts is now ',Std,' and n =',N
! What do we do if N=1 or is Std is negative?
WRITE(*,*)'SQRT(Std)=', SQRT(Std)
std = SQRT((std / (N - 1)))
...

At some point You will determine that X is a column, and it is the first column. What is the second column? Y?
Comment: How is it connected with the question about the error message? I mean, you can just say that the parentheses are unbalanced in a sentence and then you can add whatever you want and no-one can complain. I will also not complain at all. One sentence is enough. **But you really should first answer the original question.**
Comment: It is because this is not a discussion forum where you can give any well-meant advice, but it is primarily 1. a question -> 2. answer to the question. And then you can add your advice, no problem at all.
Comment: @VladimirF Question about the error message? The last question was why the results were zero and why only 1 column... Let him see the value of nand then we will know if the answer has value... The question of "what is wrong with my code" in some cases has multiple answers. For the student the answer may be that they need some method To find the problems. His last question from yesterday was about the columns. Maybe he needs the question out of the comments?
Comment: It is just one sentence. "You are missing one parenthesis and that's why it prints the error message you ask about." I really wasn't asking for anything more. Note that if a queation allows many different answers it can be closed as too broad. The point of StackOverflow is that it is simply question -> answer. And one (only one) gets accepted by the asker. Not a discussion about various aspects.
Comment: I think the fact that this question is about the `Unclassifiable statement` message is quite clear.


Is this the Crudy anti pattern?

Question: Currently I am creating a WCF service which has to connect to a DAL which, just connects to a database using ADO.net and stored procedures.
The DAl writes its responses from the database to a datacontract which is passed over the wire to the client via the service.
I was reading that this may possibly be the anti pattern 'CRudy Interface', but I wasn't sure as I am sharing the datacontract.
If I am using an anti pattern, can anyone suggest a better pattern to use for the behavior I require?
Answer: Well, there seems to be some controversy about the CRUDy pattern and it's pros and cons. At a minimum, I would call a service interface that makes you write this kind of code to use it an anti-pattern (as commented here):
<code>service.CreateCustomer(c);

foreach(Group group in c.Groups)

  service.AddCustomerToGroup(c.CustomerId, group.GroupId);

foreach(Person person in c.Contacts)

  service.AddCustomerContact(c.CustomerId, person);
</code>
Is exposing CRUDy interfaces bad in itself? I wouldn't say so. What's important is to provide an interface which will

encapsulate knowledge about the underlying processes
not be very chatty
Comment: The danger of a CRUD interface is that it encourages multiple calls. For example, for processing an Order there could be both an InsertOrder and InsertOrderLine method - two interface calls. This is in contrast to using one well-defined interface method to process the whole transaction.
Comment: The problem with the CRUD interface is that it will generally result in breaking the 2nd rule because multiple calls have to be made to do anything remotely complex - it will be "chatty".
Comment: I imagine those two methods would share logic. What kind of interface would you expose to support the "place an order" use case?
Comment: For a start I would have just one method that processes an order, the "four tenets of service orientation" in the paper I reference are a good check-list.
Comment: Hmmm...I think the vagueness of term "CRUDy" is what makes it a controversial subject. I (maybe mistakenly) thought about insertOrder() as a CRUDy concept even though if I were to implement it, it would handle order line insertion as well, along with everything else that happens when a new order is placed. In any case, I've bookmarked the paper you linked to for more detailed reading. :)
Answer: It does seem like the CRUD interface anti-pattern, but it would be good to see some interface examples to confirm.
This paper has a really good discussion on designing better service interfaces.
It includes a critique on, and alternative to, the CRUD anti-pattern.
Answer: If you have a cruddy use case to implement you will get a cruddy interface, don't sweat it. The anti-pattern is when you implement non-cruddy things in a cruddy way.

Is this the Crudy anti pattern?


Opposite parametrization of closed plane curve

Question: This may be trivial but I cannot fully wrap my head around it:
Suppose we have a simple closed regular differentiable plane curve $\alpha : \mathbb{R}\rightarrow \mathbb{R}^2$ parametrized in arc length. Moreover suppose that is it positively oriented (the normal vector always point to the interior of the curve) then define $\beta(s):=\alpha(-s)$ show that it is negatively oriented (and v.v. of course). My issue is that while taking derivatives I get lost in changing signs, thanks in advance for the help.
Answer: (1) If you define the normal as the derivative of $\frac{\alpha'(s)}{\|\alpha'(s)\|}$, as you suggest in your question, then the statement is not correct. The fact that the normal vector points inwards doesn't tell anything about how you walk through the curve (counterclockwise or clockwise).
Example:
$$ \begin{align*}
\alpha_1(s) &= \left( \cos (s),\sin(s)\right) \\
\alpha_2(s) &= \left( \cos (-s),\sin(-s)\right)
\end{align*}
$$
Taking the second derivatives gives the normal vectors. In both cases, the normal vectors point inwards. However, $\alpha_1$ parametrises the circle counterclockwise; $\alpha_2$ clockwise.
(2) However, for plane curves one often defines the normal as $N=JT$, where $J$ stands for "rotating the vector 90 degrees counterclockwise". In this case, the statement is true (just use the right hand rule).
Comment: I think I know what the confusion is all about! Let me add it in the answer.
Comment: Thank you! This one example came to my mind and is the one that made me ask this question here. What do you think is the misunderstanding ? Can my question be made correct?
Comment: Well, the misunderstanding is that your "definition" of positive orientation isn't right. We found a counterexample, so the question cannot be made correct.
Comment: The point of the exercise is to show that "any curve can be positively oriented" so if we have a negatively oriented curve we can just put the minus in the argument and we're done.
Comment: I see. As your question is written now, I interpreted that you regarded "positive orientation" as defined by "normal vectors pointing inwards". But nevertheless, indeed, you just need to change $s$ into $-s$.
Comment: Yes this is my definition, so is this correct? How do I show that?


If piano tablature is easier to read than traditional sheet music

Question: I am familiar with guitar tabs which are much easier to learn and read than sheet music. Mainly because it is a direct mapping from the notation to the guitar frets; you don't have to do any translation really. The strings are displayed on the tablature, and the numbers indicate the fret position. Sheet music, on the other hand, requires you to memorize a system and then translate that system to the guitar's fret board. However, once you learn it I guess you could more easily transfer the skill to other instruments.
I am wondering if tablature is likewise easy for the piano. I have just encountered it so haven't learned it yet, but I wanted to see if it was easier to use than sheet music like the guitar. I can't really imagine how it would work, because you probably don't think of the keys as numbers 1-88, and maybe it's possible to hit more than 10 notes at a time, so it's not mapped to your fingers. But yeah I will need to learn it better, but wanted to ask first if it was useful and/or easier than sheet music for piano.
Comment: I think the closest thing to what you're looking for is "lead sheet symbols" or "chord symbols".
Comment: Any notation is easy to read after you've used it enough.
Comment: @CarlWitthoft That is just not true. There are a lot of conceivable notations that would never, ever get *easy* to use no matter how long you train, because they intrinsically impose cognitive work on you that can't be abbreviated. We never see the worst systems because they're so bad that they don't survive, but that doesn't mean all existing methods are equivalent. E.g., current notation makes no distinction between minor and major seconds, and as a result they're harder to tell apart than it has to be - remembering accidentals and doing the math will never be as easy as observing distances.
Comment: @KilianFoth ok, but that's kind of the pathological case.
Answer: There are 3 major downsides I can think of when using this type of music writing:

There aren't many songs written in this notation for piano.
Completely lacks notes durations (this is where it gets a lot simpler than traditional).
Unlike guitar, it gets more complex to read when mixing different notes or rythms with each hand.

It might be simpler to learn but particularly for piano I believe it's very limited. Learning the traditional way it's hard and will take longer but will give you a very solid base not just for piano but for western music in general.
However, it's true that many people that don't want to be professional or proficient in music (myself included) don't want to spend this much time learning. Unfortunately there is no "easy sheet" for piano (there are fakebooks, but still require some knowledge) as its nature gives the possibility of multiple notes and rythms at the same time, unlike most other instruments.
Answer: Just my thoughts: tablature is easier for guitar mainly because the guitar has multiple string/ fret combinations for each note. Translating from the note in the sheet music to these combinations and then deciding on the fly which one is easiest to play is the tricky part, and the person writing the tab has figured out one solution for you.
On a piano, you have a 1-1 mapping between the notes and the keys, and with a little practice translating between the sheet music and the keys is not much harder than translating from tablature to the keys, and the geometric arrangement of the notes conveys whether you're moving up or down without having to parse each symbol. Flats and sharps make things a bit harder, but that's manageable. One tricky aspect of playing piano is deciding which finger to use for what key, and tablature doesn't help you with that either.
Besides, the tablature example that you linked to has a lot of problems:

glossing over the difference between flats and sharps makes no sense in terms of music theory. Referring to the "b flat" in the F scale as an "a sharp" feels just wrong to me - the note replaces the unmodified "b", not the "a".
as EzLo has pointed out, note durations and rhythms become tricky to write. Many guitar tabs are sloppy in that respect, and expect you to listen to the piece and figure things out on your own, whereas piano scores are usually meant to convey how to play the piece without having access to a recording.
with chords, you need to read each individual letter. With sheet music, an experienced pianist sees the shape of the notes stacked on top of each other and knows "Ah! Triad, root position" and only needs to figure out the root note. Maybe it's possible to get the same speed with tablature eventually, but I'm not sure.
Answer: Standard note systems are sort-of tabs for pianos.  You get one note space per key, with the default notes (without sharps or flats) corresponding to white keys.  The usage of both sharps and flats (and even double sharps and flats) is important since it makes scale positions correspond directly to note placement which simplifies the planning of fingerings: three positions further implies three fingers (possibly requiring wraparound) further as long as no non-scale notes interfere.
As someone who switched from piano accordion to chromatic button accordion (which has a uniform layout of semitones, greatly facilitating transposition and playing by ear), it's been quite a nuisance to lose that direct mapping of a standard score to the keyboard, particularly when polyphonic material is involved.  Sight reading really is the one thing that suffers.
Answer: One important feature of traditional notation is that it is portable across keys (one can transpose) and it is transportable across instruments. Knowing guitar tablature isn't that helping in playing lute tablature or playing organ tablature.
Answer: I'll go to an extent that tab makes it easier to play stuff on guitars. There's good and there's bad. The timing on good tab is real notation - so learning and playing that, you're half way to playing real music! Without the timing, the notes can be played with whatever timing the player thinks - hardly playing what the original sounded like. Also, tab shows where the writer thinks it would be played. Any number of students question why there, why not here, where it's easier, more effective, sounds better, etc.
Your statement that it's easily transferrable to other instruments? Which ones? And how?
'Tab' for piano does work, and maybe it's more accurate, because one note can only be found in one location. But for me the bottom line (and this goes for tab on guitar/bass too) is that with the extra bit of effort, you've armed yourself with a totally transferrable skill, if you learn what the tadpoles on the washing lines is all about. Heck, it's even transferrable to drums and percussion. Bonuses are always good to have, and being able to understand 'proper' sheet music is a heck of a bonus for that extra mile of travel. 'Painting by numbers' came to mind while this was being read.
The piano tab I came across on Wiki doesn't do a lot for music. Only sharps (capital letters)? That's plainly wrong. Just like so many guitar sites that eschew the use of flats! O.k, with piano the limitations are down to lower case and caps, but it's inaccurate, and frankly, somewhat Mickey Mouse. Downvoters - please quote that...


Bypassing a custom login page

Question: I am demoing a web-application soon and would like to make the flow of my demo a little cleaner.
At the moment, when one clicks on a page, they get redirected to the login for this webpage. I'd like to do away with login page this for my demo.
Let's, as an example, take https://home.bt.com/login/loginform.
I want to add a link to my webpage which will, in the background, log me in as BT ID "User1" with password "securityDoesntMatterForDemos". This can all be hardcoded. The user should only see the webpage navigating them to the members area for this user (whatever page would be produced after an accepted login on this page).
What is the best way of accomplishing this safely and reliably?
Answer: I think the best way to accomplish this would be to have a short and simple webpage that you initially route to that is hosted on your machine. This webpage will use client side code(javascript) to send a request to your server's webservices requesting your authentication token with that username and password, upon receiving it, reroute to your website and hand off the authentication token in the same manner that your login page achieves this, be it in a cookie, local storage, etc etc
This will hide your login credentials from the live version without you having to change how the live version works.

Bypassing a custom login page


Abrir um EditText quando um componente Switch é desligado

Question: Tenho um Adapter customizado que renderiza uma lista, nessa lista tem um switch que por padrão vem ligado e quando o usuário desliga, o sistema valida uma regra e se essa regra foi true, ele tem que mostrar um EditText para que o usuário justifique o porque do desligamento.
O problema é que eu não consigo fazer com que o EditText seja mostrado na tela, quando o switch é mostrado.
Adapter:
public class ListaFaltaProvaExameAdapter extends BaseAdapter implements ListAdapter {

    private Context context;
    private List<FaltaMo> faltaList;
    private List<FaltaMo> faltasList;
    private EditText editTextJustificativa;

    public ListaFaltaProvaExameAdapter(Context context, List<FaltaMo> faltaList) {
        this.context = context;
        this.faltaList = faltaList;
        this.faltasList = faltaList;
    }

    @Override
    public int getCount() {
        return faltaList.size();
    }
    @Override
    public Object getItem(int position) {
        return faltaList.get(position);
    }
    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        FaltaMo falta = faltaList.get(position);

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View view = inflater.inflate(R.layout.listview_faltas_prova_exame, null);

        TextView textCod = (TextView) view.findViewById(R.id.textCodigo);
        textCod.setText("Código: " + falta.getTipoFalta().getCodigo());

        TextView textFalta = (TextView) view.findViewById(R.id.textFalta);
        textFalta.setText(falta.getTipoFalta().getDescricao());

        TextView textHorarioRegistro = (TextView) view.findViewById(R.id.textHorario);
        textHorarioRegistro.setText("Horário: " + Util.getFormatedStringFromEpoch2000(falta.getRegistro()));

        final FaltaMo faltaAtual = faltaList.get(position); //Pega a falta atual

        Switch mySwitch = (Switch) view.findViewById(R.id.switch1);
        mySwitch.setVisibility(View.VISIBLE);
        mySwitch.setChecked(true);

        editTextJustificativa = (EditText) view.findViewById(R.id.editTextJustificativa);

        mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!isChecked) {
                    faltasList.remove(faltaAtual);
                    faltaAtual.setValidada(false);
                    faltasList.add(faltaAtual);
                    if (faltaAtual.getTipoFalta().isJustificativa()) {
                        editTextJustificativa.setVisibility(view.VISIBLE);
                    }
                }
            }
        });
        return view;
    }

    public List<FaltaMo> getListaFaltas(){
        return faltasList;
    }}
}

Layout XML:
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="600sp"
    android:padding="5dp">

    <TextView
        style="?android:textAppearanceLarge"
        android:id="@+id/textCodigo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:textSize="15sp"
        android:textColor="#000000"
        android:paddingLeft="5dp"/>

    <TextView
        style="?android:textAppearanceLarge"
        android:id="@+id/textFalta"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textCodigo"
        android:text=""
        android:textColor="#000000"
        android:paddingLeft="5dp"/>

    <TextView
        style="?android:textAppearanceLarge"
        android:id="@+id/textHorario"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textFalta"
        android:text=""
        android:textColor="#000000"
        android:paddingLeft="5dp"/>

    <Button
        style="?android:textAppearanceListItem"
        android:id="@+id/btFinalizar"
        android:layout_width="130dp"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:text="@string/btFinalizar"
        android:textStyle="bold"
        android:visibility="invisible"
        />

    <ListView
        android:paddingTop="0dp"
        android:layout_width="1200sp"
        android:layout_height="wrap_content"
        android:id="@+id/listViewFaltasProvaExame"
        android:layout_alignParentStart="false" />

    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:visibility="invisible"
        android:id="@+id/switch1"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:paddingTop="5dp"/>

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:id="@+id/editTextJustificativa"
        android:textSize="20sp"
        android:hint="Digite aqui a justificativa"
        android:width="400dp"
        android:visibility="invisible"
        android:layout_alignEnd="@+id/textCodigo"/>
</RelativeLayout>
}

Activity:
   public class ActListaFaltasProvaExame extends Activity{

    private ProvaMo prova;
    private List<FaltaMo> listaFaltas;
    private ListaFaltaProvaExameAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try{
            super.onCreate(savedInstanceState);
            recuperarSessao();
            verificaConteudoListaFaltas();
            setContentView(R.layout.listview_faltas_prova_exame);
            ListView lView = (ListView)findViewById(R.id.listViewFaltasProvaExame);
            adapter = retornaAdapterPopuladoComListaDeFaltas();
            View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                    .inflate(R.layout.footer_layout, null, false);
            lView.addFooterView(footerView);
            lView.setAdapter(adapter);

            final EditText observacao = (EditText) lView.findViewById(R.id.editTextObservacao);
            Button btFinalizar = (Button) lView.findViewById(R.id.btConfirmar);
            btFinalizar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    insereFaltasNaBase(adapter.getListaFaltas());
                    prova.setFim(Util.getDataHoraAtualEmEpoch2000());
                    Logger.writeLog("Observação do examinador: " + observacao.getText().toString());
                    Logger.writeLog("## Prova Finalizada ##");
                    insereObservacaoNaProva(observacao.getText().toString());
                    openCandidatosActivity();
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }

Answer: Tenta pegar o clique do Swich e verificar se está ativo se estiver não faz nada e for desativado mostra o EditText, mas acho que você já esta fazendo assim.
Exemplo:
Switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {

                if (isChecked) {

                } else {
                    EditText.setVisibility(VISIBLE);

                }

            }
        });


Arithmetic overflow error converting varchar to data type numeric. when trying to read from a database DOES NOT happen every time

Question: I'm trying to read in from a local database and create and return an object. my code works fine the first 3 times through the loop that calls it and then fails giving me an error: Arithmetic overflow error converting varchar to data type numeric. I've done plenty of debugging and the error is being thrown at reader.Read(). To my knowledge I'm not converting anything there, and all my research has turned up completely different sources for this error. any help would be greatly appreciated.
System.Data.SqlClient.SqlDataReader reader;
/*Initialize Variables*/
        using (SqlCommand cmd = GetCommand("SELECT * FROM tblInventoryItem where InvoiceID = " + InvoiceNumber))
        {
            //Do Work...
            try
            {
                cmd.Connection.Open();
                reader = cmd.ExecuteReader();

                InventoryItem i;
                NItem ni;
                InventoryDataRepository2 idr = new InventoryDataRepository2();

                while (reader.Read())
                {
                    //Create an instance of the object....
                    i = new InventoryItem();
                    ni = new NItem();

                    ni.ItemNumber = (string)reader["ItemNumber"];
                    InventoryItem invitem = (InventoryItem)idr.GetItem(ni.ItemNumber);
                    ni.Title = invitem.Item.Title;
                    ni.Model = invitem.Item.Model;
                    ni.RetailPrice = invitem.Item.RetailPrice;
                    ni.WholesalePrice = invitem.Item.WholesalePrice;
                    i.Item = ni;
                    i.Quantity = Convert.ToInt32(reader["Quantity"]);

                    allItems.Add(i);
                }

EDIT: stacktrace:
 at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
 at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
 at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
 at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
 at System.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean& moreRows)
 at System.Data.SqlClient.SqlDataReader.TryReadInternal(Boolean setTimeout, Boolean& more)
 at System.Data.SqlClient.SqlDataReader.Read()
 at NeweggDistributor.InventoryItemDataRepository.GetAllItemsInInvoice(String InvoiceNumber) in c:\Users\AJ\Documents\Visual Studio 2012\Projects\NeweggDistributor\NeweggDistributor\InventoryItemDataRepository.cs:line 90
 Arithmetic overflow error converting varchar to data type numeric.

Comment: Reader.Read() will not throw that error.  Perhaps you are debugging optimized code?  What is the stack trace when this exception is thrown?
Comment: Side note; the use of abbreviations all over the place makes the code a lot harder to read.  Thanks to code completion in the IDE, you don't actually need to type out full variable names, so it's not really more typing, but it results in much more readable code.  Also, there's no real reason to declare variables outside of a loop when they're only used inside the loop.  It opens up possible mistakes if you forget to (re-)initialize them, pollutes intellisense outside of the loop, and gives the reader the impression they may be used outside of the loop.
Comment: what is the type of InvoiceId and InvoiceNumber?
Answer: I agree with Eric J. i don't believe Reader.Read() would throw such an error. What i see is likely to throw such an error tho is if the Quantity field in the DB is a string and cannot be converted to an integer, or if it is null in the DB because null cannot be converted to any integer. other possibilities are the RetailPrice and WholesalePrice fields. Perhaps you can comment out those lines and make sure you don't get the same error when they are commented out. then you can uncomment each field one at a time, testing that each field one new field at a time.
My first guess is that i.Quantity = Convert.ToInt32(reader["Quantity"]); is trying to convert a varchar field into an int and the varchar string is not numeric. I hardly ever use Convert.ToInt32 or C# casting for situations like this because they can throw unexpected nasty errors. I create a separate method that converts what i want, and i pass it a default value that is returned if the conversion cannot be performed. Thus i use a 'defaultValue' parameter in my conversion methods.
Answer: Your query is
SELECT *
FROM tblInventoryItem
WHERE InvoiceID = 1234

My guess is that InvoiceID in the database is a varchar field.
This means that you are comparing an integer with a varchar in the where clause. Implicit conversions changes your query to
SELECT *
FROM tblInventoryItem
WHERE CONVERT(int, InvoiceID) = 1234

You will get an error if any InvoiceID in the database contains something which will not fit into an integer.
The arithmetic overflow error make the most probable cause an invoiceid > 2147483648
Note that the error will not happen if your InvoiceNumber is also to big for an integer.
SELECT *
FROM tblInventoryItem
WHERE InvoiceID = 5000000000

will work because it is changed to
SELECT *
FROM tblInventoryItem
WHERE CONVERT(bigint, InvoiceID) = 5000000000

The solution is of course to use parameters
command.CommandText = @"SELECT * " +
                      @"FROM tblInventoryItem " +
                      @"WHERE InvoiceID = @InvoiceNumber";
command.Parameters.Add("@InvoiceNumber", SqlDbType.VarChar).Value = InvoiceNumber;

(You can also use a parameter of type SqlDbtype.BigInt if you are sure InvoiceID only contain numbers)


Is it possible using Spring MVC + PrimeFaces?

Question: I want to know if it is possible and how to use Spring MVC with PrimeFaces.
Comment: https://stormpath.com/blog/tutorial-spring-web-mvc-primefaces
Answer: After 3 days of research I just don't think it's possible out of the box. Spring MVC with JSF exactly - Web Flow is something else. Spring Roo straight up makes you choose whether you're going to have Spring MVC or JSF.
None of the examples supposedly integrating both would work for me on latest library releases using Jetty. At this point I wouldn't be totally surprised that some of them do actually work with other containers as I did get varying results trying out a couple with Tomcat. Most examples do the same thing without explaining much - they do use the Spring MVC dispatcher servlet and declare the faces servlet separately as well and how it's supposed to work is all a mystery especially when it doesn't work.
I'm new to all this, but to me the desired thing would be for the Spring dispatcher just handle JSF2 out of the box, JSF2 has been out for a while yet I can't google up anybody trying to do that or even expressing the same sentiment; is there something inherently wrong with what I'm thinking?
Answer: The technology stack you are trying to build is certainly possible (as per the link below)
I'm trying to do something similar. The technology stack I am trying to build is JSF2+Primefaces3.5+springMVC3+hibernate+MySQL on Tomcat 7 using Eclipse Juno.
I found this from google..
http://www.javacodegeeks.com/2012/04/jsf-2-primefaces-3-spring-3-hibernate-4.html
This link is what I've been trying to follow. So far, I've gotten my webapp to run on primefaces+JSF+tomcat running. I've created my own models and controllers. But I'd like to have them done through Spring MVC. This, I am currently trying to set up.
I hope it helps you move forward.
Answer: You can do this by using MangedBean instead of @Controller and other components of Springframework like @Service @Repository . It will work in this way. I hope this will help you
Comment: This rather sounds like a comment than an answer ... consider adding some more, real content.
Comment: Not correct, that is spring and primefaces, not spring mvc and primefaces
Answer: http://www.springfuse.com/. They have a mvn pom that will reverse engineer your DB schema and produce all your boiler plate code for a persistence app based on your JSF2+Primefaces3.5+springMVC3+hibernate+MySQL tech stack


How do I identify chord scales? (Chord scale theory)

Question: I'm confused with how to identify chord scales because there are a lot of modes and combinations I have to consider. For example, Cmaj is C Ionian, and C13 is C Mixolydian, etc., right? Basically there's a whole chart with these modes and their corresponding chords. And it's very specific. But what about chords like G7#9#5? What chord scale is that? Or E7#9? That can't be mixolydian right?? What about Dm7b5? Or C9? Or Db9#11??
I just wish there was a chart that has a complete list of all these specific chords because I'm genuinely confused.
Comment: See some typical chord scale associations in Aebersold's handbook, p. 14 https://www.jazzbooks.com/mm5/merchant.mvc?Screen=FQBK But these are just some guidelines, and they may not even work well at all, depending on the preceding or the following chord(s), or on the notes in the original melody of the song. Courses of jazz harmony often devote quite some time to consider how various scales fit in various situations.
Comment: Are you assuming there is a one to one chord/scale match? That for example `C` ionian is the only scale to play for `Cmaj`?
Comment: Maybe you can make yourself a chart, building up more options as you need them?
Comment: Are you approaching this from a big chord chart, or perhaps a complete fake book, and want to know the associated scales? Or are you working from selected lead sheets with a lot of altered/uncommon chord types?
Answer: The idea behind chord-scales is that given a chord there is a scale that contains the chord tones, plus pitches that fill in the "gaps" between chord tones.
Given a Cmaj chord, a C major scale contains all of the chord tones (C E G) plus adds notes in between (D F A-B).
This is usual taught in a simplified manner: Cmaj (or Cmaj7) = C major scale. But the simplification can be misleading. Think of the scale as adding passing tones between the chord tones. At that level, the scale could be anything containing the chord tones. For Cmaj, we might have C D E F# G A B. That scale uses an F# "passing tone" between E and G rather than F. The F# works well if, for example, the larger context of the Cmaj chord is within the key of G major.
At the introductory level chord-scales just cover the unaltered triads and seventh chords. But one can construct scales for altered chords as well. Take the example of G7#9#5. The chord contains G B D F A# D#. For convenience, respell D# as Eb, then put the notes in scale order: G A# B D Eb F. The only gap — missing letter name — is between B and D. The gap could be filled with either C or C# according to taste or musical context.
Comment: The way I see it a G7#9#5 does not contain a D, #5 replaces the D with a D#. A G7#9b13 would technically have a D.
Comment: Isn't a manor a gang's area?! Maybe manner?
Comment: @Tim No, no. The theory is usually taught in a "simplified manor", such as a one-room schoolhouse or, less simplified, a craftsman bungalow. (Fixed now. Thanks for catching.)
Comment: @JohnBelzaguy Yeah, I swept that under the rug thinking it would complicate the larger point.
Comment: "But the simplification can be misleading." Yes.
Answer: I haven't had to study the chord scale theory (for which I am very greatful), but this is how I understand that the concept has to be, in order to make any sense.
You don't have to know a proper name for a scale, names are needed for talking, not for playing. And you don't have to know all scales in the world, you can make them up as you go. If a given chord only explicates three notes, you are free to choose the other four. If you can come up with any set of seven different note names that includes the written chord's tones, it should be enough. In a theory exam you might be asked to give a name for your scale.
Start from the given chord like C major and keep adding notes until you have seven pitches, according to your own personal taste, preferences, skills, imagination. Then over the written C major chord, you can play notes and chords from the scale.
For example, if you built a C Lydian scale over the C major chord, you can play alternating interleaved triads: C major, D major, C major, D major ... this technique is called "triad pairs". But like I said, you don't have to think "C Lydian" first, or at all. You can think "I have C, E and G here - what other notes would I like to have?"
Learning to answer the "what other notes would I like to have" question is what you should practice. Learn the characteristics of the different options by trying them out in songs. Do you want a Bb or a B natural to go with your C major chord? Do you know what consequences that decision has? Do you feel the differences? Try it! You build skills by practicing and trying things out, gradually, one little thing at a time. Not by memorizing huge pre-filled scale charts.
Comment: Yes, this is exactly it. While memorising a few of the more common chord spellings and what scales they generally suggest can be useful to start with the aim is to be able to swiftly see what important chord tones you have to include and spontaneously building a scale around it that satisfies. The scale you end up with may be familiar or unusual, but it doesn't matter. In finding your way through a modal chord sequence you may find that on subsequent cycles round a chord sequence you may find one path suggests a particular scale, and another path a different one. As ever, it's about context.
Answer: The other answers have captured the essence of the process very well, so I'll try not to repeat. In the earlier stages you are more likely come come across chords such as you have asked about and they may have some more common, 'first look' scales that apply. I'll just address those you have mentioned here -
G7#9#5 - This is an altered dominant chord, it's close to a dominant chord suggesting a diminished scale. One diminished scale, the whole/half, doesn't have a major 3rd, so doesn't fit. The common diminished scale that fits over a dominant chord is the half/whole diminished scale. However, this scale doesn't have a #5, so the chord spelling can't be suggesting that. The commonly used scale for this chord is the 7th mode of the melodic minor scale, the Altered scale. It is spelled 1, b2(b9), b3(#9), 3, b5, #5, b7. I've renamed the intervals to reflect how it is commonly though of, strictly though the scale is spelled 1, b2, b3, b4, b5, b6, b7.
E7#9 - Without the 5th being specified as sharp or flat you are a bit more free, and the common choices are again the altered scale or the half/whole diminished scale. This involves altering the 5th but it's not that strong a tone in this idiom and can generally be pushed or pulled where necessary.
Dm7b5 - Is usually seen as the ii in a minor ii V i. It is generally played as the Locrian scale. Commonly however a player may use the 6th mode of the melodic minor, the Locrian nat2 scale. This scale is spelled 1, 2, b3, 4, b5, b6, b7. If this scale choice works it can sound really good, but if the natural 2 sounds awkward then the standard Locrian scale should work fine.
C9 - By default is Mixolydian.
Db9#11 - Is a Lydian dominant chord, the 4th mode of the melodic minor scale, it's scale is spelled 1, 2, 3, #4, 5, 6, b7.
All the above are 'defaults' for playing jazz in this idiom, play around with them and see what you get, but they are far from strict rules. It's up to you to choose the scales you like the sound of, and the magic little shifts of harmony, or feel, that you hear the greats make (in this idiom, think Herbie, Shorter etc.) are often when they pick one scale the first time around, then pick another the second. Or even create some tension in a minor ii V i by playing Locrian nat2 at first, settling it down to plain Locrian then moving on, or vice versa.
You can play any scale over each chord, aiming to satisfy the chord tones. Once you are comfortable with the 'defaults' suggested above then try different scales that satisfy the chord tones or even try scales that diverge from the chord tones somewhat. For example playing the D altered scale over D9 for a measure before running down in D Lydian dominant and then finishing off with the D7 chord tones, or a D mixolydian. These sideways shifts are the hallmark of the idiom and can make for very free improv, though it can be a little overwhelming at first.
There are some general starting points, the 1, 3, 5, 7 will tell you wether it's maj7, min7, dom7 or minMaj7. The upper extensions will narrow down the pool of available 'first choice' scales, and generally most alterations will be on dominant chords. On these a #5 indicates Altered Scale, a #4 indicates a Lydian Dominant scale and a #9 or b9 indicates half/whole diminished or altered. However this is not set-in-stone and a 7#5 chord may well work best simply as a Mixolydian with the 5th sharpened.
The chord spelling is usually suggesting roughly what the composer intended eg, E7#9#5 = Altered, E7#5 = Mixolydian with a sharp 5. However this can be heavily lost in translation with the realbook leadsheets, but that shouldn't be a major hinderance. To properly learn a jazz tune you should be taking into account what the melody is doing, what sounds best to you and how you have extended the previous and following chords, all in order to make your own decisions on what scale you will use. When you hear musicians seemingly leaving the written changes altogether but still sounding coherent they are essentially embarking on journeys encouraged at first by small alterations of the suggested chord/scale and then going from there (if we think of this as THIS, then think of that as THIS then we can get to a completely different key, coherently..)
In truth any chord sequence that lends itself to modal playing can be navigated in many many ways. A good one to start with is Havona by Weather Report. It's just 4 Major chords, all leaning toward Lydian, you can start by playing the Lydian scale on each, then see if the natural 4 works on any of them, then see if you can think of chord 2 as a mode of chord 1, then see if you can think of all of them as modes of each other with steps up or down. There is no right answer for this tune, like all modal playing, and it's a relatively easy playground on which to experiment.. (Just slow it down, at the original speed it's a little frantic!).
Answer:
...I just wish there was a chart that has a complete list of all these specific chords because I'm genuinely confused.

It's confusing because chord/scale charts - at least all the teaching material I have seen - don't put chords into a diatonic/key context, which is the context for many jazz phrases.
You will see charts giving examples like this:

CHORD   SCALE
min 7   dorian
(dom)7  mixolydian
maj7    ionian

What isn't explained is a common example of that is the ubiquitous ii V I progression, which in relation to a key might be C: iimin7 V7 Imaj7, where all three chords are covered by the major scale, in that example a C major scale.
I suggest first understanding common chords in a diatonic/key context and learn how the "scales" like dorian, mixolydian, ionian, etc. are just positions/rotations/modes of the prevailing key for the phrase. In other words don't always look at each and every chords change and match a scale, look for key changes and play in key.
Just like any other style, jazz will have chromatic chord progressions where the extended sense of key isn't at play. Some of those cases still involve two chord progressions that do fit into a diatonic/key context. You can treat those as above, as diatonic, but the passages are simply shorter, they last for only two chords. An example might be: A7 Dm G7 Cmaj7 where you want to recognize the two tonal centers A7 Dm in D minor and Dm G7 Cmaj7 in C major. Rather than thinking of four chord/scales, think of two tonal centers, two keys.
Sometimes there will be chromatic passages where all the chords are chromatic. One of the very common examples being all dominant seventh chords, ex. A7 D7 G7 Cmaj7. Again you can think of these in terms of keys, but the durations are shorter. Think of those dominant seventh chords as secondary dominants to implied diatonic chords. Harmonic analysis of that passage would still identify a key, like this C: V7/vi V7/V V7 I. If we literally put the implied chords in to the passage using parathesis, it would be A7 (Dm) D7 (G) G7 Cmaj7. So, play A7 as in key Dm, play D7 as in G major, play G7 Cmaj7 as in C major.
So far you can play all of those progression by simply playing in the appropriate major or minor keys. And it's understood that "playing in key" includes all the usual chromatic embellishing non-chord tones. No one should ever have the misunderstanding that "playing in key" means literally playing only the tones of a key signature. Even "classical" music does not do that.
To make the point emphatically, one more time, so far the only thing you need to identify is major and minor keys, not a long and confusing chord/scale chart.
Eventually you will get to altered chords whose tones do not fit neatly into major/minor keys. For these chords you can learn the associated special scales or just simply arpeggiate the chord tones. There are many ways to alter chords and it can become confusing. Keep in mind that chords with dominant function are the typical altered chords. Fully diminished seventh chords can be treated a similar way. Common scales to use for these chords are the altered scale, the diminished scales, and whole tone scale.
If you don't already know, the altered scale is the seventh mode of the melodic minor scale. Knowing that can help a lot to aid memorization and fingering. If you know how to play all the minor scales (and you should), then you already have the technique needed to play the altered scale.
This covers a huge amount of real world harmony.
It requires you to understand and play in:

understanding/identifying chords in context of keys
major keys
minor keys
altered scales
diminished scales
whole tone scales

...Or Db9#11??

This should get special attention. When you see a #11 or I suppose a #4, it's basically conveying in some sense of lydian. That sort of works against the diatonic/key approach. You will see it less in early jazz styles. Rather than taking the diatonic/key approach the lydian dominant scale is the thing to use. Yikes! yet another "scale". One way to not get overwhelmed by this scale is to recognize it as the fourth mode of the melodic minor scale. So, that's two "scales" you "already know" - the altered scale and the lydian dominant scale - if you already know your minor scales.


Python: Creating and writing to a file error

Question: I am having trouble creating and writing to a text file in Python. I am running Python 3.5.1 and have the following code to try and create and write to a file:
from os import *
custom_path = "MyDirectory/"
if not path.exists(custom_path)
    mkdir(custom_path)
text_path = custom_path + "MyTextFile.txt"
text_file = open(text_path, "w")
text_file.write("my text")

But I get a TypeError saying an integer is required (got type str) at the line text_file = open(text_path, "w").
I don't know what I'm doing wrong as my code is just about identical to that of several tutorial sites showing how to create and write to files.
Also, does the above code create the text file if it doesn't exist, and if not how do I create it?
Comment: You can find the reply you need here http://stackoverflow.com/a/1046674/5179092
Answer: Please don't import everything from os module:
from os import path, mkdir
custom_path = "MyDirectory/"
if not path.exists(custom_path):
    mkdir(custom_path)
text_path = custom_path + "MyTextFile.txt"
text_file = open(text_path, 'w')
text_file.write("my text")

Because there also a "open" method in os module which will overwrite the native file "open" method.
Comment: Ah that makes sense. Thank you


href not working after redirect

Question: I have the following navigation buttons in the main project folder which correctly navigate to each of the pages
analysis.aspx:

Home

Analysis

Blog

Contact

When a user logs in correctly, the analysis.aspx should redirect to a similar version in say the admin folder
analysis.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
    if (Page.User.IsInRole("admin"))
    {
        //Admin
        Response.Redirect("/admin/analysis.aspx");
        //base.OnLoad(e);
    }
    else if (Page.User.IsInRole("member"))
    {
        //Members
    }
    else if (Page.User.IsInRole("trial"))
    {
        //Trial
    }
    Else
    {
        //Keep Out

    }
}

This is working fine. However, after the redirect to the admin/analyis.aspx page none of the links work. The page appears to refresh but stays on the same page. I've tried to link to pages in both the base project folder and the admin folder without success, so far I've tried without success. There are 2 home.aspx pages, one in project folder and one in admin.
admin/analysis.aspx.cs:

Home

Home

Home

Home

The address bar shows the following after clicking http://localhost:6246/admin/analysis.aspx?ReturnUrl=%2fadmin%2fhome.aspx
Any ideas what I'm doing wrong?
Comment: I guess, `analysis.aspx` page requires authentication which fails and that's why it is occurring.
Comment: I'm redirecting to analysis.apx fine though, I can't navigate back off it?
Comment: sorry, my mistake to understand :(
Answer: If I see your codes it seems you haven't put runat="sever" property on the href. If you want to using ~ as root sign on the asp.net then you need to add runat="server" property, that way will let .NET framework compile the object as an asp.net object.
try this

Home

Home

Home

Home

Let me know if it solve your issue
Comment: Yes that's it. runat="server" seems to be the answer to all of my problems. Thank you.

href not working after redirect


Is it always true? $\left|A-B\right| \le \left|A\right| + \left|B\right|$

Question: Is it always right to claim that:
$$\left|A - B\right| \le \left|A\right| + \left|B\right|$$
where $A, B \in \mathbb{R}$ ?
Comment: If you prove it for $A>B$ & then $A<B$, you can reach a conclusion.
Comment: Or if you prove it just for $ A \geq B $ as there is no loss of generality.
Answer: Yes.
$$|A-B|=|A+(-B)|\le|A|+|-B|=|A|+|B|.$$
Answer: Hint:
Consider the cases where both $A$ and $B$ are either negative or positive (you should get an inequality)
Consider then the cases where one of them is negative and the other positive (you should get an equality)
(The cases where one or both are zero are trivial)
Comment: You don't get equality when $A = 2, B = 1$ (clearly both positive!)
Comment: @amWhy Sorry, my bad. The equality is when they have different sign and the inequality is when they have the same one. I'll edit that.
Comment: Exactly, Darth! ;-)
Answer: Triangle inequality in one-dimension.


Is it safe to use up all memory on linux server, not leaving anything for the cache?

Question: I have a CentOS server fully dedicated to MySQL 5.5 (with innodb tables mostly). Server has 32 GB RAM, SSD disks, and avarage memory usage looks like this:

So about 25GB is in use and about 6.5GB is cached. I am experiencing performance problems with WRITE queries, so I was thinking, is this the optimal cache size? I might increase innodb buffer size, so that linux cache would become smaller, or decrease it, so it would be bigger.
What is the optimal used/cached memory balance for busy MySQL server on linux?
Comment: "WRITE" queries? Do you mean INSERT and UPDATE statements?
Comment: @Michael Hampton, yes, inset, update, delete. See my other question here: http://stackoverflow.com/questions/12316122/
Comment: Have you heard of our sister site [Database Administrators](http://dba.stackexchange.com/)? They generally welcome questions regarding database performance tuning.
Answer: Cached memory exists to make use of unused memory to speed up requests. So if you give all your memory to an application that can make use for it, you will see a performance increase. So to answer your question, there is no such thing as an optimal balance.
Answer: In general I would allocate as much cache to MySQL as possible if you're worried about MySQL performance. It knows what to cache, whereas the operating system cache doesn't -- it just caches frequently accessed files.
Regarding your performance issues, you could try running the database off a RAM disk if that's possible. Otherwise, use a filesystem that can make use of cache devices.
Answer: To answer directly to the heading of your question: No, that would be a very bad idea.
If you assign all of the free memory, +/- a few MB, to a program exclusively, any other program that will use some of your systems memory (e.g. if you use find from time to time or cronjobs running daily, weekly and so on) will have to swap.
If your system is going to swap, you will notice a huge decrease in overall performance.
Comment: Considering his setup, it is reasonable to allocate a giant portion of his memory to this one application since the server is dedicated to this one task.
Comment: I agree fully to your comment (yet he asked if he could "use up all memory" for his mysqld).
However, he should keep in mind the memory requirements of other software running on his server.


Webview start always in desktop mode

Question: It's two days i can't start my webview directly in mobile mode. When i open the application for the first time starts the webview displays the desktop. My code
<code>@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS); // Request     progress circle
        setContentView(R.layout.main);
        webview = (WebView) findViewById(R.id.webview);
        WebSettings websettings = webview.getSettings();
        websettings.setJavaScriptEnabled(true);

        webview.getSettings().setUserAgentString("Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en)AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3");
        setProgressBarIndeterminateVisibility(true); // Show progress circle

        final Activity activity = this;

        webview.setWebChromeClient(new WebChromeClient(){

                public void onProgressChanged(WebView view, int progress) {
                    activity.setTitle("Loading...");
                    activity.setProgress(progress * 100);
                    if(progress == 100)
                        setProgressBarIndeterminateVisibility(false); // Hide progress circle when page loaded
                    activity.setTitle("Title");
                }
            });
        if (savedInstanceState == null)
        {
            webview.loadUrl("http://forum.ubuntu-it.org/");
        }

    }
</code>
Even if i changed the User Agent doesn't work! I tryied every way. I hope in a help from someone, Thanks.
Comment: does the forum have a mobile view alternative or does it have a mobile view ?
Comment: Yes, when i open the website with my phone on bottom of the page there is a "link" to change version to mobile view. Maybe the problem is this.. Maybe the website doesn't recognize the device automatically but you must change the version manually.. Strange..
Comment: did u notice any url changes after u selected the mobile view ?
Comment: edit: I tryied to enter with the stock browser.. the link says: `http://forum.ubuntu-it.org/?mobile=off` .This means that it recognize the device(the query string says `**mobile**=off`) but doesn't start automatically..i think the problem is from the website
Comment: i tried changing the url to `http://forum.ubuntu-it.org/?mobile=on` and the mobile view worked in chrome !!, So i'd advice you to try changing the url to the above.
Comment: yes, it works..But the problem is if i write:`webview.loadUrl("http://forum.ubuntu-it.org/?mobile=on");` The first page open in right mobile view but when i try to navigate inside the forum change again in desktop mode. Only the index page open in mobile version.
Comment: okay, i tried opening it with the mobile=on in my chrome and the website took me as browsing from a mobile device(even the subforums) until i changed the url to mobile=off.
Comment: this is strange..i mean, in web browser it works but in webview not..mmh
Answer: Add this line before loadUrl()
<code>webview.setWebViewClient(new WebViewClient());
</code>
Comment: Always desktop mode :( i can't belive in... really i tryied everything!!

Webview start always in desktop mode


Transformation does not work correctly

Question: Here is my code which rotates my object. I have to rotate two same type of objects.

initialization:

private TransformGroup trGrp;
        private RotateTransform trRot;
        private TransformGroup trGrp1;
        private RotateTransform trRot1;
        static private double angle;
        SerialPort port;
        value v;
        string result;
        public int zeroValue;
        public MainWindow()
        {
            InitializeComponent();
            angle = 0;
            zeroValue = 327;
            trGrp = new TransformGroup();
            trRot = new RotateTransform(angle) { CenterX = rectangle1.Width / 2, CenterY = rectangle1.Height };
            trGrp1 = new TransformGroup();
            trRot1 = new RotateTransform(angle) { CenterX = rectangle1.Width / 2, CenterY = rectangle1.Height };
           // trGrp.Children.Add(trRot);
            //trGrp1.Children.Add(trRot1);
            v = new value();
            port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
            port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
            port.Open();
        }

Code For serial port received data:

void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (!port.IsOpen)
            {
                port.Open();
            }

            try
            {
                result = port.ReadLine();
                result = result.Replace("\r", "");
            }

            catch (Exception e1)
            { MessageBox.Show(e1.Message); }
            int[] temp = new int[4];
            this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background,
        new Action(
          delegate()
          {

              try
              {

                      temp[0] = int.Parse(result[1].ToString() + result[2].ToString() + result[3].ToString() + result[4].ToString());

                      if (temp[0] == zeroValue)
                      {

                          trRot.Angle = 0;
                          trGrp.Children.Add(trRot);
                          rectangle1.RenderTransform = trGrp;
                          trGrp.Children.RemoveAt(0);//because Add function adds a new trGrp so its size increases and we do not need old trGrp so we remove them.
                          label3.Content = trRot.Angle.ToString();

                      }

                      else if (temp[0] > zeroValue)
                      {

                          int totalValues = temp[0] - zeroValue;
                          if (totalValues == 1)
                          {
                              totalValues = 0;
                          }
                          textBox3.Text = temp[0].ToString();
                          angle = totalValues * Properties.Settings.Default.angle;

                          if (angle<31)
                          {
                              trRot.Angle = angle / 2;
                              trGrp.Children.Add(trRot);
                              rectangle1.RenderTransform = trGrp;
                              //trGrp.Children.RemoveAt(1);//because Add function adds a new trGrp so its size increases and we do not need old trGrp so we remove them.
                              trGrp.Children.Remove(trRot);
                              label3.Content = angle.ToString();
                          }

                      }
                      else if (temp[0] < zeroValue)
                      {

                          int totalValues = zeroValue - temp[0];
                          if (totalValues==1)
                          {
                              totalValues = 0;
                          }
                          textBox3.Text = temp[0].ToString();
                          angle = -totalValues * Properties.Settings.Default.angle;

                          if (angle> -21)
                          {
                              trRot.Angle = angle / 2;
                          trGrp.Children.Add(trRot);
                          rectangle1.RenderTransform = trGrp;
                          trGrp.Children.Remove(trRot);//because Add function adds a new trGrp so its size increases and we do not need old trGrp so we remove them.
                          label3.Content = angle.ToString();
                          }

                      }

              }
              catch (Exception)
              { }
          }
      ));
            this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background,
        new Action(
          delegate()
          {

              try
              {
                  temp[1] = int.Parse(result[6].ToString() + result[7].ToString() + result[8].ToString() + result[9].ToString());
                  if (temp[1] == zeroValue)
                  {

                      trRot1.Angle = 0;
                      trGrp.Children.Add(trRot1);
                      rectangle2.RenderTransform = trGrp1;
                      trGrp1.Children.RemoveAt(1);//because Add function adds a new trGrp so its size increases and we do not need old trGrp so we remove them.
                      // textBox3.Text = trRot.Angle.ToString();
                      label4.Content = angle.ToString();

                  }

                  else if (temp[1] > zeroValue)
                  {

                      int totalValues = temp[1] - zeroValue;
                      if (totalValues == 1)
                      {
                          totalValues = 0;
                      }
                      angle = totalValues * Properties.Settings.Default.angle;
                      angle = Math.Round(angle, 0);
                      if (angle < 21)
                      {
                          trRot1.Angle = angle / 2;
                          trGrp1.Children.Add(trRot1);
                          rectangle2.RenderTransform = trGrp1;
                          trGrp1.Children.RemoveAt(0);//because Add function adds a new trGrp so its size increases and we do not need old trGrp so we remove them.
                          label4.Content = angle.ToString();
                      }
                  }
                  else if (temp[1] < zeroValue)
                  {

                      int totalValues = zeroValue - temp[1];
                      if (totalValues == 1)
                      {
                          totalValues = 0;
                      }
                      angle = -totalValues * Properties.Settings.Default.angle;

                      if (angle > -21)
                      {
                          trRot1.Angle = angle / 2;
                          trGrp1.Children.Add(trRot1);
                          rectangle2.RenderTransform = trGrp1;
                          trGrp1.Children.RemoveAt(0);//because Add function adds a new trGrp so its size increases and we do not need old trGrp so we remove them.
                          label4.Content = angle.ToString();
                      }

                  }
              }
              catch (Exception)
              {

              }
          }));

        }

I have used here two Dispatcher.BeginInvok' functions because i want to rotate both objects simultaneously. But the issue is that when i use only one object to rotate then no issue come. But when i include second one the first objects does not rotate correctly according to the angle i have mentioned in my program. What i understand that it is a problem that everytime event is fired transformGroup adds a new rotateTransform. So i tried to remove the added TrRot after addition. But this also does not work for me.
Thanks.
Comment: Why don't you just add the animations in XAML? Also, using `Dispatcher.Invoke` does *not* mean that your code will run in parallel... it just adds your requests onto the main UI thread queue, just the same as if you add two animations in XAML.
Comment: Would it be a different result? I had to write Event handler for Serial Port data received thats why i wrote it there.
Answer: You can add a simple Trigger to start your animations in XAML... let's say you add a bool property named IsReady. You could then trigger your animations to start when you set this to true and to stop when you set it to false. Add this Style to whichever objects contain the RotateTransform object that needs to be animated:

</Style>

Transformation does not work correctly


Display VAT price on products

Question: I have added a 20% vat on my products. This is added during checkout. How can I add it to the display price when you view the product?
Answer: I'm assuming you're using the VAT module. Ubercart's prices aren't flexible enough to adjust the display price based on the VAT. You should probably enter the prices for each product including the VAT and adjust your uc_vat so the sell price is inclusive.

Display VAT price on products


Do Neural Networks Always Need all 3 Initiating Rules for Neurons in Hidden Layers

Question: Did we always need the 3 rules quoted below in the end result for a neural network? Could 2 or just 1 make a formidable network? I am seeing that if all 3 rules were met by a network, the number of inputs > the number of neurons in the hidden layers > the number of outputs
3 initiating rules:

The number of hidden neurons should be between the size of the input layer and the size of the output layer.
The number of hidden neurons should be 2/3 the size of the input layer, plus the size of the output layer.
The number of hidden neurons should be less than twice the size of the input layer.

The 3 rules above are taken from an Introduction to Neural Networks for Java (second edition) by Jeff Heaton available as a Google Book.
Comment: This is very outdated advice, there's a million and one different neural networks architectures nowadays and I doubt any of them even thought about these rules. Best thing is just to experiment yourself though with keras or something and see what happens
Answer: No, these are just rules of thumb (dictionary definition: not intended to be strictly accurate or reliable for every situation) for designing a neural network. Quoting from the neural-nets FAQ,

These rules of thumb are nonsense because they ignore the number of training
  cases, the amount of noise in the targets, and the complexity of the
  function. Even if you restrict consideration to minimizing training error on
  data with lots of training cases and no noise, it is easy to construct
  counterexamples that disprove these rules of thumb.

You must experiment yourself with different number of hidden layers, and number of neurons in them pertaining to your problem statement. (A starting guide)
Take for example, autoencoders. A type of autoencoder, called undercomplete autoencoder, uses fewer hidden neurons compared to the input neurons. The sparse autoencoder include more hidden neurons than inputs, but only a small number of the hidden neurons are allowed to be active at once.


Show full screen Incoming Call Activity in Android

Question: In Android sometimes when we use an app and we receive a call , appears the full screen Incoming call activity

Instead if i create a new blank main activity and i put a simple BroadCast receiver, when im in the main activity and i receive a call this compares:

There is a way to show the full screen incoming call or just hide the incoming call popup notification ?
I searched a lot but i have not found anything...
MainActivity.java
<code>public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public static class PhoneStateReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {

        Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
    }
}
</code>
}
Answer: in android The system UI may choose to display a heads-up notification, instead of launching your full-screen intent, while the user is using the device. check it out Display time-sensitive notifications


How can I extract a sublist with the lowest integer value from a nested list?

Question: If I have a nested list as follows:
foods = [['Category', 'Carbs', 'Calories'], ['SWEET POTATO', '23.4', '100'], ['TOMATOES', '5.1', '23'], ['BEETS', '16.28', '65'], ['LETTUCE', '2.23', '13']]

I want to find and print the sublist with the lowest Calorie count. I have tried the following:
    lowcal = foods[0]
for x in foods:
    if x[2] < lowcal[2]:
        lowcal = x
    else:
        continue
print (lowcal)

But I am getting the wrong output, I am getting: `['SWEET POTATO', '23.4', '100']
When I should be getting: ['LETTUCE', '2.23', '13']
Answer: You can use min() on your list with key as third element:
min([x for x in foods[1:]], key=lambda x: int(x[2]))

Answer: Your problem is that your values for Carbs and Calories are strings (you have them in quotes!), rather than integers. Also, you start with lowcal = foods[0] which is your headers, not a food with calories and carbs. I'd suggest the following:
foods = [
    ['Category', 'Carbs', 'Calories'],
    ['SWEET POTATO', '23.4', 100],
    ['TOMATOES', '5.1', 23],
    ['BEETS', '16.28', 65],
    ['LETTUCE', '2.23', 13]
]
lowcal = foods[1]
for x in foods[2:]:
    if int(x[2]) < int(lowcal[2]):
        lowcal = x
>>> print (lowcal)
['LETTUCE', '2.23', 13]

Victory! Hope that helps, happy coding!
Comment: The problem is for this task I am working on a .csv file given to me so I cannot remove the quotes around the calorie integers. I have to convert them to ints in my code but I'm not sure how to do that.
Comment: ah, you just presented it as a list of lists. In fact, you said you have a list of lists, not a csv. I see you chose a correct answer already, but I modified mine to work as well.


How do I add a previous and next function to on a vertical carousel?

Question: How do I add a previous and next function on a vertical carousel that is also compatible with Squarespace? I am trying to model a carousel around the following code I found from codepen
When I add more images to the carousel, I am unable to scroll down. Can someone help in showing me how I can add this functionality please? Thank you in advance!
Below is the code:
HTML

            26 JAN
            Great win for the club

            22 JAN
            Can they be caught?

            17 JAN
            League is nearly over

            26 JAN
            Great win for the club

            22 JAN
            Can they be caught?

            17 JAN
            League is nearly over

            26 JAN
            Great win for the club

            22 JAN
            Can they be caught?

            17 JAN
            League is nearly over

CSS
body {
    background: #f3f3f3;
    color: #111;
    padding: 20px;
    display: flex;
    place-items: center;
    height: 100%;
    justify-content: center;
    align-items: center;
    height: 90vh;
}

.wrapper {
    width: 80%;
    position: relative;
    max-width: 100%;
    overflow: hidden;
    // border-radius: 3px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, .1)
}

.list-reset {
    list-style-type: none;
    margin: 0;
    padding: 0;
    display: flex;
    width: calc(30% - 4px);
    min-height: 350px;
    height: 70vh;
    flex-direction: column;
    border: 2px solid #fff;
    li {
        padding: 20px;
        border-bottom: 2px solid #fff;
        transition: all 600ms ease;
        cursor: pointer;
        &:hover {
            background: #f9f9f9;
        }
        img {
            transition: all 600ms ease;
            opacity: 0;
            transform: translatey(10px);
            transform-origin: bottom;
        }
        a {
            display: block;
            margin-top: 4px;
        }
        span {
            font-size: 0.7rem;
            opacity: 0.7;
        }
        img {
            position: absolute;
            top: 0;
            right: 0;
            width: 70%;
            height: 100%;
            object-fit: cover;
            object-position: center;
        }
    }
    .active {
        z-index: 999;
        background: #fff;
        a {
            color: #548AF7;
        }
        img {
            opacity: 1;
            transform: translatey(0);
        }
    }
}

Javascript
$('.list-reset li').on('click', function() {
    $('.list-reset li').removeClass('active')
    $(this).addClass('active')
})

Answer: You could just add:
.list-reset{
  overflow: auto;
}

So you can scroll down the list.
I'm aware it has been months so you probably worked this out, but I'll leave this here just in case.
https://www.quackit.com/html/codes/html_scroll_box.cfm


"Punning chord"

Question: I'd like to know if the following description is accurate:
"A composer modulates from one key to another by the use of the "punning" chord, the augmented sixth (punning because it is also a dominant seventh)".
Also, does he mean "punning" as "having two different meanings"?
A bit of context: the speaker is Anthony Burgess, the writer (who also was a musician and a composer).
Answer: Great question; this is a particularly clever part of music theory!
Here's a nice little example in F major; it's just a I--V7--I progression with a little cadential six-four thrown in there just because.

Meanwhile, this next example is in E minor, and it's a little bit different. It actually starts with what we call a German augmented sixth, which then resolves to its own dominant and tonic.

I put a star above one chord in each example; it's above the V7 in the F example, and it's above the Ger+6 in the E example. You'll notice that they're actually the same chord! There are only three real differences:

It's spelled with a Bf in F major but with an A# in E.
The Bf in F resolves down while the A# in E resolves up.
The E in the F example resolves up, though it resolves down in the E example (and eventually returns back to itself).

This means that we can be moving along in F major, get to a V7 chord, and just conceptualize that Bf as actually being an A#, and we can just all of a sudden modulate down a half step! This is shown at the end of the second measure below:

So by a "punning" chord, you're exactly right: it's a musical pun because this starred chord, although it sounds the same, can function in two different ways. Others call it a "harmonic sleight of hand."
It's kind of like this joke:

Two fish are sitting in a tank, and one fish looks to the other and says, "Hey man, how do you drive this thing?!"

This works because "tank" has two meanings here; when we see it alongside the word "fish," we think it's a fish tank. Only later do we realize which version of "tank" is actually meant, and of course that's the joke.
It's the same thing here; When we first hear beat 4 of that last example, our brains assume it's just a V7 in F. Only when we hear what comes next do we realize what was actually going on!
Note that this is also sometimes called a "common chord modulation," so named because the same chord is "in common" between these two keys.
Comment: There has always been a paucity of levity on this site, so thanks for the punny joke. +1 for a clear answer, too.
Comment: @Richard  He doesn't talk much abut his composing music here, yet he mentions some thing about music and literature Anthony Burgess, The Art of Fiction No. 48 Paris Review
Interviewed by John Cullinan http://www.theparisreview.org/interviews/3994/the-art-of-fiction-no-48-anthony-burgess
Comment: Thanks! I really loved that joke! But the "punning chord" metaphor isn't mine, I'm just translating an interview with Burgess and I need to check up every fact (or half-fiction) he mentions to translate these accurately.
Comment: @VetaVeta Can I ask what interview this is? I never knew that he was also a composer, I'd love to read more about it.
Answer: When a chord contains the tritone - the augmented 4th that is the functional "engine" of a dominant 7th chord, we can exploit the symmetrical nature of this interval.  "Punning" is a nice description of this!
Thinking in C major - the important part of G7, the dominant 7th chord of that key, is the tritone interval F - B, which tends to a resolution on E - C.   But F - B may be respelled as E# - B, part of C#7, the dominant 7th of F# major!
When Beethoven explored methods of development through modulation, a favourite chord was the diminished 7th.  C#, E, G, Bb.   There are FOUR tritones in there, each one of which may resolve in two different directions!  Oh joy!
It would not be a vast exaggeration to sum up all of Common Practice harmonic analysis as "hunt the tritone".
Comment: You can also use diminished 7ths to fool the listener into thinking you have modulated when really you haven't. This is Bach having a bit of fun with tritones, especially bars 14-15.  Score: http://imslp.org/wiki/Special:ImagefromIndex/344146 Audio: https://www.youtube.com/watch?v=fCWHiOgv6wE
Comment: Thanks! "Hunt the tritione"... There a pun hidden in this, too.Triton is a myphological Greek god (also Triden), and the Russian for "newt" is "тритон" (pronounced "treeton"). But the most important thing for me is that your answer corroborates that the passage from Burgess interview is correct.

"Punning chord"


What's wrong with this usage of a template `using` declaration

Question: What's wrong with the following usage of a template using declaration?
template <typename T1, typename T2> struct A {
    template <typename AnotherT1>
    using MyTemplate = A<AnotherT1, T2>;
};

template<class SomeA> struct B {
    using MyType = typename SomeA::MyTemplate<double>;
};

int main() {
    B<A<int, int>> b; (void)b;
}

gcc 4.8.2 complains:
temp.cpp:17:46: error: expected ';' before '<' token
     using MyType = typename SomeA::MyTemplate<double>;
                                              ^
temp.cpp:17:46: error: expected unqualified-id before '<' token
temp.cpp: In instantiation of 'struct B<A<int, int> >':
temp.cpp:21:20:   required from here
temp.cpp:17:46: error: 'typename A<int, int>::MyTemplate' names 'template<class AnotherT1> using MyTemplate = struct A<AnotherT1, int>', which is not a type

Comment: `using MyType = typename SomeA::template MyTemplate;`
Comment: @PiotrSkotnicki Thank you! It would be nice if you could make it a reply, in which you would kindly include a link where I will be able to learn about the need for this usage of the word `template`.
Comment: Please refer to the question of which your is a duplicate
Answer: Reference this page.
https://msdn.microsoft.com/en-us/library/0afb82ta.aspx
Modify like below:
using MyType = typename SomeA::template MyTemplate<double>;


How to find the marginal distribution of this particular question?

Question: the question in the link below is to find the marginal distribution of random variables $X$ and $Y$ please refer the questions for details, they says lump the two kinds of failure back together, thereby getting that $X$, the number of successes is a binomial random variable. what is this lump thing? whereas i think it should be according to me $$f(x)=\sum\limits_y\dfrac{n!}{x!y!(n-x-y)!} p^x_1p^y_2 (1-p_1-p_2)^{n-x-y}$$ for all $x\in\ X$, which is surely not correct because the source has different answer. So please do check the link and describe why the marginal distribution of $X$ is $$f(x)=\dfrac{n!}{x!(n-x)!} p^x_1 (1-p_1)^{n-x}$$
Question link
Answer: Don't know what lumping things together is, but, multiplying and dividing by $(n-x)!$,
\begin{align*}
f &=  \sum_y \frac{n! (n-x)!}{x! (n-x)! y!  (n-x-y)!} p_1^x p_2^y (1-p_1-p_2)^{n-x-y} \\
&= \binom{n}{x} p_1^x \sum_y \binom{n-x}{y} p_2^y (1- p_1 - p_2)^{(n-x) - y}\\
&= \binom{n}{x} p_1^x (1-p_1 -p _2 + p_2) ^{n-x}
\end{align*}
where the last equality comes from the binomial theorem.
By symmetry, $y$ is binmially distributed with parameters $n, p_2$. That the two are dependent is then simple.
Comment: Thanks i get the point, any suggestions for better understanding the bivariate distribution.