How many subgroups are there in an elementary-$p$ group

Question: $C_p\times C_p$ has $1+1+(p-1)=p+1$ subgroups of order $p$ (all of which $\cong C_p$), so it has $1+(1+p)+1=3+p$ subgroups totally.
But how many subgroups in $C_p\times C_p \times C_p\times C_p$?
(its seems hard to count subgroups of order $p^2$ and order $p^3$)
Furthermore, could we easily point out how many subgroups which isomorphic to $C_p\times C_{p^2}$ in group $C_{p^2}\times C_{p^2}\times C_{p^2}$?
I only figure out how to find all order-p subgroups in the elementary-$p$ group:
For example in $C_p\times C_p \times C_p$: $p^3=x(p-1)+1\Leftrightarrow x=(p^2+p+1)$, so it has $p^2+p+1=(p-1)^2+C_3^1(p-1)+C_3^1$ order-$p$ subgroups in total. So there are 3 types order-p subgroups:
$\{(x,1,1)| x\in C_p\}$, $\{(x,x^{\alpha},1)| x\in C_p\}$, $\{(x,x^{\alpha},x^{\beta})| x\in C_p\}$, where $\alpha$ and $\beta$ $\in Aut  {C_p}$
Answer: Subgroups of elementary abelian groups are also elementary abelian, so the problem in that context reduces to one of vector spaces: given a vector space $V$ of dimension $n$ over a finite field $\Bbb F_q$ (for us our $q$ is prime, but the question's difficulty is unchanged by generalizing), how many subspaces of dimension $d$ are there? This is a textbook problem - the answer is $q$-binomial coefficients. See the discussion in this question for instance. (Note this hints at finite sets being vector spaces over the field with one element, since $q$-binomial coeffs when $q=1$ are just binomial coeffs.)


Unique Aggregation of Numbers

Question: Suppose I have 5 numbers:  1,7,13,5,6.  I want to perform some kind of algorithm that allows me to derive a number such that if any of those numbers changed in value or switched in order that I would get a different aggregate.
The aggregate must be unique.  In other words the only way to get that aggregate is using exactly those 5 numbers in that exact order.
I have something that is passing all my initial testing but would love to have other people weight in.
Proposed:  1^2 + 1^2 + 7^2 + 2^2 + 13 ^ 2 + 3 ^ 2 + 5^2 + 4 ^2 + 6 ^ 2 + 5 ^ 2
Explanation: I square the number add that to the square of the position it is in the list and then accumulate a grand total.
Bonus:  Provided that the proposed solution does work. Any solution that would produce a smaller number or require less operations would be fantastic.
Comment: Your function is unchanged if you permute the numbers.
Comment: Are your numbers constrained to be integers?
Comment: Yes the numbers are positive integers.  They can range from 1 to 95. The length of maximum numbers is known in each case but varies from case to case.  So if I said there would be no more than 4000 values does that help?
Comment: Certainly.  If each number in the list has a maximum of $b$, you can just use the base $b+1$ represetation of your string.  Your original example, if you knew the maximum were $15$, would simply translate to $17D56_{16}=97622_{10}$  That is an enormous simplification.  The length of the list does not matter
Answer: It is not unique, even up to permutation of the numbers.  Note the sum of the squares of the positions just gives a constant depending on the length of the string.  We know $\sum_{i=1}^ni^2=\frac 16n(n+1)(2n-1)$, so in your case it is $45$.  The simplest example that fails is $(0,0,0,2)$ and $(1,1,1,1)$.  Another is $(3,4)$ and $(0,5)$
To get a provably unique value for every string of naturals the values will be large.  You can do this with the Cantor pairing function, which can be extended to arbitrary length lists, but it gets complicated.  Easier would be to use a hash function.
Comment: As I understand it, the pairing function only comes into play if you insist on getting all natural numbers as possible values.  It's a lot easier if you drop that condition.
Comment: I don't think so.  Do you have a limit on the length of the string and the magnitude of the contents?  That makes a *huge* difference.  If so, you have a limit on the total number of strings, so you can compute the number of bits necessary to represent all of them by taking the $\log_2$.  Now you have a trade between storage, computation time, and ease of programming.  (cont)
Comment: If you have a limit on the length of the string, yes you can exploit the linear independence of the square roots of the primes to choose a real $a_1\sqrt 2 +...a_n\sqrt{p_n}$ where $p_n$ is the $n^{th}$ prime.  To store that you also need a lot of bits so that you know the real to sufficient accuracy that there is no confusion.  Unless you know that most of then entries will be small, you should recognize that bits are cheap.  Store the list and you are done.  Anything else exploits the fact that some lists are more common than others.  Is this true for your application?
Comment: Oh, it wasn't my question originally...I have no idea what the OP had in mind (integers aren't even specified).  I agree with your comments.  I wasn't thinking about the storage issues so much as about the abstract comment "injections from $\mathbb N^2\rightarrow \mathbb N$ are easy to write down while bijections are not.  Not obvious to me why injections have to explode in size, but I agree that everything I can think of does.
Comment: @lulu:  I think OP was thinking of lists of naturals.  A lot depends on the length of the list.  The Cantor pairing fn is quadratic in the maximum value, but you have to know that there are only two elements.  If you have $n$ elements, each of which may be up to $k$, you need $n^k$ numbers to represent the list.  If you don't know the limits beforehand, you waste some bits on separators.  Frankly, I think the question is not well enough specified to have a good answer.  There are ways to represent an arbitrary string in many bits.  If the string is not arbitrary, you can reduce the length.
Comment: @Ross the string is not arbitrary.  See my comment to lulu above and let me know if that clarifies things well enough.
Answer: Assuming that your numbers are constrained to be integers (though this was not specified) then here's a way to do it:
Choose 5 distinct primes,  {$2,3,5,7,11$} for instance.  Then given your five numbers {$a_i$} just form the single integer: $$2^{a_1}3^{a_2}5^{a_3}7^{a_4}11^{a_5}$$

Unique Aggregation of Numbers


Modify configuration properties of ejb-jar.xml during deployment in GlassFish 4.0

Question: I have an ejb-jar.xml that contains configuration information for one of my MDB.
In there is a configuration of:
 <activation-config-property>
        <activation-config-property-name>addressList</activation-config-property-name>
        <activation-config-property-value>mq://test.server.uk:7676</activation-config-property-value>
</activation-config-property>

As my project is built and packaged and then distributed off to users I need to be able to make sure this value can be modified as users have different server addresses.
Currently I have the option to set the address in a properties file. Is there anyway that I could modify this xml during deployment on glassfish 4.0 with the property value?
If not am I going to have to set the value every time someone wants the application and re-build it?
I am open to putting the configuration else where I just need to have it dynamic so that users can set the server addresses in a properties file.
Comment: Have you thought on using a MDB annotated with `@ActivationConfigProperty` and then you could [modify the MDB class definition's annotation string parameter at runtime](http://stackoverflow.com/questions/14268981/modify-a-class-definitions-annotation-string-parameter-at-runtime)?
Comment: Using the `@ActivationConfigProperty` like is shown on [Example 7-3](http://docs.oracle.com/cd/E21764_01/web.1111/e15493/annotations.htm#WLMDB10008) and then using [Bill Burke's approach](http://bill.burkecentral.com/2008/01/14/scanning-java-annotations-at-runtime/) in order to scan your annotations, might solve your problem.
Comment: I'd be happy to use '@ActivationConfigProperty' if it would allow me to modify the values in the annotation. I didn't realise that was possible.
Comment: When I get back to my pc I will have a look. Really appreciate the links
Answer: One thing you can try is to use an @AroundConstruct interceptor to set the value on the MDB at runtime. It's worthwhile to note that while it is possible to use placeholders in your ejb-jar.xml, it's primarily container-dependent, and the apparent lack of reading material on how it's done for Glassfish specifically should be a source of worry for you. Let's try this:

Define an interceptor on your MDB:
@MessageDriven
@Interceptors(AddressListInterceptor.class)
public class YourMDB

Define your interceptor
public class AddressListInterceptor {

    @AroundConstruct
    private void begin(InvocationContext iCtxt) {

        /**load your property prior to this point */

        ActivationConfigProperty addressList = new ActivationConfigProperty{

                                                  public String propertyName(){
                                                    return "addressList";
                                                  }
                                                  public String propertyValue(){
                                                    return theAddressList;
                                                   }

                                 public Class<? extends Annotation> annotationType(){
                                      return ActivationConfigProperty.class;
                                  }

                                               };

          try {
                /**get the annotations, with the intention of adding yours (addressList) to the array using the method demonstrated in
                  http://stackoverflow.com/a/14276270/1530938  */
               Annotations[] annotations = iCtxt.getClass().getAnnotations();

                iCtxt.proceed(); //this will allow processing to continue as normal
           } catch (Exception ex) {

           }
   }

Apart from the unfortunate need to scan and modify the annotations yourself, what this approach buys you is that you're allowed to step into the lifecycle of the MDB and modify the value of the annotation, just before the bean is intantiated. By the time the bean is put into service, it'll take the value you've set and everything should be in order
Comment: Thank you for your answer. I'm not sure where your example for setting up the MDB fits into an actual MDB? Would you be able to provide a small example on injecting via annotation?
Comment: Looks like I spoke too soon. For some reason, I assumed you were writing a message producer, not a consumer. There really isn't any way other than fiddling with the annotations. See my update @Softey. P.S. It's important you confirm here that you're able to get this solution to work for you here; if it doesn't, I need to delete the answer so as not to mislead anyone else that lands on this page
Comment: I don't get how this works @kolossus. How do you set off the interceptor from a Stateless bean (the MDB) that is only initiated once it receives a message from the producer that is connected via the addressList property? I would understand this working for a Singleton but not a stateless MDB
Comment: @Softey, `@AroundConstruct` is a lifecycle interceptor that will be triggered by the container before the MDB is even instantiated, let alone put in service. This is how this interceptor works. None of all the configuration you've set will matter until the instance of the MDB has been instantiated (like any other EJB). See [the lifecycle of an MDB](http://docs.oracle.com/cd/E13222_01/wls/docs81/ejb/message_beans.html). The container *does not* wait until a message arrives to instantiate an MDB; they're pooled like any other EJB beforehand.
Comment: I have followed your suggestion and put it into my code but the interceptor is never initiated. I thought they were only initiated when any method in the class is invoked. I thought the highest level interceptor was a class one.
Comment: @Softey Forgot to mention that you need to declare an empty beans.xml file in your META-INF in the ear or use the [`@Priority`](http://stackoverflow.com/questions/12076586/interceptor-method-not-called-with-interceptor-binding) annotation. If for some reason that doesn't still sort it out, you can configure the interceptor in your ejb-jar.xml
Comment: Where does the @Priority annotation go?
Comment: @Softey `@Priority(Interceptor.Priority.APPLICATION)` in the interceptor; it's in the answer I linked. For the beans.xml file, [look here](http://www.cdi-spec.org/faq/)
Answer: I found a simple way of modifying the address list in glassfish 4.0. This solution allows the rest of your @ActivationConfigProperty to still be used. For me when a user uses a setup script for the installation I can run the following commands:
asadmin server.jms-service.type = REMOTE

asadmin set configs.config.server-config.jms-service.jms-host.default_JMS_host.host=
"testserver.test.te.uk"

asadmin restart-domain

You set the default JMS host to type REMOTE this then tells the broker to use the address defined in the default JMS host.
You then set the host address with the asadmin set command.
Once that is done you need to restart your glassfish.
This is obviously glassfish container dependant but that is all I required.
Comment: Probably should have mentioned that you didn't mind modifying your client's app server configuration. Your question was framed like you were looking for code-based solutions only


Ubuntu 10.04 install is missing /etc/rc0.d, is there a quickfix?

Question: I have no idea how this happened, but /etc/rc.*/ is simply missing.
As a result, aptitude and apt-get don't work right anymore.
Is there a quick-fix for this? I really don't want to reinstall the OS if I don't have to.
Answer: In what way doesn't apt-get work?  A lack of init scripts shouldn't have any direct effect on package management.
What you'll want to do is restore those directories from backup.  Since I'm assuming you don't have backups, then you'll need to identify all of the packages that had files in the removed locations (grovelling through /var/lib/dpkg/info/*.list is probably the quickest way), then on top of that reconfigure any package that has an init script, to recreate the symlinks that would have been in place (because the directories that are apparently missing consist mostly of symlinks created at package install time).
See how much easier life is when you have backups?
Answer: Try this:

manually download sysv-rc and initscripts
manually install them with:
dpkg -i sysv-rc*.deb initscript*.deb
then reinstall all packages with services with this script:
#!/bin/bash
for package in $(dpkg --get-selections | awk '{ print $1 }'); do
  if dpkg -L "$package" | grep -q /etc/init.d; then
    apt-get --reinstall install $package
  fi
done

Answer: You could try installing it somewhere else (Like a virtualbox install) with the same services configuration and copy the directories over.
You shouldn't run into any configuration files in /etc/rc.*/ the main thing is making sure the services you expect to start on boot are starting. I forget Ubuntu's setup but many times the files in /etc/rc.*/ are just symlinks to files that actually reside in /etc/init.d/.
Still I would install it somewhere else and compare.


How can I invoke a drush hook on a remote alias?

Question: I have a local dev environment and a test server environment.  Both are running the exact same code.
In a custom module, I added a drush hook to extend the sql_sanitize command in order to ensure all private user data is removed from the development database.
From a directory within my local environment, I can invoke drush like this:

drush sql-sanitize

And my custom drush hook is run properly.
However, when I invoke drush from the same location but targeting my remote server environment (Pantheon, if it matters, and I checked their documentation, but didn't see any relevant notes):

drush @mytestserver sql-sanitize

sql-sanitize resolves, but the custom drush hook is not called, even though the module containing the hook is enabled locally and on the test server.
I tried invoking the command from a directory outside my local dev environment, but again sql-sanitize resolved without the custom drush hook being called.
How can I execute the drush hook in a remote environment from my local machine?
I have tried both Drush 5.9 and 6.4.0.
Answer: If I understood correctly, we had a similar problem with drush < 6.4, drush was not passing the alias to the remote server if root and uri where not specified.
One way to solve it is to define $conf['root'] and $conf['uri'] in your local alias, the other is to use drush 7.
Answer: I eventually "solved" this by moving the SQL into myfile.sql and running it like this:
`drush @myalias sql-connect` < myfile.sql


Ladder on smooth inclined plane

Question: A uniform ladder AB of weight W and length 2d rests in equilibrium with its upper end A against a smooth vertical wall and its lower end B on a smooth inclined plane. The inclined plane is 10 degrees to the the horizontal.  Find what angle the ladder makes with the wall.
Because the wall and inclined plane are smooth surface`s, only normal reactions will exist at the wall and inclined plane.
Comment: Welcome to MSE. It will be more likely that you will get an answer if you show us that you made an effort. This should be added to the question rather than in the comments.
Answer: In the attached figure, the inclined floor is represented by line $L_1$ Line $L_3$ is perpendicular to the supporting vertical wall. Line $L_2$ is perpendicular to $L_1$ and intersects $L_3$ The intersection point ($p_i$) has the same $x$ coordinate as the ladder mass center ($G$).
$$
A = \lambda_4(0,1)\\
L_1\to B=\lambda_1(v_x,v_y) \\
L_2\to p_i = B+\lambda_2(-v_y,v_x)\\
L_3\to p_i = A+\lambda_3(1,0)\\
G = \frac{1}{2}(A+B)\\
G_x = (p_i)_x\\
\lVert A-B\rVert = L
$$
Solving for $\lambda_1,\lambda_2,\lambda_3,\lambda_4$ we have
$$
\lambda_2 = \frac{L}{\sqrt{v_x^2+4v_y^2}}\\
\lambda_1 = \frac{2v_yL}{v_x\sqrt{v_x^2+4v_y^2}}\\
\lambda_3 = \frac{v_yL}{\sqrt{v_x^2+4v_y^2}}\\
\lambda_4 = \frac{(v_x^2+2v_y^2)L}{v_x\sqrt{v_x^2+4v_y^2}}
$$
After that we can build the plot

NOTE
$L$ represents the ladder lenght. $v = (v_x,v_y) = (1,\tan(\frac{10\pi}{180}))$
$$
\angle BAO=\alpha = \arccos\left(\frac{(0,1)\cdot(B-A)}{\lVert B-A\rVert}\right) = 19.4254^{\circ}
$$
Comment: Interesting graph development.  I attempted resolving vertical and horizontal force components, then taking moments about B.  The answer is 19.4 degree, but I`m unable to calculate that value.
Comment: @tas75 This problem can be solved only with the resultant. No need for moments. Once we know the reaction forces  direction, we have $\vec W = \vec F_1 + \vec F_2$ two equations and two unknowns $|\vec F_1|$ and $|\vec F_2|$
Answer: vertical resolution: $wg=R \cos10\cdots(1)$
horizontal resolution: $S=R \sin10\cdots(2)$
moments about B: $wg d \cos\alpha = S \times 2d \sin\alpha$
$\therefore \quad wg \cos a=2S \sin\alpha$
$\therefore \quad \frac{wg}{2S}=\tan\alpha\cdots(3)$
(1) and (2) $\Rightarrow$ (3) $\frac{R \cos 10}{2R \sin 10}=\frac{1}{2} \cot  10=\ \tan\alpha$
$\therefore \quad \tan\alpha=\frac{5.67128}{2}=2.83564$ so $\alpha=70.57^\circ$
Thus by considering right-angle triangle, Angle A = $180-90-70.57=19.43^\circ$

Ladder on smooth inclined plane


Can I use Wilcoxon Signed-Rank paired Test to compare binary data?

Question: I have two series of binary outcomes:
      Series1 Series2
Test1 0       1
Test2 1       1
Test3 1       1
Test4 0       1
Test5 0       0
...

I want to know whether or not the outcomes in the two series were significantly different.
Can I use the Wilcoxon signed rank test for this purpose?
I.e., in R:

wilcox.test(data1, data2, paired=TRUE)
Comment: You *could* (you type the command, it happens), but should not. The test is designed for a continuous outcome. There are other tests for the binary case.
Answer: For binary and independent variables you should use a chi-square test if the Central Limit Theorem's assumptions are not violated or Fisher's exact test if they are.
Here is a piece of code that tests the CLT assumptions and runs the relevant test depending on the outcome.
I've used a rule of thumb value of 5. Feel free to change my number "5" with something a higher value for more conservative or less if you want to be less conservative:
# Generate some random binary outcomes for Series 1 and 2
set.seed(1241535)
Series1 <- rbinom(150, 1, 0.5)
Series2 <- rbinom(200, 1, 0.6)

# All tests need to be confirmed
pooled_p <- (sum(Series1) + sum(Series2))/(length(Series1) + length(Series2))

test1 <- (length(Series1) * pooled_p) >= 5
test2 <- (length(Series2) * pooled_p) >= 5
test3 <- (length(Series1) * (1 - pooled_p)) >= 5
test4 <- (length(Series2) * (1 - pooled_p)) >= 5

final_test <- all(test1, test2, test3, test4)

# Chi-square or Fisher's exact test
x    <- c(sum(Series1), sum(Series2))
n    <- c(length(Series1), length(Series2))
mash <- rbind(c(sum(Series1), length(Series1) - sum(Series1)),
              c(sum(Series2), length(Series2) - sum(Series2)))

if(final_test == T){

  ## With Yate's continuity correction

  prop.test(x,n)
  #Exactly the same as:
  chisq.test(mash)

}else{

  # Fisher's exact test
  fisher.test(mash)

}

If your variables are not independent e.g: if series 1 and 2 are measurements of the same individual before and after an intervention, then a McNemar's test is more appropriate:
set.seed(1241535)
Series1 <- rbinom(200, 1, 0.5)
Series2 <- rbinom(200, 1, 0.6)

tab <-
  matrix(c(sum(Series1 == 1 & Series2 == 1),
           sum(Series1 == 0 & Series2 == 1),
           sum(Series1 == 1 & Series2 == 0),
           sum(Series1 == 0 & Series2 == 0)
           ),
         nrow = 2,
         dimnames = list("Series1" = c("1", "0"),
                         "Series2" = c("1", "0")))

tab
mcnemar.test(tab)

The latter might be the relevant one for your case as I've noticed that you specify paired = TRUE in your code.
Comment: Fixed that. Name of the corrected table is "tab" for future readers
Comment: No. I meant simply that I can see nothing in the central limit theorem itself that says anything about how to choose when the chi-squared approximation is not suitable. Your first sentence mentions "central limit theorem assumptions". Which assumption violations would make the chi-squared unsuitable but leave the Fisher exact test unaffected?
Comment: Take a look at what the [Central limit theorem](https://en.wikipedia.org/wiki/Central_limit_theorem#Classical_CLT) actually says. Could you explain which of the assumptions of the central limit theorem (or indeed any of the central limit theorems, since there are several) are relevant to choosing whether to do a chi-squared test or something else?
Comment: @Glen_b Oh you mean that the outcomes of series 1 and 2 might not be independent? You are right, I will edit my answer to account for that case as well. Thanks for your correction, it was my bad to assume independence.
Comment: The sample size. In the case of independent samples and when we want to assess the frequency difference H0:p1=p2 vs H2:Otherwise, the statistic that we derive is Z = ((p1hat - p2hat) - (p1 - p2))/(SE(p1_hat-p2_hat)) which under the null hypothesis of p1=p1=p becomes Z = (p1hat - p2hat) /(sqrt(p(1-p)(1/n1 + 1/n2))). The derived test statistic converges in distribution to N(0,1). This is what I meant by assumptions of CLT, that we basically need sufficiently large samples for this convergence to be valid.  https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test#Assumptions
Comment: Thank you very much for your comments. My data is paired and nominal (i.e., "1" or "0" for each case with two settings). The n~900. I have used the McNemar's Chi-squared test which returned a p-value <<5%. I conclude, that the change observed in my case was significant.
Comment: You are welcome. Sounds solid!


Atualizar formulário dialog sem fechar o mesmo

Question: Como posso fazer para atualizar meu formulário dialog sem fechar o mesmo?
Ou seja preciso buscar o endereço pelo CEP, e jogá-lo no formulário, mas não estou conseguindo. Segue o código que estou usando.:
View:cadastro clientes
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <ui:composition template="./../template.xhtml">
            <ui:define name="content">

                <h:form>

                </h:form>

                <h:form id="formDataTable">

                        <f:facet name="header">
                            Listando Clientes
                        </f:facet>

                            <h:outputText value="#{cliente.idCliente}" />

                            <h:outputText value="#{cliente.cpf}" />

                            <h:outputText value="#{cliente.nome}" />

                            <h:outputText value="#{cliente.endereco}" />

                            <h:outputText value="#{cliente.bairro}" />

                            <h:outputText value="#{cliente.telefone1}" />

                            <h:outputText value="#{cliente.celular1}" />

                            <h:outputText value="#{cliente.dataAniversario}" />

                                <f:setPropertyActionListener value="#{cliente}" target="#{clientesBean.selectedclientes}" />

                                <f:setPropertyActionListener value="#{cliente}" target="#{clientesBean.selectedclientes}" />

                </h:form>
                <h:form id="formCreate" >

                        <h:panelGrid id="display" columns="2" cellpadding="4">

                                    <h:panelGrid id="aba1" columns="2" cellpadding="4">
                                        <h:outputText value="CPF:" />

                                        <h:outputText value="RG:" />

                                        <h:outputText value="Nome:" />

                                        <h:outputText value="Data Aniversario:" />

                                        <h:outputText value="Status:" />

                                            <f:selectItem itemLabel="Ativado" itemValue="1" />
                                            <f:selectItem itemLabel="Inativo" itemValue="0" />

                                    </h:panelGrid>

                                    <h:panelGrid id="aba2" columns="2" cellpadding="4">
                                        <h:outputText value="CEP:" />

                                        <h:outputText value="Endereço:" />

                                        <h:outputText value="Bairro:" />

                                        <h:outputText value="Cidade:" />

                                        <h:outputText value="Complemento:" />

                                        <h:outputText value="Ponto de referencia:" />

                                    </h:panelGrid>

                                    <h:panelGrid id="aba3" columns="2" cellpadding="4">
                                        <h:outputText value="Telefone 1:" />

                                        <h:outputText value="Telefone 2:" />

                                        <h:outputText value="Celular 1:" />

                                        <h:outputText value="Celular 2:" />

                                    </h:panelGrid>

                            <f:facet name="footer">

                            </f:facet>

                        </h:panelGrid>

                </h:form>

                <h:form id="formUpdate">

                        <h:panelGrid id="display" columns="2" cellpadding="4">

                            <h:outputText value="Id:" style="display: none;"/>

                                    <h:panelGrid id="aba1" columns="2" cellpadding="4">
                                        <h:outputText value="CPF:" />

                                        <h:outputText value="RG:" />

                                        <h:outputText value="Nome:" />

                                        <h:outputText value="Data Aniversario:" />

                                        <h:outputText value="Status:" />

                                            <f:selectItem itemLabel="Ativado" itemValue="1" />
                                            <f:selectItem itemLabel="Inativo" itemValue="0" />

                                    </h:panelGrid>

                                    <h:panelGrid id="aba2" columns="2" cellpadding="4">
                                        <h:outputText value="CEP:" />

                                        <h:outputText value="Endereço:" />

                                        <h:outputText value="Bairro:" />

                                        <h:outputText value="Cidade:" />

                                        <h:outputText value="Complemento:" />

                                        <h:outputText value="Ponto de referencia:" />

                                    </h:panelGrid>

                                    <h:panelGrid id="aba3" columns="2" cellpadding="4">
                                        <h:outputText value="Telefone 1:" />

                                        <h:outputText value="Telefone 2:" />

                                        <h:outputText value="Celular 1:" />

                                        <h:outputText value="Celular 2:" />

                                    </h:panelGrid>

                            <f:facet name="footer">

                            </f:facet>
                        </h:panelGrid>

                </h:form>
                <h:form id="formDelete">

                        <h:inputHidden value="#{clientesBean.selectedclientes.idCliente}" />

                </h:form>

            </ui:define>

        </ui:composition>

Managed bean buscarCEP:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import util.CepWebService;

@ManagedBean(name = "user")
@SessionScoped
public class UserBean {

    public String userName;

    public String outcome() {
        return "index2";
    }

    public String index() {
        return "index2";
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void execute(String value) {
        // ...
    }

    private static final long serialVersionUID = 1L;

    private String cep = null;

    private String tipoLogradouro;
    private String logradouro;
    private String estado;
    private String cidade;
    private String bairro;

    public void encontraCEP() {
        CepWebService cepWebService = new CepWebService(getCep());

        if (cepWebService.getResultado() == 1) {
            setTipoLogradouro(cepWebService.getTipoLogradouro());
            setLogradouro(cepWebService.getLogradouro());
            setEstado(cepWebService.getEstado());
            setCidade(cepWebService.getCidade());
            setBairro(cepWebService.getBairro());
        } else {

            FacesContext.getCurrentInstance().addMessage(
                    null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR,
                            "Servidor não está respondendo",
                            "Servidor não está respondendo"));
        }
    }

    public String getCep() {
        return cep;
    }

    public void setCep(String cep) {
        this.cep = cep;
    }

    public String getTipoLogradouro() {
        return tipoLogradouro;
    }

    public void setTipoLogradouro(String tipoLogradouro) {
        this.tipoLogradouro = tipoLogradouro;
    }

    public String getLogradouro() {
        return logradouro;
    }

    public void setLogradouro(String logradouro) {
        this.logradouro = logradouro;
    }

    public String getEstado() {
        return estado;
    }

    public void setEstado(String estado) {
        this.estado = estado;
    }

    public String getCidade() {
        return cidade;
    }

    public void setCidade(String cidade) {
        this.cidade = cidade;
    }

    public String getBairro() {
        return bairro;
    }

    public void setBairro(String bairro) {
        this.bairro = bairro;
    }
}

agora quando clico no botão pesquisar o cep null para managedBean
public class CepWebService {
private String estado = "";
private String cidade = "";
private String bairro = "";
private String tipoLogradouro = "";
private String logradouro = "";

private int resultado = 0;

@SuppressWarnings("rawtypes")
public CepWebService(String cep) {

    try {
        URL url = new URL(
                "http://cep.republicavirtual.com.br/web_cep.php?cep=" + cep
                        + "&formato=xml");

        Document document = getDocumento(url);

        Element root = document.getRootElement();

        for (Iterator i = root.elementIterator(); i.hasNext();) {
            Element element = (Element) i.next();

            if (element.getQualifiedName().equals("uf"))
                setEstado(element.getText());

            if (element.getQualifiedName().equals("cidade"))
                setCidade(element.getText());

            if (element.getQualifiedName().equals("bairro"))
                setBairro(element.getText());

            if (element.getQualifiedName().equals("tipo_logradouro"))
                setTipoLogradouro(element.getText());

            if (element.getQualifiedName().equals("logradouro"))
                setLogradouro(element.getText());

            if (element.getQualifiedName().equals("resultado"))
                setResultado(Integer.parseInt(element.getText()));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

public Document getDocumento(URL url) throws DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(url);

    return document;
}

public String getEstado() {
    return estado;
}

public void setEstado(String estado) {
    this.estado = estado;
}

public String getCidade() {
    return cidade;
}

public void setCidade(String cidade) {
    this.cidade = cidade;
}

public String getBairro() {
    return bairro;
}

public void setBairro(String bairro) {
    this.bairro = bairro;
}

public String getTipoLogradouro() {
    return tipoLogradouro;
}

public void setTipoLogradouro(String tipoLogradouro) {
    this.tipoLogradouro = tipoLogradouro;
}

public String getLogradouro() {
    return logradouro;
}

public void setLogradouro(String logradouro) {
    this.logradouro = logradouro;
}

public int getResultado() {
    return resultado;
}

public void setResultado(int resultado) {
    this.resultado = resultado;
}

}

Ainda não cheguei no resultado
Answer: Isso já aconteceu comigo. A solução foi ao invés de dar update no <h:form> em que o
 está dar update no container de dados dentro do
.
No seu caso pode o <h:panelGrid> que está dentro do
.
Comment: Coloquei conforme explicado, mas agora não aparece meu formulário.
``
Comment: Como você colocou o `update`?
Comment: `update=":aba2"`
Comment: mudei para `update="aba2"` atualiza o formulário porém não preencher as informações nos campos do endereços
Comment: agora não esta preenchendo os campos do formulário, não consigo chegar em um resultado.
Comment: ainda não consegui chegar em um resultado


use of define-fun in z3's input language

Question: Going by this post, define-fun seems to be a macro that gets expanded by z3's preprocessor and not seen by the actual solver but makes the input file possibly compact and easier to read. I'm asking because I see some (apparently random) differences in the satisfying assignments and performance on the same problem: one which uses define-funand one which doesn't, which makes me wonder if it is more than just a macro. Does one have to be careful about the aggressive use of define-fun in certain cases? I observed this on some QF_NIRA, QF_LIRA problems that I have.
Answer: define-fun is treated as a macro in Z3.
The behavior of Z3 will be different if you use equalities and uninterpreted functions.
Furthermore, if you use "declare-fun" and then create quantified equalities,
the problem is no longer in the QF_LIRA fragment.


Query condition that needs to return true no longer working

Question: I'm working on updating our sites to D9. One of our custom modules stopped working and I narrowed it down to this bit of code that modifies some query conditions for a view filter. It's trying to set a condition that always returns true (i.e. 1 = 1).
function views_taxonomy_filter_process_query_conditions(array &$conditions, $field) {
  foreach (Element::children($conditions) as $key) {
    if ($conditions[$key]['field'] instanceof ConditionInterface) {
      $child = & $conditions[$key]['field']->conditions();
      views_taxonomy_filter_process_query_conditions($child, $field);
    }
    elseif (strpos($conditions[$key]['field'], $field) !== FALSE) {
      // We cannot just unset the condition, because this action might create
      // incorrect query. Let's replace it with 1 = 1 condition.
      $conditions[$key] = [
        'field' => 1,
        'value' => 1,
        'operator' => '=',
      ];
    }
  }
}

This worked fine in D8. However I'm now getting this error as it seems to be looking for a column called 1 instead of evaluating that condition:
Drupal\Core\Database\DatabaseExceptionWrapper:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '1' in 'where clause'

How can I change this to restore the old functionality? Thank you!
Comment: @leymannx Just updated with the full function. The module works on views filters with filters based on taxonomies to limit selections in those filters to only contain terms that have results.
Comment: This might not be a Drupal issue. Are you using the same PHP and MySQL versions?
Answer: I found out here that since Drupal 8.7.0 (at least) the field part of the condition can not be an expression.
Since you can't use "where" you must figure out another way to force the condition to always be true. Maybe you could mess around with the operator like this:

Instead of overriding the entire condition, use the "LIKE" operator:
$conditions[$key]['value'] = '%';
$conditions[$key]['operator'] = 'like';

Or if that doesn't work, the "NOT IN" operator:
$conditions[$key]['value'] = array('w00t');
$conditions[$key]['operator'] = 'NOT IN';

Hope this helps you!


War card game in java text based

Question: I need some help creating a war card game in java. I'm pretty inexperienced with ArrayLists, and I'm guessing this is what I need to use to add and remove cards from the computer's array of cards and the user's array of cards.
Can anyone give me some help on the steps I should take and the ArrayList methods I can use to print, compare, etc. cards?
Code is welcome, I'm kinda new to this!
Thanks
Comment: @DanW:  To be fair, War was how I learned much of the Python I do today.  Then again, I had read up on a few tutorials beforehand...
Answer:
Consider making some sort of Card object that will handle all of the suits and values.
Create an ArrayList<Card> to hold the cards in.
Implement the logic of the game:

Dequeue cards from the front of the ArrayList using ArrayList.remove(int), and enqueue them using ArrayList.add(Object).
Consider what happens during a turn.  Each Card must have a weight.
Consider what happens when two cards of equal weight are placed down.  What do you do then?

Get these things out of the way.  Code can come later.  Also, check out the Java API for ArrayList; it will help you a lot.

War card game in java text based


Weak instrument but 2nd stage significant

Question: My IV's 1st stage F-stat is 4.7 (considered weak by the rule of thumb). The 2nd-stage regression coefficient is significant. I wonder what is the best way to interpret such observations.
Comment: Your question might have been [answered here](https://stats.stackexchange.com/q/482589).
Comment: Hi Durden, my question is actually the "opposite" situation of the question you mention. In my case, I have a weak instrument with significant 2nd stage results. And I am not sure what are the appropriate take-aways for such scenario. Thanks!
Answer: If it's overidentified IV (more instruments than endogeneous regressors), the second-stage $t$-test can be severely distorted when instruments are weak (see for example Stock & Yogo (2005) p. 28 about the $F$>10 rule). Recent research (Angrist & Kolesár, 2023), however, has shown that if you're using a single instrument, you can  interpret your second-stage $t$-test fairly reliably regardless of the first-stage $F$-statistic unless there is extreme endogeneity.

Our setup has two free parameters: the correlation between structural and first-stage residuals (henceforth, "endogeneity"), and the population first-stage
$F$-statistic. This fact lends itself to the construction of easily-interpreted rejection contours characterizing conventional second-stage
$t$-tests and confidence interval coverage rates. We see, for example, that for endogeneity less than about 0.76, 95% confidence interval coverage is distorted by no more than 5% for any population $F$. This is explained by the fact that, even as median bias increases when the first stage gets weaker, second-stage precision falls (we focus on median bias because the conventional just-ID IV estimator has no moments). In contrast with the over-identified case, conventional just-ID IV standard errors reflect this, and confidence intervals widen accordingly. This fact keeps interval coverage high unless endogeneity is extraordinarily high. (Angrist & Kolesár, 2023)

So, if both the first stage and the reduced form are significant and your results are robust to whatever checks you have devised to assess their credibility, I wouldn't worry too much about $F$<10.
REFERENCES:

Angrist, J., & Kolesár, M. (2023). One instrument to rule them all: The bias and coverage of just-ID IV. Journal of Econometrics. https://doi.org/10.1016/j.jeconom.2022.12.012
Stock, J. H. and Yogo, M. (2005). Testing for Weak Instruments in Linear IV Regression. IDENTIFICATION AND INFERENCE FOR ECONOMETRIC MODELS: ESSAYS IN HONOR OF THOMAS ROTHENBERG. Available at SSRN: https://ssrn.com/abstract=1734933
Comment: Thanks a log Jonathan, this is very helpful!
Comment: Terrific answer.
Answer: Just for fun, the following is ChatGPT's response (not helpful repeating what we already know):
``When dealing with instrumental variables (IV) estimation, particularly in a two-stage least squares (2SLS) framework, the strength of the instrument is crucial for reliable inference. Your observations involve two key points: a weak first-stage F-statistic and a significant second-stage regression coefficient. Here's how to interpret these observations:
Weak First-Stage F-Statistic (4.7): The first stage of an IV/2SLS estimation involves regressing the endogenous variable on the instrumental variable(s). The F-statistic from this regression tests the null hypothesis that the instrument(s) are weak, i.e., they are not correlated with the endogenous explanatory variable. A rule of thumb is that the F-statistic should be greater than 10 to ensure that the instrument is not weak. An F-statistic of 4.7, as in your case, suggests that the instrument might be weak. This raises concerns about the reliability of the 2SLS estimates, as weak instruments can lead to biased and inconsistent parameter estimates and weaken the inference in the second stage.
Significant Second-Stage Regression Coefficient: Despite the weak first-stage F-statistic, you've found a significant coefficient in the second-stage regression, where the predicted values from the first stage are used as instruments for the endogenous variable. This significance suggests that, conditional on the instrument, there is a statistically significant relationship between the instrumented variable and the dependent variable. However, this result should be interpreted with caution due to the weak instrument issue in the first stage.
Given these observations, here's how to proceed:
Reassess the Instrument: Ensure that the instrument is theoretically valid, meaning it affects the dependent variable only through the endogenous explanatory variable and is not correlated with the error term of the outcome equation. If the theoretical justification is strong, the concern about weak instrumentation might be somewhat mitigated, but empirical concerns remain.
Use Alternative Instruments: If possible, consider finding and using alternative or additional instruments that are stronger (i.e., more correlated with the endogenous variable but still exogenous).
Robustness Checks: Conduct robustness checks using different specifications or subsets of the data to see if the results hold.
Report the Weak Instrument Issue: When presenting your results, it's crucial to discuss the potential limitations due to the weak first-stage F-statistic. This includes the potential for biased and inconsistent estimates.
Consider Other Methods: If the instrument's weakness is a persistent issue, consider other estimation strategies that might not rely on instrumental variables, such as natural experiments, regression discontinuity designs, or difference-in-differences approaches, if applicable to your research question and data.
Use Weak Instrument Robust Inference: There are statistical methods designed to deal with weak instruments, such as the Limited Information Maximum Likelihood (LIML) approach or the use of a Fuller adjustment. These methods can provide more reliable inference when the instruments are weak.
In summary, while a significant second-stage coefficient is encouraging, the weak first-stage F-statistic raises concerns about the reliability of the IV estimates. Careful consideration of the instrument's validity, exploration of alternative instruments, and robustness checks are essential steps in addressing this issue.''


Simple SQL code evades me.. Unionize two mismatched tables

Question: I'm selecting 1 field from 1 table and storing it into a temp table.
Sometimes that table ends up with 0 rows.
I want to add that field onto another table that has 20+ fields
Regular union won't work for me because of the field # mismatch.
Outer wont work for me because there is nothing to compare.
NVL doesn't work on the first temp table.
Anyone know how to do it?
UPDATED:
I failed to mention.... When the table that retrieves 1 field finds a match in other cases, this code that I'm using now works....
SELECT DISTINCT reqhead_rec.resp_name

FROM reqhead_rec, biglist

WHERE reqhead_rec.req_no = biglist.req_no
 AND reqhead_rec.frm = biglist.req_frm

INTO TEMP grabname with no log;

SELECT biglist.*, grabname.resp_name

FROM biglist, grabname

ORDER BY prnt_item, account_amt

INTO TEMP xxx with no log;

Comment: What are the criteria for choosing whether to add the field from the first table to a row in the second table?
Comment: the first table has a bunch of stuff about PO's in it
the second table just finds the name from another table matching it across two fields
sometimes POs are made without the info to match
Can i just default something in the case that no rows are found?
Answer: It sounds like you do want a join, not a union.
You don't need to compare anything to do a join.  You end up with a cross product if you specify no join condition:
SELECT t20.*, t1.*
FROM table_with_20_columns AS t20
  LEFT OUTER JOIN temp_table_with_1_column AS t1 ON (1=1);

When there are zero rows in the temp table, it'll be reported as NULL in the result of the above query.
However, if there are multiple rows in the temp table, you'll get the cross product with the first table.  I can't tell from your question what you want.
edit: The join condition expressed in the ON or USING clause should be optional according to the SQL standard, but at least as I test it in MySQL 5.0, it's a syntax error to omit that clause.  But you can use ON (1=1).
edit: Answering your question in the comment:
SELECT COALESCE(reqhead_rec.resp_name, dflt.resp_name) AS resp_name
FROM (SELECT 'default name' AS resp_name) dflt
  LEFT OUTER JOIN reqhead_rec ON (1=1)
WHERE reqhead_rec.req_no = biglist.req_no AND reqhead_rec.frm = biglist.req_frm
INTO TEMP grabname WITH NO LOG;

Actually, you may be able to skip the temp table altogether.  Just LEFT JOIN your main table to reahead_rec.  Put those conditions into the ON clause of the join, not in the WHERE clause.  Then use COALESCE() in the select-list of that query to give a default name when one is not found in the other table.
SELECT b.*, COALESCE(r.resp_name, 'default name') AS resp_name
FROM biglist AS b
  LEFT OUTER JOIN reqhead_rec AS r
    ON (b.req_no = r.req_no AND r.frm = b.req_frm)
INTO TEMP xxx WITH NO LOG;

Comment: You need an "ON" clause other wise you'll get an error... you can join "ON 1 = 1".
Comment: I guess what i really should be asking is how can i fill a field with a default value if no results come from the query?

original query..

SELECT reqhead_rec.resp_name
FROM reqhead_rec
WHERE reqhead_rec.req_no = biglist.req_no
AND reqhead_rec.frm = biglist.req_frm
INTO TEMP grabname WITH NO LOG;
Comment: Im getting a syntax error at the open quote for default name... im not using mysql and sometimes the syntax of subroutines fail in the version im using... im going to keep trying this though, thanks.... i edited the original question with the sql im using now
Comment: im getting syntax errors with the coalesce subroutine... im using informix believe it or not... but thanks a lot for your help... much appreciated
Comment: Wow, that's pretty weak.  Coalesce is a standard SQL function.  It could be Informix has a function to do a similar thing, like IFNULL() or NVL() or something.
Comment: nvl exists, but did not do the trick for some unknown reason.. thats why i posted this question
Answer: What field would it match with? BTW, here's how to line them up:
SELECT NULL, NULL, NULL, NULL, MySingleField, NULL, NULL, NULL... FROM #temp
UNION ALL
SELECT Col1, Col2, Col3, Col4, Col5, Col6,... FROM OtherTable

UPDATE:
OK, after reading your update... I don't think you want a UNION at all, but rather, and incredibly simple SUBSELECT
SELECT
    *,
    (SELECT TOP 1 Name FROM Blah WHERE Blah.SomeID = MyTable.SomeID) AS ExtraCol
FROM
    MyTable

Comment: i need to add the field to the table
the first table has 73 fields, its needs #74, which is someones name from another table
Comment: thanks.. the subselect worked!!!

"2 row(s) retrieved."  never looked so good...
Answer: Try selecting nvl(NULL,NULL) for missing values


Display message to authenticated users

Question: I have a Drupal site and my problem is that it doesn't display error messages when authenticated users are filling in, but they display with the administrator users.
An example of the messages I am referring to is "image size too exceed […]."
How can I make the error messages appear for every users?
Answer: Use Disable Message Module. and set permission for user roles you want.

Gives a site owner options to disable specific messages shown to end
  users. The core drupal message system as offered by drupal_set_message
  is an excellent way for modules to send out messages to the end users.
  However not all drupal site owners are keen to show all the messages
  sent out by drupal core and all modules to their users. This module
  gives site administrators a reasonably powerful way to filter out
  messages shown to the end users.
Comment: Thanks zhilevan, I have installed the module and enabled the options but the error message is still not showing
Comment: @jonazz you're welcome,  is the theme used by both users is equal?
Comment: no its not equal, the one for authenticated users is limited
Comment: @jonazz try use admin theme for authentication  user, (it is just for debug purpose) and tell me about the result

Display message to authenticated users


Can I still use the staff notes that exceed the number of beats?

Question: May I ask if the measure has a certain number of beats, can I still use notes in that measure that exceed the number of beats?
Look at the picture below:
Comment: Even though the *notes* must not exceed the length of the bar (or in US the measure) *rests* can appear to. By convention a semibreve (whole note) rest is also used for a complete bar rest, even when the bar is less than four crotchets long. Of course normally others are playing while you are carefully counting out your rests.
Comment: @nuggethead [I think it's ok](https://music.meta.stackexchange.com/questions/3802/how-invasive-of-an-edit-is-too-invasive); the OP clearly intends to talk about measures; a minimal edit that preserves (clarifies!) intent helps rather than hurts. Edit made.
Comment: Is this a US/UK convention, or am I the only one?  I think that the word measure would be cleaerer than staff/stave.
Comment: @nuggethead, yes. UK uses bars and bar lines, while US uses measures and bars. The staff (plural staves) is always the five lines.
Comment: @Peter in that case why does the question mention staff/staves at all?  Isn't the question only about time?
Comment: @nuggethead, you would need to ask OP. I assumed, as I think others also did, that OP inadvertently used the wrong terminology.
Comment: @Peter I've not encountered this before.  Is it improper to edit another user's question?
Comment: @Peter For OP's benefit, I should probably point out that the opposite is certainly true. A 2-bar rest, or even a 100-bar rest, can be notated as a [multi-bar rest](https://musescore.org/en/handbook/3/measure-rests) with one black rectangle between two bar lines. BUT, it isn't standard to use it with a score or grand staff as shown here; standard practice is for all bar lines to line up, and these multi-measure rests would then be printed as individual bars. There could be exceptions for non-standard practices as in Lazy's answer, or e.g. polymeter.
Comment: @go_poke You've used incorrect terms and someone has fixed this for you (a measure/bar is very different to a staff/stave)
– this was not a good rollback so I've reverted it.
Comment: Please help me reply this: https://musescore.org/en/node/342222, https://musescore.org/en/node/342225
Comment: @Peter in the US "measure" and "bar" are synonyms, and the lines separating them are typically called "bar lines" as they are everywhere else.  For example, the US gave birth to both the 12-bar blues and the 32-bar song form.  It's not clear to me when "measure" fell out of use in the UK but the OED (in 1908) quotes the Grove dictionary from the 1880s noting that "bar" is incorrectly applied to that which is technically called a measure, which seems to imply that it was already well on its way out in the late 19th century. But I did find it in an English theory book of the 1870s.
Answer: The whole point of having barlines is to split a piece into equal parts. If some of those parts are not equal, then they will need another time signature to accommodate them. And every bar in a piece with one time signature will have the appropriate number of beats, be it notes or rests.
Except - the first and/or last bars. Which will never have more (exceed) the quoted number, but could contain fewer. This is the anacrucis, at the beginning (the 'pick-up), which is usually only part of one bar, and the part at the end, which 'fills the gap' made at the beginning. That's usually to allow a repeat to follow say, a first verse, without a timing hiccup.
So, if you wanted the breve to be the bar-filler, the time signature would need to be 8/4, allowing a count of 8 beats in each bar (maybe not 1st and last). Or, if you wanted a note lasting those 6 beats, write in 4/4, and do as you did second, tie two semibreves across two bars.
Comment: Also excepting cadenza bars, which can be any length but are usually visually distinctive (like every note being smaller).
Answer: Both ways of notation are metrically correct. The second way to notate it is the default and expected way of doing this, so unless there is a good reason against it you should stick with that. The upper example is something you'd mostly see with modern editions of old mensural scores, which did not have bar lines but the editor still decided to add bar lines for readability, such as this:

You can use something like this for example if otherwise the notations would become cluttered, but you should be careful, as this might also just get confusing.
So only use this if its meaning is clear and it is clearly beneficial for the readability of the score.
Funnily there are also cases where a brevis is used without adding a bar line, implicitly doubling the duration of the bar. Schubert does this in his canon for three male voices "Dreifach ist der Schritt der Zeit" (D43):

Note how on the cadence ("the past forever stands still") Schubert is slowing down, eventually switching the beat from the half to the whole note. It is also quite clear why Schubert decided to go for this way of writing this. If you compare these two ways of notating this, you'll see that what Schubert is doing is less cluttered and thus somewhat easier to read:

But you will also notice that this second one is very clear on what is meant, while the first one might require a few thoughts on what this actually means. So I'd say this case does not fit the rule of a clear meaning perfectly (although well enough).
So the point is: Do what you want and what looks good, but if you go against the default, do it for a good reason, and even then only if the benefits clearly outweigh the confusion this may cause.
Comment: @Laurence Why should this be so? It is quite uncommon for 1) support in notation software is a bit weird, and 2) you should probably not do it anyway unless there is a really good reason to do so. *Modern notation* usually allows **far** more than old notation, especially since graphic notation came along. What for example if you want to write mensural-style music? Or what if simply doing something like this leads to less clutter? Take something like Chopin Op. 28 Nr. 5. Even modern editions have the 8th notes cross the bar lines for the sake of readability.
Comment: We should make it clear that the sort of thing shown in this answer is NOT an option in modern notation.
Answer: Given a 4/4 time signature, a note of 8 beats must be split across two measures as two whole notes tied together. The lower example is correct; the upper is not permitted.
Comment: That's right, it turns out that to use double whole notes, you have to be in 8/4 time or more to use it, why didn't I think of it!
Answer: The simple answer is 'no'.  In modern notation, a note's length cannot exceed the bar that contains it.  Ancient practice (and modern facsimiles of ancient works) might differ, but that's today's rule.
And, as a corollary, bars MUST be filled, by notes or rests adding up to that bar's length.  There's a Whole Bar Rest, but no Whole Bar Note, convenient though it might be when filling a bar of (say) 5/4.
We could mischievously claim that anacrusis ('pick-up') bars and any matching 'short' bar at the end of a piece break that rule I suppose!
Answer: It's HEDLEY (who later renamed to Aaron) is correct as always, but there is one exception. Pickup measures can, in theory, be any length, though they almost never go beyond 2/4. If you have some strange burning desire to use breves, and you don't happen to be on a pickup measure, simply change the time signature.
Comment: There are many pieces where the anacrucis is 3 or even 3.5 beats long.
Comment: @Tim I don't see that too often. Maybe we're thinking of different general styles.
Comment: No, unless marked with a different time sig,  the anacrusis cannot exceed the defined measure timing.
Comment: "any length" as long as it's shorter than the length specified by the time signature.


how to get text from edittext inside a dialog

Question: Like the title said how can I get text out of EditText which is found inside a custom dialog?
This is the onCreateDialog method from my dialogfragment:
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();

    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = sharedPref.edit();

    builder.setView(inflater.inflate(R.layout.name_dialog, null))
           .setPositiveButton(R.string.name_ok, new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int id) {
                   EditText nameEditText = (EditText) getActivity().findViewById(R.id.name_text_view);
                   editor.putString(getString(R.string.name_key), nameEditText.getText().toString());
                   editor.commit();
               }
           })
           .setNegativeButton(R.string.name_cancel, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   NameDialogFragment.this.getDialog().cancel();
               }
           });
    return builder.create();
}

I can't get it to work.. I write something in the edittext then i press OK and it just crashes and gives me a null pointer error on this line :
editor.putString(getString(R.string.name_key), nameEditText.getText().toString());

Comment: `(EditText) getActivity()` -> `(EditText) dialog`
Answer: You are looking for the EditText at the wrong View. Its not part of the Activity, its part of the dialog. So check the dialog for the view:
 Dialog dialogView = dialog.getDialog();
 EditText paymentEt = (EditText) dialogView.findViewById(R.id.edittext_payment);

Comment: thanks :) I thought I might need to use something else instead of getActivity() but I tried giving it the fragmentmanager
Answer: Instead of using
EditText nameEditText = (EditText) getActivity().findViewById(R.id.name_text_view);
try using this
Dialog dialg = (Dialog) dialog;
EditText et = (EditText) dialg.findViewById(R.id.search_input_text);
val = et.getText().toString();


How to use tolower or toupper with a special character such as Å

Question: While programming in C, I encountered a problem regarding the tolower and toupper functions.
I want to print an upper case 'Å', and then using the tolower function to print a lower case 'Å' ('å').
First, I declare a variable int x, and give it a value of 143 (because in the ASCII, Å is given that integer). When I then print out x using printf("%c", x) I will get an 'Å'. I also want to print an 'å' (a lower case Å), and to do so, I used the tolower function. However, I do not get an 'å', I only get 2 Å's and I do not understand why. If someone could explain it to me I will be grateful. Also, I am new to programming. Thus I might not use the correct terms at all times, but hopefully you will understand!
Here is my code:
#include <stdio.h>
#include <ctype.h>

int main(void){

int x = 143;

printf("Upper case is %c\n", x);
printf("Lower case is %c\n", tolower(x));

return 0;
}

Output:
Upper case is Å
Lower case is Å
I also tried this, but the output was the same:
#include <stdio.h>
#include <ctype.h>

int main(void){

int x = 143;
int y;

y = tolower(x);

printf("Upper case is %c\n", x);
printf("Lower case is %c\n", y);

return 0;
}

Comment: Unfortunately, `Å` is a variable length UTF-8 codepoint. It is _two_ chars (i.e. `0xC3, 0x85`). So, it can _not_ work with `toupper/tolower` or other `ctype.h` functions. You may need to devise your own conversion table. See: https://en.wikipedia.org/wiki/UTF-8 Also, see [one of] my answer: [Searching letters in the two dimensional array in C](https://stackoverflow.com/a/73887619/5382650)
Comment: Might need `setlocale()` first too.
Comment: Use wide characters instead.
Comment: @CraigEstey it may work if the particular locale has this letter.
Comment: Alexander Jonsson, In the C standard _locale_, `tolower(143)` is 143 when code is ASCII.  Call `setlocale()`.
Answer: Have a look at: tolower

Return value
Lowercase version of ch or unmodified ch if no lowercase version is listed in the current C locale.

Since you get the unmodified value, that means no lowercase version was found.
To fix the problem, a solution might be to set the appropriate C locale (via setlocale).
Furthermore, i would suggest to read the following two articles, since the value 143 is not ASCII but Extended ASCII (and to get a better understanding what setlocale is good for):

https://en.wikipedia.org/wiki/ASCII
https://en.wikipedia.org/wiki/Extended_ASCII


How to reload data on a subview if the model is presented using UIModalPresentationFormSheet

Question: I have implemented a UIModalPresentationFormSheet in my iPad application.  The new view partially covers the sub view and allows the user to make a choice.  This all works great, however...
When the user selects an option I would like to update the underlying view with the new details, but cannot get it to work!
I have tried using setNeedsDisplay or [table reloadData]; in both the viewDidAppear and viewWillAppear methods.
Some code for codes sake:
- (void)viewWillAppear:(BOOL)animated {
    [self updateUserDetails];
    [self.myTableView reloadData];
}

- (void)viewDidAppear:(BOOL)animated {
    [self updateUserDetails];
    [self.myTableView reloadData];
}

- (void)updateUserDetails {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:selection forKey:@"userDetail"];
}

My transition is as follows.  If this line is commented out then the application functions as expected:
myNavigationController.modalPresentationStyle = UIModalPresentationFormSheet;

Any help appreciated, thanks!
Answer: You can set
self.view.autolayoutSubviews = NO;
UI will change your view's size for UIModalPresentationFormSheet. This may be break the reload process.
Comment: "This may be break the reload process." Please expand.
Comment: I don't know the details about the reload process, I mean when use the UIModalPresentationFormSheet style, system will change your view's size, and your view controller will auto layout subviews, include changing the tableview's size, this may take a problem when you invoke reload. We can't read the source code, We don't know what  happened, but this works out for me.
Answer: I think you should put the reloading of data near the code where you detect the selection of the user, not in the viewWillAppear of viewDidAppear.


Is there such a thing as an Add#9 chord?

Question: I understand that the chord formed by the intervals 1-3-5-b7-9 is a 9th chord and that the intervals 1-3-5-9 (omitting the 7) create an add9 chord, but how do you properly define the chord created by the following intervals?
1-3-5-♯9
Is this an add♯9 chord?
Also is there an add♭9? or an add♯11 or add♭11? (ex: 1-3-5-♭9, 1-3-5-♯11 or 1-3-5-♭11)
And while we're at it can you name a chord using add♯13 or add♭13? (ex: 1-3-5-♯13 or 1-3-5-♭13)
Or is this just improper?
I know this may seem obvious, but I have never seen a chord written as "add♯9" so I have to at least ask...  What is the correct way to name these chords?
Edit:
Since a ♯9 is essentially the same thing as a ♭3, you could essentially say that the intervals used to create this chord could be 1-♭3-3-5.  How would you name that? You can't call it M(♭3) can you?
Answer: It depends how you want to look at. Practically if you told someone to play a Cadd#9, they would understand to play the notes C, D#, E, and G. However from a theoretical standpoint, most likely the name would not properly show function as technically there are two thirds in the chord (D# is an enharmonic equivalent to Eb).
I have seen this chord come up though in a different post and I earlier I concluded that it would best show its fucntion as an altered minor major chord. In the example of Cadd#9 the resulting chord would be EmM7#5.
As Tim points out you probably would not see this chord without the seventh which would help smooth out the dissonance and I don't think I've ever seen an altered extension (9,11,13) without some type of 7th. Most of the combinations of notes you list have two notes a half step apart which creates the dissonance above.  He also pointed out why the add b11 and add #13 would not exits. Another thing to note, there are no add13 chords as a 6 chord would be used to notate a basic triad with a 6th.
Back to the main question these are the chords I would think "theoretically exits" although I wouldn't think add would be the best way to represent them:

add#9
addb9
add#11
b6(addb13)
Comment: 'add9' is more commonly found in acoustic guitar stuff.
Comment: What about calling it an add♭3 chord? since technically a ♯9 is the same as a ♭3 and it is being "added" to the major triad, or am I breaking some rules there? I feel like you can't use "add" with thirds... but I haven't seen any rule about it explicitly stated.
Comment: @tjwrona1992 "add" applies only to extensions (9,11,13).
Comment: Okay thanks, I know these may be dumb chords you'd never see, but I've just been trying stacking thirds and seeing if I can name the chord it creates.  It's sort of like a learning exercise. :) I actually have one more if you don't mind.  What would you call 1-♭3-♭5-♭♭7-♭9?  I get that the 1-♭3-♭5-♭♭7 forms a diminished 7th chord "°" for short, but would you be able to label it as °(♭9) or would it be more appropriate (from a theoretical not a practical standpoint) to call it °add♭9?
Comment: @tjwrona1992 why don't you ask that as a new question as other people may have different ways to look at those sets of notes and since it is kind of a new question.
Comment: okay I will, Actually I googled 9th chords and realized that you can have a dominant 7♯9 chord where it doesn't put parenthesis around the "♯9".  If that is an acceptable format that would suggest that you can have a diminished 7♯9 or diminished 7♭9.
Answer: Both answers (by Tim and Dom) are good ones.  To add to these answers, I believe these rules of thumb will help break it down:
"Add" plus only the chord's root means that 7ths, 9ths, 11ths, and 13ths are not implied (strictly speaking).  Only your #9 pitch should be added to the triad.  So for Cadd#9, you would play the C triad plus D#, and that's it.
With no "add", all the decorative notes will be implied up to the number after the root.  If the number is altered (e.g., b13), the lower-numbered decorative notes will not be altered, unless noted.  So for Cb13, you would play the C triad, and Bb, D, and F would be implied, along with Ab.  If the chord needed those lower-numbered notes to be altered, this would be included in the chord symbol (e.g., Cb9b13: C E G Bb Db F Ab).
Sometimes you will see both a number after the root, plus an "add", such as Cmaj7(add x).  In this case, you'll play the C triad, the B, and then add the "x" pitch, but decorative notes between 7 and x will not be implied.
Finally, with 6th chords, much of the above does not apply.  To clarify what I mean, a C6 chord does not follow the same rules as a C13 chord.  Although 6 and 13 are the same pitches, a C6 chord does not imply b7, 9, and 11.  But, "add" can be used for 6th chords, so C6add9 would be the C triad, 6, and 9 (but no b7, etc.).
Answer: Just like yourself, I've never seen it written, possibly because it is so discordant it wouldn't be used much! Yes, the Hendrix chord (A7#9) is similar, but the m7 part makes it more listenable.
Chords are basically 1-3-5 with other appendages marked appropriately, so 1-3-5-#9 would be called Add#9. Incidentally, # can be written as + so it could be Add+9.
The other examples can be similarly written - 'add' anything means just that. There  may also be other ways of voicing or writing the four notes which give a different name. Add b11 will end up sounding like the original major so that won't exist, theoretically or practically. Add    #13 will effectively be a dominant 7.
Answer: Yes, add#9 definitely exists and is common in jazz. Let's go through some background info first.
Chord Nomenclature
The nomenclature of chord naming works like this: If the chord has a 7th of any type (or something from the 7th family like the 6 or b6) then we can have 9ths, 11ths and 13ths in a chord.
ex) Cadd2 is CEG and D. This chord does not have a 7th (or 6th, which is a replacement for the 7th) so we would call the D a 2nd, rather than a 9th.
ex) Cadd9 requires us to have some sort of 7th as well. It could be CEGBD or CEBD (we don't need the 5th) or even CEGBbD, etc.
So, a true Cadd#9 would involve a B of some sort.
Upper Structure(US) Chords
To form all sorts of #9 (or 11th and 13th) chords we can use a concept called Upper Structures. These are a class of amazing chords that are generically defined as a polychord (a dom 7th shell, which is R3b7, plus some combination of 9, 11 and 13). I'm speaking purely from a piano standpoint. We can think of US chords as two chords in two different hands. The left hand(LH) will have the dominant 7th, while the right hand(RH) will have the 9th, 11th and 13th (the "colour" notes).
Here's an example of an US chord with a #9. Let's say we're talking about Cadd#9. The LH will have the notes C E and Bb. The RH will have the rest. #9 is essentially D# (or Eb if we rename it enharmonically). Let's call it Eb as it will be easier to understand the next part. We have 2 avoid notes (notes we're not allowed to include) in any US chord. These are always a perfect 4th from the root (F in this case) and a major 7th from the root (B in this case) because the 4th clashes with the 3rd of our Cdom7 and the B clashes with the b7 of our Cdom7 chord.
To fill in the rest of the chord, choose any major or minor chord that includes Eb, but does not include our avoid notes (F and B). Here's a list:

Eb major (Eb as the root...Eb G Bb)
Eb minor (Eb as the root...Eb Gb Bb)
C minor (Eb as the third...C Eb G)
Ab major (Eb as the fifth...Ab C Eb)

Cb major (Cb Eb Gb) wouldn't work because Cb is the same as B and that's an avoid note. Neither would Ab minor because it contains a Cb (avoid note).
Now that we have these 4 chords, we can combine our LH chord with any of these and we will get a #9 chord. If we use the Eb major chord, since it's a minor 3rd from our root (C), we would call the chord C USbIII (pronounced as C upper structure flat 3). For the Ab major example, we would call the chord C USbVI since Ab is a minor 6th above the root. If we choose C minor we would get C USi. Notice the use of large roman numerals for major chord upper structures and the use of lower case roman numerals for minor chord upper structure chords. Here are some example of what we would call the intervals in these chords:
ex) LH: C E Bb with RH: Ab C Eb gives us a C#9b13 chord a.k.a. C USbVI
ex) LH: C E Bb with RH: C Eb G gives us a C#9 chord a.k.a. C USi
In general, forming chords based on using upper structures allows us to not have to worry about figuring out b9, 9, 11, #11, etc intervals. We can simply view the chord as a polychord.
Using Upper Structure Chords
In jazz, you can use them to replace dominant 7th chords or you can use them as passing chords that are used to get to a certain chord.
Here's an example of a typical "turn around" in jazz using the pattern I - VI - II - V (one, six, two, five). In the key of C major, I is CEG, VI is ACE, II is DFA and V is GBD. In jazz, we would use the 7th versions of those chords: I is CEGA or CEGB, VI is ACEG, II is DFAC and G is GBDF. No jazz musician worth their salt would play GBDF for the V chord, it's just too tame, hence upper structures! For your case, let's say we wanted to have the #9 interval in the chord.
For the V chord, #9 would be A# (G is the root).Let's call it Bb for simplicity. Our avoid notes in this case are 4 (C) and 7 (F#). What major and minor chords have a Bb, but do not contain C or F# (or their enharmonic equivalents which are B# and Gb respectively)?

Bb major
Bb minor
G minor
Eb major

So, we could play the V chord as an Eb/G7 chord, which means we have the notes G B F Eb and Bb. That's a very nice and lush chord to use in place of the typical GBDF!
Check out the wikipedia entry on Upper Structure chords for more details: enter link description here
Answer:
1-3-5-♯9
Is this an add♯9 chord?

Yes.
Adding the sharp doesn't change the way add chords work. The sharp means you're adding an augmented ninth rather than a major ninth. Over a root of C it would be a D♯. Over a root of B it would be Cx a double sharp.
The only things I can think would be a problem are:

Lots of people will misspell it. With a root of C it would be C E G D♯. It would not be C E G E♭. Your edit gives an example of a ♭3, a minor third. That would give you the spelling with E♭. Enharmonically they are the same, if you ignore the octave, but the spelling is different, you should choose the spelling based on what you really intend the harmony to mean.
Someone might not read the add and consider it a ♯9 chord - as in a dominant seventh chord with a sharp ninth. You could avoid that by using add♯2.

Jazz chord symbols don't specify voicing so there is no practical difference between add2 and add9. So, using add#2 could help avoid confusion with a ♯9 chord. The ♯9 chord is popular so if you really want to avoid that probably it's better to use add♯2.


1/4 to 1/8 jack problem

Question: I was planning to record months ago, with my electric guitar, and yesterday I got myself a guitar rig software and bought some 1/4 to 1/8 adapter jack so that I can plug in unto my laptop's mic hole.
Whenever I plug my guitar cable to the 1/4 to 1/8 adapter then to the laptop I can't hear any sound (past the clicking sound you hear) but when I plug the cable almost halfway of the adapter's body (before the clicking sound) I can hear sound when I play and there's some loud buzzing sound involved.
Any explanations as to why this is happening?
Comment: While it's fun to hook stuff together, may I recommend reading up a little bit about electricity:  impedance matching, voltage levels, ground connections, etc. ?  It'll make things easier as you go along.
Answer: You can't just use an adapter to plug your guitar directly into your laptop -- the laptop's sound card is expecting either mic-level or line-level sound, whereas your guitar is a very high impedance signal coming in at a very low level (particularly if your pickups are passive).
It's possible that your adapter is just faulty, but it's far more likely that you will need a special interface to use with your guitar. There are countless options, but for the most basic setup you would just want to google USB guitar cable. They're pretty cheap.
Comment: It really depends on your specific equipment. You need to figure out if your laptop input is mic level or line level, and if your amp has an appropriate output--this would usually be marked "DI Out", and you may need to consult your manual to find out what level it is at. Be very careful with those 1/4" jacks--the same type of cable is occasionally even used to power speakers, and you don't want to go and fry your laptop by accident.
Comment: thanks bro. Additional question, I have an guitar amplifier here, is it possible to plug it into my laptop then record the sound that it produces?
Answer:
when I plug the cable almost halfway of the adapter's body I can hear sound when I play

Sounds like (haw!) a mono-to-stereo problem. Look at the 1/4 inch plug. How many parts? The tip connector and the sleeve right behind the tip? Now look at the 1/8 inch plug. Two sleeves?
If yes, you are shorting out one of the channels. Go back to the shop and look for a 1/4 mono to 1/8 stereo adapter, preferably with a short cord to take the load off the laptop's input.
Comment: +1 -- This is much more likely than the adapter being faulty. You still have the problem of instrument level->mic/line level, though.
Comment: Agreed, this is probably the issue. All of this said, it's likely best to purchase an audio interface.
Comment: I have both mono (i guess) because my cord and adapter both have 1 black strip on the tip.
Answer: If you want to record better sounding guitar tracks, getting an audio interface is the way to go, as others have mentioned.  You also want to think about shielding, interference, and turning off electrically noisy overhead lights.
However, to say "You can't just use an adapter to plug your guitar directly into your laptop" isn't true.  I do this without a problem on my computers, its just not going to give you ideal signal levels. The  problem you might be seeing is that there is a mono-stereo mismatch between your mono guitar cable, your 1/4 to 1/8 inch adapter, and your input on the laptop.  I have both mono and stereo 1/4 to 1/8 adapters and laptops with both mono and stereo input jacks. Depending on my configuration, the input signal is reduced by half because of the way I've hooked it up, i.e. the incorrect conversion of a mono signal results in half of it being lost.
At least, this is the issue that comes to mind when I read your  sentence, "when I plug the cable almost halfway of the adapter's body ... I can hear sound when I play and there's some loud buzzing sound involved."  There are likely multiple issues at play here.

1/4 to 1/8 jack problem


Validate Signature Objective-C

Question: I created an EC public key with OpenSSL:
openssl ecparam -name prime256v1 -genkey -noout -out ec-key.pem
openssl ec -in ec-key.pem -pubout -out ecpubkey.pem

How can I import it (ecpubkey.pem) and use it in my objective-c code to validate a signature?
Answer: One way to use EC keys in iOS is by using 3rd party library GMEllipticCurveCrypto: https://github.com/ricmoo/GMEllipticCurveCrypto. Check it out.
Comment: I'm looking for CSR with ecdsawithsha256 and I followed this library this is only for signature from EC so could you help me that how can I generate CSR (PEM format) certificate via using this library?
Answer: This worked for me:
Creating the key using opens
openssl ecparam -name prime256v1 -genkey -noout -out ec-key.pem

Using openssl to generate der encoded certificate:
openssl req -new -x509 -key ec-key.pem -outform der -out server.pem -days 730

Sign the content
openssl dgst -sha256 -sign ec-key.pem content.txt > signature

Then loading the certificate
NSString *cerPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"server" ofType:@"cer"];
NSData *cerData = [NSData dataWithContentsOfFile:cerPath];
SecCertificateRef certificate = SecCertificateCreateWithData(NULL, (CFDataRef)cerData);

Extrating the public key from the certificate
SecPolicyRef secPolicy = SecPolicyCreateBasicX509();
SecTrustRef trust;
SecTrustCreateWithCertificates(certificate, secPolicy, &trust);
SecTrustResultType resultType;
SecTrustEvaluate(trust, &resultType);
SecKeyRef publicKey = SecTrustCopyPublicKey(trust);

Verifing the signature
uint8_t digest[CC_SHA256_DIGEST_LENGTH];
if (!CC_SHA256([content bytes], (CC_LONG)[content length], digest)) return NO;
OSStatus status = SecKeyRawVerify(publicKey,
                                  kSecPaddingPKCS1,
                                  digest,
                                  CC_SHA256_DIGEST_LENGTH,
                                  (uint8_t*)[signature bytes],
                                  [signature length]);

return status == errSecSuccess;

Validate Signature Objective-C


Unable to open the Web site: http://.. Forbidden

Question: Maybe somebody has already encountered with next problem:
When I try to open Remove Web Site using Visual Studio 2008 TS (File -> Open -> Web Site -> Remote) located on Windows Server 2008 SP2 Enterprise x64 (IIS 7.0) I'm getting next error:
alt text http://img193.imageshack.us/img193/7820/croppercapture1.png
I have access to the server. I added  user 'Everyone' with Full Permissions for that web site root directory, but it's doesn't helped.
Also I have installed FrontPage Server Extensions for IIS 7.0.
Comment: Issues with firewall and/or proxy?
Answer: Being as its IIS7 its complex; there is a page on learniis about it though.
Comment: All other sites on the same server are opens without any problems. But the main one - Forbidden !@#$%^&*


Change folder permission for apache on VPS

Question: Symfony 2 config keeps saying

Major problems have been detected and must be fixed before continuing
  : Change the permissions of the "app/cache/" directory so that the web
  server can write into it. Change the permissions of the "app/logs/"
  directory so that the web server can write into it.

My steps:
rm -rf app/cache/*
rm -rf app/logs/*

chown -R www-data:www-data app/cache
chown -R www-data:www-data app/logs

Via ftp I change permisson on this folders to 777. Apache is runnung as www-data with www-data as group.
But the folders are still not writable and symfony 2 still prints this messages. Any ideas why?
I am running Ubuntu 10.04 Server, Apache 2 and PHP 5.3.x. And since I am on VPS I cannot add acl to mount options.
ls -al app/cache

gives
total 8
drwxrwxrwx 2 www-data www-data 4096 May 25 00:10 .
drwxrwxr-x 6 www-data www-data 4096 May 25 00:10 ..

ls -al app/cache

gives
total 64
drwxrwxrwx 2 www-data www-data  4096 May 25 00:10 .
drwxrwxr-x 6 www-data www-data  4096 May 25 00:10 ..
-rwxrwxrwx 1 www-data www-data 40235 May 23 06:33 dev.log
-rwxrwxrwx 1 www-data www-data 15029 May 23 06:14 prod.log

Command
ps aux | grep apache

gives
root     12012  0.0  0.8 257952 18356 ?        Ss   20:32   0:00 /usr/sbin/apache2 -k start
www-data 12013  0.0  0.2 154324  4836 ?        S    20:32   0:00 /usr/sbin/apache2 -k start
www-data 12019  0.0  1.5 278124 32924 ?        S    20:32   0:00 /usr/sbin/apache2 -k start
www-data 12020  0.2  1.5 278116 33348 ?        S    20:32   0:02 /usr/sbin/apache2 -k start
www-data 12171  0.0  1.5 278380 33172 ?        S    20:37   0:00 /usr/sbin/apache2 -k start
www-data 12173  0.2  1.5 277568 32740 ?        S    20:37   0:01 /usr/sbin/apache2 -k start
www-data 12175  0.0  1.5 278392 33396 ?        S    20:38   0:00 /usr/sbin/apache2 -k start
www-data 12178  0.3  1.5 277604 32816 ?        S    20:38   0:01 /usr/sbin/apache2 -k start
www-data 12204  0.2  1.5 277832 33048 ?        S    20:39   0:00 /usr/sbin/apache2 -k start
www-data 12210  0.5  1.8 283748 38960 ?        S    20:40   0:01 /usr/sbin/apache2 -k start
www-data 12212  0.3  1.5 277832 33088 ?        S    20:40   0:00 /usr/sbin/apache2 -k start
www-data 12214  0.2  1.5 278132 33352 ?        S    20:40   0:00 /usr/sbin/apache2 -k start
www-data 12215  0.0  0.5 258216 10780 ?        S    20:40   0:00 /usr/sbin/apache2 -k start
www-data 12223  0.0  0.5 258084 10676 ?        S    20:42   0:00 /usr/sbin/apache2 -k start
root     12227  0.0  0.0   6164   664 pts/0    S+   20:44   0:00 grep apache

Any ideas how to deal with this problem?
Comment: Can you add the results for `ls -al app/cache` and `ls -al app/logs/` to your opening post??
Comment: ok see my update
Comment: Are you sure the directories you have fixed permissions for is the same directories targeted by the application?
Comment: Well the message says clearly that cache and logs folders have no write permissions and there are located in the app directory of symfony2 installation. So I cd in /var/www/mysite/ and change permissions...
Comment: what is your apache vhost config? is php running as cgi or as mod_php?
Comment: It is running as mod_php
Answer: First, as others have said, are you examining the right files?
The error message from Symfony is poor. It should specify the full path of the files it cannot access. You can try using strace of lsof to find the files.
Second, is php running as www-data?
If you're using mod_php, then php runs as the user running apache. But have you checked using ps or top what that user is?
Third, are the old files held open somehow?
In UNIX a file can be open even after removal, and only gets removed completely after all open file handles are closed. Apache/php restart or reboot should take care of this.
Fourth, are you running apparmor/selinux?
Try disabling them first.
Comment: Apache is running as www-data. I restarted apache. apparmor/selinux are not installed. Still same problem...
Comment: are you using mod_php? or some other method of running php?
Answer: What are the permissions on /var/www/mysite? It needs to be at least executable by the www-data user for that user to access its contents:
$ chmod o+x /var/www/mysite

Comment: Command does not help, still same problem
Answer: The problem is that plesk is messing up permissions. I removed the domain from plesk and created my own vhost. Now everything works just like expected.
Answer: Maybe some folders above has no appropriate rights. Check permisions for /var and /var/www.


Unable to logout php

Question: When an admin is logged in , the admin will have a admin page on the nav bar.
When the member is logged in, the member will have a profile page on the nav bar.
However, lets say when the admin logged out, it will goes to a logout page hat says logged out and when the administrator goes back to the home page, the administrator is still logged in and the admin page is still on the navbar.
This is my codes for the login and logout.
<?php
//checks if login session variable exist? If it does, display Logout
session_start();
if(isset($_SESSION['login']) && $_SESSION['login']!="") {
    //link to page logout.php and displays the word Logout + username
    echo"
Logout ".$_SESSION['login']."
";
    if(isset($_SESSION['login'])&& $_SESSION['usertype'] !="admin") {
        echo ("
Profile
");
    } else {
        echo ("
Administrator
");
    }
    if($_SESSION['login'] == "") {
        header("Location:login.php");
    }
    if($_SESSION['login'] != "" && $_SESSION['usertype'] =="member") {
        header("location:home.php");
    }
} else {
    //else link to pagelogin.php and display the word Login
    echo("
Login
");
}
?>

How do I rectify the error so that when the user is logged in the user can log out successfully.
Comment: "when the administrator goes back to the home page, the administrator is still logged in and the admin page is still on the navbar." Means admin go back from browser back button link?
Comment: this may not be an answer to the question, but `if($_SESSION['login'] == "")` will be never true because it is inside a `if($_SESSION['login']!="")` test
Answer: in your logout.php file you just need to do the basic:
<?php

session_start();

session_destroy();

header("Location: pagelogin.php"); // or whatever your login file is called
?>

Comment: That is good and it works but how do i still show the text "you have logged out successfully " on the logout page before directing back to the home page?
Comment: You don't have to do it exactly the way I suggest with the header location. You could make logout divert to loggedout.php with a message. But generally you'd make it so if logged in a user cannot see the login screen.
Comment: If you're happy with the answer please mark this as resolved.
Answer: on logout you have to destroy user's session:
in your logout page write code
session_destroy();

2nd method is to remove data from your session variables,
in your logout page write code
$_SESSION['login'] = '';
$_SESSION['usertype'] = '';
session_destroy();

after destroy session and session variable send him back to login page
header('location:login.php?msg="You Have successfully logout....!!"');

Answer: Code for destroying session, logout conditions etc is required but You dont have control over browser's back button, you have to write a code to clear cache and its max-age etc. search on below mentioned details. you might need to add more code in html header / php header.
<?php

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>

You can check this link might help How to prevent Browser cache for php site

Unable to logout php


NSTimer continue during sleep mode

Question: I have a timer app which uses a NSTimer to track minutes. How can I keep the timer going, even when the device is put into sleep mode? Thanks!
Comment: You need to update your question with information about why you think you need the timer to keep going when the device is asleep. Most likely there is a better solution but it depends on what you need this for.
Answer: Adjust After Wake Notification
Scheduled NSTimer instances will halt during sleep. Your application needs to respond to the NSWorkspace's wake notification and adjust its timers.
If you do not respond to wake notifications, your timers will resume but without accounting for the time spent asleep.
See Apple's technical note QA1340 Registering and unregistering for sleep and wake notifications for getting the appropriate notifications.
Example
Consider this situation:

Create a timer to trigger in 5 minutes
Wait 1 minute
Put the computer to sleep for an hour
Wake the computer
The timer resumes upon waking
The timer triggers 4 minutes after waking

From the timer's perspective, five minutes has passed by. Note the language used by NSTimer, it uses relative durations rather than absolute times, scheduledTimerWithTimeInterval:invocation:repeats:.
Comment: What happens if I don't respond to wake notifications, as I am doing now?
Comment: Your timer will resume but not account for the time spent asleep.
Comment: Could I use something like NSDate to track and add the time spent asleep?
Comment: Yes, NSDate is the recommended way to get the current date and time. You will need to reschedule your timer after wake.
Answer: Take a look at this class, which handles sleep/wake for you with the "Hourglass" behavior: https://github.com/jmah/MyLilTimer
Answer: You can use wall time. Specifically, I recommend you to check out DispatchSourceTimer.schedule(wallDeadline:) or DispatchQueue.asyncAfter(wallDeadline:)
This script is useful to understand how they behave. Run this from a Swift playground, set your mac to sleep for 30 seconds and check the results. Also, do the same experiment without putting your mac to sleep.
import Foundation

// Pauses on sleep
let monotonicDispatchSourceTimer = DispatchSource.makeTimerSource(queue: DispatchQueue.main)
monotonicDispatchSourceTimer.schedule(deadline: DispatchTime.now() + 30)
monotonicDispatchSourceTimer.setEventHandler(handler: {
    print("Hello from monotonic makeTimerSource")
})
monotonicDispatchSourceTimer.resume()

// Pauses on sleep
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 30) {
    print("Hello from monotonic DispatchQueue.asyncAfter")
}

// Pauses on sleep
class TimerWrapper: NSObject {
    var timer: Timer?

    func run() {
        timer = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: false)
    }

    @objc private func fireTimer(){
        print("Hello from Timer.scheduledTimer")
    }
}

let timerWrapper = TimerWrapper()
timerWrapper.run()

// Doesn't pause on sleep
let timer = DispatchSource.makeTimerSource(queue: DispatchQueue.main)
timer.schedule(wallDeadline: DispatchWallTime.now() + 30)
timer.setEventHandler(handler: {
    print("Hello from DispatchSourceTimer with wall deadline")
})
timer.resume()

// Doesn't pause on sleep
DispatchQueue.main.asyncAfter(wallDeadline: DispatchWallTime.now() + 30) {
    print("Hello from DispatchQueue.asyncAfter with wall deadline")
}

Answer: You can actually use dispatch_walltime() which uses the wall clock instead of registering for sleep/wake notifications with NSTimer.
Some documentation here: https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/GCDWorkQueues/GCDWorkQueues.html

NSTimer continue during sleep mode


How to change views field value using a hook

Question: I want to change drupal 8 views field value before displaying.
I am using below hook_views_pre_render
function MYMODULE_views_pre_render(ViewExecutable $view) {
  if ($view->id() == "demo1" && $view->current_display == 'page_demo1') {
     foreach($view->result as $value){
      $value->_entity->set('created', $value->_entity->get('created')->value . '-' .($value->_entity->get('changed')->value - $value->_entity->get('created')->value));
     }
  }
}

I want to time difference between created and changed date time.
but its not working...
Answer: You can convert them to int and work with them as integers.
For example if you want to set created to changed - created.
Here is a working example:

use Drupal\views\ViewExecutable;

function MYMODULE_views_pre_render(ViewExecutable $view){
  if ($view->id() == "views_id" && $view->current_display == 'view_display') {
    foreach ($view->result as $value) {
      $created = (int) $value->_entity->get('created')->value;
      $changed = (int) $value->_entity->get('changed')->value;
      //- If you want for example to set created time with changed -
      created.
      $value->_entity->set('created', $changed - $created);
    }
  }
}


Question about writing proofs for limit

Question: I intuitively understand proof with limits, but I'm not sure on how to write a formal proof for this example.
For each $n \in \mathbb{N}$, let $a_n$, $b_n$ be real numbers. Also, let $a_{\infty}$, $b_{\infty}$ be real numbers. Suppose that $\lim_{n\to \infty} a_n = a_{\infty}$ and $\lim_{n\to \infty} b_{n} = b_{\infty}$.
Prove that $\lim_{n\to
 \infty} (a_n b_n) = a_\infty b_\infty$.
Comment: $a_nb_n-a_{\infty}b_{\infty}=a_n(b_n-b_{\infty})+(a_n-a_{\infty})b_{\infty}$
Comment: Do you mean $\displaystyle\lim_{n \to \infty}(a_nb_n) = a_{\infty}b_{\infty}$ or $\displaystyle\lim_{n \to \infty}(a_n+b_n) = a_{\infty}+b_{\infty}$?
Comment: I meant the former one. I changed it.
Comment: Scroll down to "Proof of the Product Rule for Limits" http://en.wikibooks.org/wiki/Calculus/Proofs_of_Some_Basic_Limit_Rules
Answer: You want to show that $\lim_{n \to \infty} a_nb_n = ab$, where $\lim_{n \to \infty} a_n = a$ and similarly $\lim_{n \to \infty} b_n = b$. By the Triangle Inequality, we have that
\begin{align}
|a_nb_n - ab| &= |(a_nb_n - a_nb) + (a_nb - ab)| \\
&\leq |a_n(b_n - b)| + |b(a_n - a)| \\
&= |a_n||b_n - b| + |b||a_n - a|.
\end{align}
Since $\lim_{n \to \infty} a_n = a$, given $\epsilon > 0$, there exists $M_1 > 0$ such that $|a_n| < M_1$ for all $n \in \mathbb{N}$. Set $M = \sup\{M_1,b\}$. Then we have
$$|a_nb_n - ab| \leq M|b_n - b| + M|a_n - a|.$$
Now from the convergence of the sequences $(a_n)$ and $(b_n)$, we have that if $\epsilon > 0$ is given, there exist $K_1,K_2 \in \mathbb{N}$ such that if $n \geq K_1$, $|a_n - a| < \epsilon/2M$ and analogously, if $n \geq K_2$ then $|b_n - b| < \epsilon/2M$. Set $K = \sup\{K_1,K_2\}$.
What can you conclude on the quantity $|a_nb_n - ab|$ if $n \geq K$?

Question about writing proofs for limit