Why was the letter Q chosen in Q-learning?

Question: Why the letter Q was chosen in the name of Q-learning?
Most letters are chosen as an abbreviation, such as $\pi$ standing for policy and $v$ stands for value. But I don't think Q is an abbreviation of any word.
Comment: In my metaphorical understanding, Q is a function that associates a quantity (call it reward, cost or whatever else is being optimized) for an action in a given state.
Comment: @sycorax the original question framed implied an understanding of Q-learning and in order to offer an explanation, it would help to add context. The OP would be lost with any explanation without establishing a grounding.
Comment: Does the metaphorical Q = Quantity help? I think of it as a quantification of action given states
Answer: I'm sorry to disappoint everyone, but Q doesn't stand for anything :)
Q-learning was proposed by Watkins in his PhD thesis in 1989, see p.96. The Q in the equation on that page is updated in certain way at each step. The Q is the expected return from action at a given state, see the definition of Q on p.46. The return is in a economic or game theory sense, i.e. discounted probability weighted rewards, not a computer science term like a return from a function.
Notice, how he already used P for probability and R for reward, so he grabbed Q for the return. That's it. There's no deeper meaning for a choice of a letter Q.
Comment: No deeper meaning but it *is* a meaning (that Q fits with P and R in the alphabet) and stands for *something*.
Comment: @MartijnWeterings It's not a meaning at all. It's a purely syntactical choice of letter, with no semantic considerations whatsoever.
Comment: Sure, there may be few semantic considerations (and this might be debated because differences between latin or greek letters, letters in different positions of the alphabet, or uppercase versus lowercase might form a gray area between syntactics and semantics). I consider the choice of Q as 'meaningful' because the form of the letter (Which is somewhat arbitrary) does express to some extend the meaning of the variable/parameter. The meaning relates to the choice of letter. There would not have been a good choice when u or v would have been chosen, or i,j,k or x,y,z or $\alpha, \beta, \gamma$.
Comment: @MartijnWeterings, Q also sounds like a *queue*, which brings somewhat relevant connotations too
Comment: @Aksakal, that might have been reinforcing the use of Q. But, I don't think it is strong. I don't know much about this topic, but in a quick overview of that thesis to me it seems very plausible that the letter $Q$ has been used for a quantity like  $\sum_i R_i P_i$ or $\sum_i V_i P_i$. Eventually 'some name' like 'action-value' was given to it but those letters used in that thesis seem to stick much more to the alphabet. E.g. $f$ $g$ $h$ for functions $x$ $y$ for variables $V$ $U$ for value function and it's approximate. , etc.
Comment: @MartijnWeterings, I meant similarly to "queue the music," you say "queue learning"
Answer: The reason Q-Learning is called so because it uses Q values to form it's estimates. The usual learning rule is, $Q(s_t,a_t)\gets Q(s_t,a_t)+\alpha(r_t+\gamma \times \max_{a} Q(s_{t+1},a)-Q(s_t,a_t))$ and it should be clear why it is called Q-Learning.
But the actual question in my view is why Q-Learning is called so. Though there does not seem to be a satisfactory answer, this link mentions that Andrew Barto, who is one of the founders of Modern Reinforcement Learning, thinks that $Q$ stands for Quality, called so because it characterizes how good the result of pulling an arm would be.
Comment: Read that thesis and tell me how "quality" makes a sense in the context of the expected return
Comment: Though I agree with you, the thesis was written after Watkins consulted Andy about a number of things. Andy may have had a better idea than you think he does.
Comment: Quality doesn't even exist as a distinct concept in learning. You can use the word in its usual sense from English, of course. The expected return, on the other hand, is very well defined in game theory, there's no need to dilute it by attaching vague concepts such as quality. You're not maximizing quality, you're maximizing discounted rewards under the suitable probability measure. If you want to be a little more broad, then you can maximize the utility.


Ficheiro .jar consola de comandos - programa cliente servidor

Question: Desenvolvi um programa do género cliente servidor, em que possuo dois mains:

um para correr o servidor
outro para correr varios clientes

Para extrair o ficheiro .jar do ecplise faço export runnable Jar File.
Consigo correr na consola de comandos quando tenho só um main mas e com dois mains? É que quando faço o export tenho de clarificar o main para correr o programa.
Não faz sentido juntar os dois mains uma vez que só necessito de correr o servidor uma vez. Preciso sim é de correr o cliente várias vezes
Comment: Não seria o caso de apenas executar cada jar em um janela do CMD diferente?
Comment: Olá rrr, nao sei se entendi direito a sua necessidade, porém me parece que você tem duas classes *main*, uma para o cliente e outra para o servidor dentro do mesmo jar correto? Seu problema é que você quer selecionar qual das classes rodar, é isso? Se sim você pode fazer isso colocando o jar da aplicação no classpath e especificando a classe a ser executada. Veja [o primeiro comando desta resposta](http://pt.stackoverflow.com/a/167772/100).
Comment: @AnthonyAccioly obrigado pelo interesse. Já sei como solucionar o problema vou postar a resposta dê uma vista de olhos
Answer: Basicamente quando existe um programa do género cliente-servidor a solução na criação de um runnable jar com dois mains é separar e criar dois jar's à parte. Um jar com o servidor, e outro jar com o cliente. Deste modo é possível lançar o servidor e vários clientes ligados a esse servidor porque eles ligam se pela mesma server socket.
Comment: Essa é a melhor solução no longo prazo, até porque em boa parte dos casos o código todo não  é reaproveitável entre cliente e servidor, não vale a pena "distribuir" um jar com o código do servidor para um cliente e vice-versa. Do ponto de vista de evolução é melhor ter módulos separados. Dito isso, para um projeto simples não há nada de errado em usar algo como o [maven-assembly-plugin](http://maven.apache.org/plugins/maven-assembly-plugin/) para gerar dois jars executáveis com MANIFESTs difetentes para o mesmo módulo.
Comment: sim exatamente assim até ficam divididos os programas


how to get $_SESSION value in cakephp

Question: I am setting up a user session from a core php app that is located in example.com/corephp/, now I want to redirect this user to example.com (the main site) which is in cakephp.
How can I retain the user session from the core php app to cakephp app?
I triend setting $_SESSION['user'] = someone and $_SESSION['token'] = token from core php app and tried to retrieve that value from cakephp but it didn't work.
I tried to google for this but no proper answer that could work.
Thanks in advance.
---------------------- edit
I have tried adding session_name('CAKEPHP');  to the core php app.
As well as tried to reduce the security level of my cake app from medium to low.
Comment: did you try `print_r($this->Session->read());` ?
Comment: yes, I see config array with userAgent, time and timeout values
Comment: thanks for your efforts guys, so the theory say that if set $_SESSION in core php app and they are on the same server, I should get it in cake as it is from $_SESSION?
Answer: Didn't test, but try this.
In your corephp app:
$_SESSION['Auth']['User'] = $someone;

My reasoning is that it will set the $_SESSION, but maybe CakePHP doesn't recognize it for some reason. So we set it the right way using Cake's API:
In CakePHP
$this->Session->write('Auth.User', $_SESSION['Auth']['User']);

Comment: I get $_SESSION['user'] as null in your example
Comment: @happyhardik: $_SESSION['user'] is null in CakePHP?
Comment: yes, I am setting the variable as $_SESSION['username'] (to be exact) from core php app and it is undefined in my cake app
Comment: Are the two systems using the same session name? I.e. do they use the same session cookie (same session ID)?
Comment: I tried doing something like this session_name('CAKEPHP');  in my core php app but it didn't help
Comment: Updated the answer. Maybe it helps. Additionally, here's a similar question: http://stackoverflow.com/questions/3877341/cakephp-session-keeps-getting-reset
Comment: Finally I figured it out, the request that my core php app received was through ajax and through a proxy server (for cross domain) which changed the session for user and proxy server :)
Answer: Always use the session wrappers. thats what they are there for
in the controller:
http://book.cakephp.org/2.0/en/controllers/components.html#using-components
in the view:
http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html
everywhere else:
http://book.cakephp.org/2.0/en/development/sessions.html#reading-writing-session-data
never ever access it using $_SESSION and you should be fine (cake inits the session for you and takes care of a lot of things behind the hood).
if you share the session make sure you set the session name equally. both should also use the same session type (php probably).

how to get $_SESSION value in cakephp


Equivalent formulas and equivalent statements in logic.

Question: I am reading a book titled "How to prove it", and I am learning about equivalences. I could be completely wrong here, so thanks for the patience and the help.
From the book, the absorption law looks like this:
Absorption law:
P ∨ (P ∧ Q) is equivalent to P.

My question regarding this.
Say I have two statements:
P: It is dark.
Q: It is cold.
P ∨ (P ∧ Q) would mean:

It is either dark, or dark and cold, or both.

Which seems different from simply P:

It is dark.

Equivalent seems to mean the following here:
The validity of the original statement (P ∨ (P ∧ Q)) depends on P alone, all other parts of the statement (like Q) don't change the validity.
And I would add, that by applying the absorption law, the resulting (simplified) form shouldn't be mistaken for having the same meaning as the original statement.
However, this seems to be a bit different in case of other equivalences:
¬¬P is equivalent to P in a sense that it is a different (simplified) form, without loosing the meaning of the original statement.
Or in case of De Morgan's law:
¬(P ∧ Q) is equivalent to ¬P ∨ ¬Q. The latter from still produces a statement that can be interpreted as having the same meaning:

It is not both dark and cold.

And

It is either not dark, or not cold, or neither dark nor cold.

Is it the case, that some laws or modifications can be used to simplify statements, whereas some can only be used to analyze certain relationships within the original statement?
Comment: A statement is either true or false. And if two statements produce the same result when taking the same inputs, then they are logically equivalent, no matter what information is contained in the statement.
Comment: I'm not sure about your premise. To me, "it is dark" and "it is dark, or dark and cold, or both" seem to have exactly the same content.
Comment: @AlexKruckman I am thinking, that according to the second statement, it is possible, that it is cold. Whereas the first statement ("it is dark"), doesn't have information about whether it is cold.
Comment: If I tell you "it is dark", isn't it possible that it is cold?
Comment: @AlexKruckman The statement "it is dark, or dark and cold, or both" includes the concept of cold. We know that according to the statement, it could be cold. "it is dark" does not include the concept of cold, and we don't know anything about it, we don't know if it could be cold or not, maybe it is never cold.
Comment: "It is dark, or dark and the moon is made of cheese, or both" is true whenever it is dark. Mentioning the concept of the moon being made of cheese does not suggest that the moon might be made of cheese (feel free to substitute any proposition that is never true for "the moon is made of cheese" in this example).
Comment: @AlexKruckman I think what was confusing for me, is that some information may be left implicit in a statement, after applying certain laws. I was completely wrong in my previous comment, too, as I got carried away by my intuitions from ordinary language (as you pointed out in your answer). Thanks a lot!
Answer: "$\varphi$ is logically equivalent to $\psi$" means that in any model, $\varphi$ is true if and only if $\psi$ is true. In the case of propositional logic, a model is just an assignment of a truth value to each basic proposition (i.e. a row of a truth table).
In the case of $P$ and $P\lor(P \land Q)$, it is easy to check that these are logically equivalent. If $P$ is true, then by the meaning of $\lor$, $P\lor (P\land Q)$ is true. If $P$ is false, then $(P\land Q)$ is false by the meaning of $\land$. Since also $P$ is false, $P\lor (P\land Q)$ is false by the meaning of $\lor$. We've shown that $P\lor (P\land Q)$ is true whenever $P$ is true and false whenever $P$ is false, so they are logically equivalent.
You should try to avoid allowing intuitions from ordinary language to creep into your understanding of logical words in mathematics. Words like "and", "or", "implies", and "equivalent" all have precise meanings in mathematics, which do not always match the informal and imprecise ways we use these words in ordinary language.


How to display modal after a delay?

Question: I want that if a user stays on my website for around 20 seconds, a modal asking for user's name and email address will be displayed. I have fetched id of the modal div and stored it in the function myFunction(). The main problem here is nothing gets displayed after 20 seconds.
Following is my code:-

New message

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                      ×
                    </button>

                    <form action="MessageServlet" method="post">

                        Recipient:
                        <input type="text" class="form-control" id="recipient-name" value="firstname.lastname@example.com" readonly="readonly">

                        Your Email ID:
                        <input type="text" class="form-control" id="email-name" name="email-name" placeholder="Email ID">

                        Message:
                        <textarea class="form-control" id="message-text" name="message-text"></textarea>

                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Send message</button>
                    </form>

My aim here is, when a user enters a value within the modal fields and clicks OK, user's data will be sent to the email servlet.
Thank you
Comment: use modal toggle after 20 sec interval
Comment: because you are not doing anything with your modal after the interval. this code here `document.getElementById("exampleModal");`
Comment: So, how can I forward it to my servlet?
Answer: You can see below example. Replace second and modal code as per your need.

setTimeout(function() {
    $('#myModal').modal('toggle');
}, 200);
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

Some text in the modal.

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

How to display modal after a delay?


Prevent email change on password reset laravel 5.7

Question: How I can prevent email change on password reset page in Laravel?
I have input email:

                            <input id="email" readonly type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ $email ?? old('email') }}" required autofocus>

                            @if ($errors->has('email'))

                                    {{ $errors->first('email') }}

                            @endif

I pasted attribute readonly, but input email is empty. How I can pass email user and prevent change email for it?
In ResetPasswordController I have:
 public function showResetForm(Request $request, $token = null)
{
    $email = //getUserEmail ?
    return view('auth.passwords.reset')->with(
        ['token' => $token, 'email' => $request->email]
    );
}

/**
 * Get the password reset validation rules.
 *
 * @return array
 */
protected function rules()
{
    return [
        'token' => 'required',
        'email' => 'required|email|exists:users,email',
        'password' => 'required|confirmed|min:6',
    ];
}

How I can change $request->email on current user email, who reset password?
Comment: if you remove `readonly`. do you able to get value then ?
Comment: @H45H nope... .
Answer: If i am getting your question well you want to show email but in readonly only format for reset password page. i am suggesting you some way for it. feel free to use any.
Solution 1 : inside, ResetPasswordController -> showResetForm()
    $password_resets = DB::table('password_resets')->get();
    foreach($password_resets as $password_reset)
    {
        if (Hash::check($token, $password_reset->token)) { // checking hash match with requested token
            // here if hash match with token
            $email = $password_reset->email;
        }
    }

Here, we are looping through password_resets table and checking if reset password token matches with actual hashed token in table. you can easily use $email inside reset.blade.php  like so :
<input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ isset($email) ? $email : '' }}" required readonly>

Solution 2:
At the time of sending password reset email you can pass email as base64_encode and can access it  using base64_decode at the time of reset password.
Hope, this helps you. enjoy coding :)


Why does Axios not seem to receive the Access-Control-Request-* headers even though they are being sent?

Question: Background
I am currently building a web service using Serverless and AWS for the backend and Axios for calling the backend resources from a ReactJS frontend.
Since the backend and frontend components are published under different domains, I need to use Cross-Origin-Resource-Sharing (CORS) to circumvent the Same-Origin-Policy that most browsers enforce by now.
The problem
Unfortunately, even though I have configured all of the Access-Control headers on the backend side (in AWS Api Gateway), I still get the error
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com/internal/role. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

The data
Now, the issue I have is that when calling the OPTIONS call (not as a preflight but as a "standalone" call) on one of my resources with Postman, I receive the correct Access-Control headers. However, when issuing that same request with Axios, I do not seem to receive those headers which makes me think it might be an issue with Axios.
These are the Postman headers I receive when making the OPTIONS call:
 - Date: Fri, 26 Jun 2020 12:01:18 GMT
 - Content-Type: application/json
 - Content-Length: 0
 - Connection: keep-alive
 - x-amzn-RequestId: <some ID>
 - Access-Control-Allow-Origin: https://example-gui.com
 - Access-Control-Allow-Headers: Origin,Accept,Content-Type,X-Amz-Date,Authorization,X-Api-Key,x-requested-with
 - x-amz-apigw-id: <some ID>
 - Cache-Control: max-age=600, s-maxage=600, proxy-revalidate
 - Access-Control-Allow-Methods: OPTIONS,POST
 - Access-Control-Allow-Credentials: true

And these are the headers Axios tells me it receives when making the OPTIONS call:
 - cache-control: max-age=600, s-maxage=600, proxy-revalidate
 - content-length: 0
 - content-type: application/json

However, when using Firefox's dev tools, I can see that all headers are actually returned as seen in the Postman list. I don't know whether Axios just hides these fields or does not process them for some reason.
Unfortunately, I have no information about data returned by the actual POST call since it just throws the mentioned exception.
The Code
The Postman call is just a basic call to the respective URL with the OPTIONS method that only has one additional header (Authorization) so I'm not going to go into that any further.
The Axios call originates from the URL https://example-gui.com/#/ and is made like this:
const fullResponse = (response: AxiosResponse) => response;

const backendRequests = {
   ...
  options: (url: string, header: {}) =>
    axios.options(url, header).then(fullResponse),
  ...
};

const loginRequests = {
  getUserRole: (accesstoken: string) =>
    backendRequests.options(
      "https://example.com/internal/role",
      { Authorization: `Bearer ${accesstoken}` }
    ),
};

And then I print the result like this:
try {
  await agent.loginRequests
    .getUserRole(this.accessToken)
    .then((response) => {
      console.log(response); // <-- Printing the results
      <...>
    });
} catch (error) {
  console.log(error);
}

Which is where I got the list within the "The data" segment from.
The questions
Is it possible that this is a bug within the Axios framework, is it a configuration based issue where the Axios call has to be set up differently beforehand to receive all of the headers or does the problem lie somewhere else?
How can I manage to get through the Same-Origin-Policy with all of this information in mind?
Comment: Have you used browser dev tools to see the OPTIONS call?  Also, the domain is a very important detail.  Instead of redacting, could you change the values but show the pattern of domain and ports involved?  Ex. `example.com`
Comment: @DavinTryon I just checked it with the browser dev tools and Firefox seems to receive all headers returned by the backend. I have also edited the question to include your example.com advice. There are no non-standard ports used.
Comment: What does your POST call perform? Basically you need to send the response back to your frontend within 29 seconds. So if you aren't responding before 29 secs you may receive a CORS error.
Comment: @SaiSreenivas The call returns in about a second, so that is unfortunately not the issue.
Also, could you quote your source on this, please? As far as I know the only aspect of CORS that takes timing into account is when using the Access-Control-Max-Age header which only affects inter-call caching of the CORS headers.
Comment: If you're not manually setting the headers on API gateway instead inserting them in the code itself causes the CORS error if response exceeds 29 seconds. btw you can view more about it [here](https://stackoverflow.com/questions/31973388/amazon-api-gateway-timeout) .Thanks
Comment: As you are saying the function replies within a second. I suggest you put the headers in the code itself rather than manually setting at the API gateway.
Comment: Ah I think I understand, you are referring to the overall execution time limit of the API Gateway. Thanks for clarifying.
I just tried returning the CORS headers both as part of the integration response from API gateway in the preflight response and from the actual lambda code as well but unfortunately, that did not seem to help. The exception remains the same. In fact, The code is never executed in the first place, which is because the request is blocked by the browser before it reaches AWS, I suppose...
Comment: I have the exact same issue as you do. Please tell me if you figured it out yet!
Answer: Have you checked if you are sending all the headers requested from backend service under Access-Control-Allow-Headers header from Axios. Maybe limit the number of headers to
Access-Control-Allow-Headers: Accept,Content-Type
and check if CORS is working.
You cannot use credentials if Access-Control-Allow-Origin uses *. You will have to specify the protocol + domain + port.
Access-Control-Allow-Origin wildcard subdomains, ports and protocols
Cross Origin Resource Sharing with Credentials
Use of * is too open and would defeat the use of credentials. So set http://domain:port as the allow origin header further.
Comment: I have now checked the following cases:
- Adding all headers sent with the Axios request to the CORS configuration in the backend
- Allowing just those headers with CORS that are requested in the "Access-Control-Request-Headers" field of the preflight request

Both attempts have unfortunately ended with the same exception. I have also restricted the * to https://example.com (I have to redact the actual domain but there are no unusual ports involved)
Do I need to specifically add the 443 port when denoting the URL with https:// ?
Comment: After some trial and error, I found out that it is actually possible to use the * in conjunction with Access-Control-Allow-Credentials == true, although for a private API that really doesn't make much sense, as you noted.


Which came first: the dot or the tie?

Question: In considering the question of the benefits of dots versus ties for extending note values, I got to wondering about the origins of those two notations.

Did one emerge before the other?
For what purpose(s) were they first developed?

There is an excellent description of the emergence of the dot in Original sources for note-increment dot. So I think my question boils down to:
What is the history of the tie, and what relationship does that history hold with the dot, if any?
Comment: ... That 1655 Playford book shows both dots and ties, and demonstrates why man at least cannot live by dots alone: Sometimes you're forced to hold a note across a barline. (Although the 1703 edition says that sometimes they would put the dot itself in the next bar, but use a tie to make the intention clear.) I don't have time at the moment to search out the actual headwaters of the tie, but I imagine they come along hand in hand with the barline.
Comment: @AndyBonner I'm quite sure dots are older. Here we see them in 15th century work: https://en.wikipedia.org/wiki/Johannes_Ockeghem#/media/File:Chigi_codex.jpg and I wouldn't be surprised if they were in use much earlier. Some more hints: ties are often used to notate 1. syncopation or generally more complex rhythms, 2. notes going over bar lines. Barlines themselves are relatively young! One more thing to consider: if a notation is used for multiple centuries, its use may change and evolve.
Comment: One only-somewhat-off-topic note: The 1703 edition (the 15th) of a John Playford book advertises "The new ty'd note." It turns out, though, that it uses the word "tie" to mean not only what we do but also the beaming of eighth notes (see p 19 and following [here](https://s9.imslp.org/files/imglnks/usimg/d/da/IMSLP83328-PMLP169945-Playford.pdf). Note that the preceding page addresses both dots ("The *Prick of Perfection*, or *Point of Addition*") as well as ties across bar lines. This is by no means anything new; both appear in the 2nd edition at least, almost a century earlier. What is new...
Comment: ... Is that Playford had taken until 1703 to manage to effectively beam 8th notes together using movable type. Movable type seriously interfered with the ability to use slurs coherently. The German printers of the 1620 Capriccio Stravagante could do little more than scatter equal-sized slur-shapes around meaninglessly (see [pp 72 ff](https://libres.uncg.edu/ir/uncg/f/Bonner_uncg_0154D_11176.pdf), even though the groundbreaking Venetian printing houses had decades earlier succeeded in aligning them to starting and ending notes ...
Comment: ... (and they gave up on the moveable-type experiment and went back to engraving entire plates long, long before Playford was still scratching his head about how to beam). What's the point? Just that evolution of musical notation is always entangled in the evolution of the physical technologies employed. I'm pretty sure notes were beamed in woodblock printing way earlier, but were temporarily forced to show even a run of 32nd notes as individual flags for about a century, just because of the technological constraint. One other point: ...
Answer: This is a fascinating question, and although I don't have a definite source that says this or that, I believe I've triangulated the data as best we can. For simplicity's sake, I'll refer to some entries in the Harvard Dictionary of Music.
The entry for dotted note isn't all that helpful, but the entry for tie tells us that "[t]he advent of the tie coincides with the advent of the bar line." When considering the bar line entry, we read that "the earliest [instance is in] Faenza, Biblioteca comunale, 117, from ca. 1400."
With this, let's assume that the tie appeared, at the earliest, around the year 1400.
The earliest dot notation that I know of is from Machaut; I found this example in his manuscripts from MS E, 131r:

Machaut, however, died in 1377, meaning that these manuscripts would have been dating from sometime before this date.
Thus with the earliest appearance of the tie being "ca. 1400" and definitive evidence of dots appearing, at the latest, in 1377, we can assume the dot appeared first.
There's of course some wiggle room here with the meaning of "ca. 1400," but I think we're relatively safe to assume that the dot preceded the tie. Further evidence of this is that Machaut was operating in the ars nova, a tradition connected to treatises from ca. 1320 of Jehan des Murs and Philippe de Vitry. (There's also an interesting national connection: this is a French tradition, but the appearance of the bar line in the Faenza manuscript is Italian!)
With all of this said, the musical idea of elongating a prior note by some amount long precedes the visual notation of the dot and tie themselves. But these particular symbols were made necessary as rhythmic notation evolved from rhythmic modes through mensural and proportional systems into something like what we have today.

Which came first: the dot or the tie?


Redirection to home page

Question: I am working on a Drupal site. I have put a "Create an account" block on one of my content pages. After the form is submitted the user is redirected to the home page. I want to reload the same page on submit. Can anyone help me out with this.
Answer: Download and install this module http://drupal.org/project/login_destination
It is also possible to keep users on the currently visited page after logging in or out.
Hope it will match your requirement!!!
Comment: done it works for registration too..?
Comment: @Syed Hashim Now you've resolved this question, please check it off.
Comment: Bala yap checking for it. Thanks for your support bro
Comment: The login destination module (as its name implies) does not work for user registration.

Redirection to home page


Covering for connected and locally path connected spaces

Question: Under the condition that the spaces (or maybe just the total) are connected and locally path connected, is then the a covering the same as a homeomorphism?
Comment: Are you sure this is what you want to ask?  As written, the answer is certainly not: consider for instance the covering map from $\mathbb{R} \rightarrow S^1$.  In fact one almost always restricts to covering maps in which both the base and total spaces are connected and locally path connected.
Comment: Actually, what I wanted to ask is why a map of coverings f : E -> E' (p: E -> B and p' : E' -> B being coverings with p'f = f) is a map of coverings (mostly why it is surjective) under the condition that we are dealing with connected and locally path connected spaces. I thought that it might follow from what I asked above but you have proved me wrong.
Comment: Dear Down, To prove the surjectivity, you will have to use connectivity of $E'$ (otherwise the result is not true).  You want to show that $f(E) = E'$.  Here are some hints: (i) think about what properties you need to prove for $f(E)$ to get this equality.  (This is where connectedness will be used).  (ii) Prove them using the covering space properties.
Comment: Incidentally, this statement (that $E \to B$ is surjective) is also true if we are working with a fibration.  This is actually a hint: use path lifting.
Answer:
Dear Down, To prove the surjectivity, you will have to use connectivity of $E'$ (otherwise the result is not true). You want to show that $f(E)=E'$. Here are some hints: (i) think about what properties you need to prove for $f(E)$ to get this equality. (This is where connectedness will be used). (ii) Prove them using the covering space properties.

– Matt E Sep 15 '10 at 18:49

Incidentally, this statement (that $E\to B$ is surjective) is also true if we are working with a fibration. This is actually a hint: use path lifting.

– Akhil Mathew Sep 16 '10 at 2:41


Why am I getting inconsistent results with Read function on a Stream connected to network?

Question: I am using a simple function:-
while((br.Read(downbuffer, 0, downbuffer.Length)>0)
{
    //Write the data in downbuffer to a file.
}

While its working well for a file(tested multiple times on a zip file download- http://citylan.dl.sourceforge.net/project/cric-scoreslive/v8.5-Live%20Cricket%20Scores%20Desktop%20App.zip), its not working when the link refers to a HTML file(tested on http://www.mediafire.com/?rc3kj22p1tb4vi9). With the later link, it only downloads and write only about 1 KB of data, while the page is of about 60 KB.
If it has something to do with not being flushed or anything, wondering how is it working with the files download? Relative code is this:-(Running in a separate thread)-
wreq = (HttpWebRequest)WebRequest.Create(uri);
wres = wreq.GetResponse();
fs = new FileStream(totalpath, FileMode.Create);
bw = new BinaryWriter(fs);
br = new BinaryReader(wres.GetResponseStream());
while((onecount=br.Read(downbuffer, 0, downbuffer.Length)>0)
{
    bw.Write(downbuffer, 0, onecount);
    totalcount += onecount;
}

totalpath leads to a file,nothing special.
downbuffer size is 20 KB, my internet speed is about 60 kBps(512kbps).
Comment: If you're simply copying one stream to another, why the BinaryWriter and Reader?
Comment: BinaryReader: Reads primitive data types as binary values in a specific encoding. That's not what you want is it? The Read and Write methods are available on the underlying stream. Wrapping with BinaryReader/Writer is pointless. If you really want to carry on with this nonsense, try `bw.Flush` after your loop.
Comment: You only use `Write(byte[], int, int)`, that method is also available for the bare stream. The BinaryWriter serves no purpose.
Comment: There are other things on my mind, and I need to begin this way.
Its a bit difficult to explain right now but I just know this is to be done for now.
Comment: I've tried with bw.Flush() too, neither did the HTML page downloaded completely with it, and neither did the file in first link had any problems with bw.Flush inside the while loop(Of course its present outside the loop).
Comment: Secondly I need a Stream which can read all types of data, so I just thought binaryReader was a good choice. Its kinda simple download manager code for me.
Answer: You could solve the whole problem by avoiding it:
using (var client = new WebClient())
{
    client.DownloadFile(uri, totalpath);
}

Comment: I just wanted to do it using BinaryReader, is there a way?
Especially I want to dig a little why its not working with HTML files when working good with other files? Its downloading a bit of data I can see by opening file, sometimes its 977 bytes,sometimes 987 bytes and likewise. Any ideas?


Should all the fields in a GlobalSettings modelling class be static ( C# centric )?

Question: The idea is that the ApplicationSettings class will get some default values from a configuration / resource file and later on some but not all from those settings will be applied to UserSettings
Answer: You should have only instance fields in such a class, and make the whole class a Singleton if needed (although be careful not to expose it globally - singletons are evil).
Static fields cannot be serialized (which is important for a settings class). Second thing, by having instance fields, you can easily pass different instances of settings to different parts of your app. And the important point is to pass the settings to the rest of the application, not to make them globally visible so that every object can access them.


examine output of shell command using subprocess in Python

Question: I'm running a shell command in a Jupyter Notebook using subprocess or os.system() . The actual output is a dump of thousands of lines of code which takes at least a minute to stdout in terminal. In my notebook, I just want to know if the output is more than a couple of lines because if it was an error, the output would only be 1 or 2 lines. What's the best way to check if I'm receiving 20+ lines and then stop the process and move on to the next?
Answer: you could read line by line using subprocess.Popen and count the lines (redirecting & merging output and error streams, maybe merging is not needed, depends on the process)

If the number of lines exceeds 20, kill the process and break the loop.
If the loop ends before the number of lines reaches 20, print/handle an error

code:
p = subprocess.Popen(cmd,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)

for lineno,line in enumerate(iter(p.stdout.readline, b'')):
    if lineno == 20:
        print("process okay")
        p.kill()
        break
else:
    # too short, break wasn't reached
    print("process failed return code: {}".format(p.wait()))

note that p.poll() is not None can help to figure out if the process has ended prematurely too


For odd integers $a,b,c$ line $ax+by+c=0$ cannot intersect parabola $y=x^2$ in a rational point

Question: For odd integers $a,b,c$ line $ax+by+c=0$ cannot intersect parabola $y=x^2$ in a rational point(where both abscissa and ordinate are rational numbers.)

We need to solve the equation of the line $ax+by+c=0$ with the parabola $y=x^2$.
Put $y=x^2$ in the equation $ax+by+c=0$,we get $bx^2+ax+c=0$,
Now we need to check whether the discriminant of the quadratic equation is a perfect square or not.
Discriminant $=a^2-4bc$
As $a,b,c$ are odd integers,let $a=2k_1+1,b=2k_2+1,c=2k_3+1$
Discriminant $=a^2-4bc=(2k_1+1)^2-4(2k_2+1)(2k_3+1)$
$=4k_1^2+4k_1-16k_2k_3-8k_2-8k_3-3$
But I do not know whether $4k_1^2+4k_1-16k_2k_3-8k_2-8k_3-3$ is a perfect square or not
Comment: For there to be rational roots then there has to exist two factors of $bc$ which adds to give $a$, e.g. $14x^2 +31x + 15 = 14x^2 + 21x + 10x + 15 = 7x(2x + 3) + 5(2x + 3) = (7x + 5)(2x + 3)$.  But if $b$ and $c$ are both odd, then $bc$ is also odd, which means that any two factors much be odd--but two odds add to give an even number.
Answer: Suppose that $a,b,c$ are odd, $bx^2+ax+c=0$ and $x$ is rational.  Let $x=p/q$ where $p,q$ are integers with no common factor.  Then
$$bp^2+apq+cq^2=0\ .$$
Reading the equation modulo $2$, we have $a\equiv b\equiv c\equiv 1$; also $p^2\equiv p$ and $q^2\equiv q$; hence
$$p+pq+q\equiv0\ .$$
Therefore
$$(p+1)(q+1)\equiv1\ ;$$
this implies
$$p+1\equiv q+1\equiv1$$
and so
$$p\equiv q\equiv0\ .$$
That is, $p$ and $q$ are both even, which is a contradiction since we assumed they have no common factor.
Answer: Proof by contradiction:
Assume that $bx^2 + ax + c = 0$ has rational roots and $a$, $b$, and $c$ are odd.  This means that there exists four integers, $k_1$, $k_2$, $k_3$, and $k_4$ such that:
\begin{align}
bx^2 + ax + c =&\ (k_1x + k_2)(k_3x + k_4)\\
=&\ k_1k_3x^2 + (k_1k_4 + k_2k_3)x + k_2k_4
\end{align}
Because $b$ and $c$ must be odd, we can assume that $k_1$, $k_2$, $k_3$, and $k_4$ must all be odd (since $k_1k_3 = b$ must be odd and $k_2k_4 = c$ must be odd).  If all of those are odd, then $k_1k_4$ is odd and $k_2k_3$ is odd and therefore $k_1k_4 + k_2k_3 = a$ must be even since an odd plus an odd results in an even number.
This is a contradiction to the assumption that $a$ is odd, and thus it cannot be the case that $a$, $b$, and $c$ are odd and you have a rational intersection.


Viewing an uploaded item in DSpace 4.2 xmlui

Question: This is how the my search results page of DSpace looks like :

On clicking the item a new page opens up showing its description:

The description page opens the file upon clicking View/Open. Is it possible to directly open the file upon clicking its title on the results page? I want to skip the item description page.
As per my understanding this is the Java file which is called to render items. Do I need to make changes to this file? Or is it possible to achieve what I want by simply modifying the sitemap and xsl files?
Comment: I believe you have to edit `item-list.xsl` for browse and `discovery.xsl` for search results. `discover.xsl` by the way is found under the `themes/dri2xhtml-alt/aspect/artifactbrowser`. It will save you time during an upgrade if you'll just copy the relevant templates into `Mirage.xsl`, preferably under the `modules` directory mentioned [here](https://wiki.duraspace.org/display/DSDOC4x/Advanced+Customisation).
Comment: What are you thinking to do if there is none or more than one file?
Comment: Currently we're only considering items containing a single file
Comment: @euler I commented out lines 183 to 192 in [discovery.xsl](https://github.com/DSpace/DSpace/blob/master/dspace-xmlui/src/main/webapp/themes/dri2xhtml-alt/aspect/artifactbrowser/discovery.xsl#L183). As a result the action upon clicking the Item name is suppressed. Then I copied lines 505 to 524 from [item-view.xsl](https://github.com/DSpace/DSpace/blob/master/dspace-xmlui/src/main/webapp/themes/Mirage/lib/xsl/aspect/artifactbrowser/item-view.xsl#L505) after line 182 in `discovery.xsl`. That didn't help. Could you tell me where I'm going wrong?
Comment: You need to adjust the xpath inside the "view-open" template to apply it on the $metsDoc. There's an example right there in the code you commented out in discovery.xsl.
Comment: I'm sorry, I can't help you further with this. I tried what you are trying to achieve and unfortunately I failed in doing so. Like @terrywb suggested, I created a similar logic that generates the thumbnail images, but I can't make the href point to the primary bitstream that is not a thumbnail (eg mets:fileGrp[@USE='CONTENT]). I have **very** limited knowledge about xslt. You can ask in the [DSpace-Tech](http://dspace.2283337.n4.nabble.com/DSpace-Tech-f3276945.html) Mailing list for additional details.
Comment: @euler thanks for all the effort you put in. I'll post my question in DSpace mailing list as you suggested.
Comment: @AntoineSnyers hey it would be nice if you could explain how the xpath is being set, and what's meant by `$metsDoc`
Comment: It's just putting 2 and 2 together, but sure, I've posted an answer.
Answer: The code that generates the thumbnail image is here.
https://github.com/DSpace/DSpace/blob/dspace-6_x/dspace-xmlui/src/main/webapp/themes/dri2xhtml/General-Handler.xsl#L34-L47
You could create similar logic to create an href to the original bitstream.
Look at the XML in /metadata/handle/xxx/yyy/mets.xml where xxx/yyy is your item handle.  You should see the information that will point you to the original bitstream.
Comment: Hi thanks for your answer. But I didn't get *Look at the XML in /metadata/handle/xxx/yyy/mets.xml where xxx/yyy is your item handle*. Could you please explain. Where do I find `/metadata/handle/xxx/yyy/mets.xml `
Comment: according to your screenshot, at http://10.17.250.230:8080/xmlui/metadata/handle/123456789/3/mets.xml
Comment: @AntoineSnyers what I understood is that these [lines](https://github.com/DSpace/DSpace/blob/master/dspace-xmlui/src/main/webapp/themes/Mirage/lib/xsl/aspect/artifactbrowser/item-view.xsl#L517-L524) of code are used to open the file in view mode. Can these lines be of help?
Answer: As was said in the comments, the xsl template to modify is the "itemSummaryList" in discovery.xsl
Replace that href value with $metsDoc//mets:FLocat[@LOCTYPE='URL']/@xlink:href"

            <xsl:element name="a">
                <xsl:attribute name="href">
                    <xsl:value-of select="$metsDoc//mets:FLocat[@LOCTYPE='URL']/@xlink:href"/>
                </xsl:attribute>
                <xsl:choose>
                    <xsl:when test="dri:list[@n=(concat($handle, ':dc.title')) and descendant::text()]">
                        <xsl:apply-templates select="dri:list[@n=(concat($handle, ':dc.title'))]/dri:item"/>
                    </xsl:when>
                    <xsl:otherwise>
                        <i18n:text>xmlui.dri2xhtml.METS-1.0.no-title</i18n:text>
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:element>

Comment: I made the change which you suggested, but it didn't work. So I then replaced the href value in the corresponding [line](https://github.com/DSpace/DSpace/blob/master/dspace-xmlui/src/main/webapp/themes/dri2xhtml-alt/aspect/artifactbrowser/item-list.xsl#L60) in **items-list.xsl** with `"$metsDoc//mets:FLocat[@LOCTYPE='URL']/@xlink:href"`. Now upon clicking the file name, the same page i.e the /xmlui/discover page is getting reloaded. Maybe the link is not getting resolved properly.
Comment: apparently the files **discovery.xsl** and **items-list.xsl** can only access the fileGrp=THUMBNAIL section of the `metsDoc`. I changed this line in [discovery.xsl](http://github.com/DSpace/DSpace/blob/master/dspace-xmlui/src/main/webapp/themes/dri2xhtml-alt/aspect/artifactbrowser/discovery.xsl#L70) to include `fileGrpTypes=ORIGINAL,THUMBNAIL` and also made similar change to this line in [common.xsl](http://github.com/DSpace/DSpace/blob/master/dspace-xmlui/src/main/webapp/themes/dri2xhtml-alt/aspect/artifactbrowser/common.xsl#L157). But it still doesn't read the xpath. Any suggestions?
Comment: that should be right, could you show us the contents of the $metsDoc? (in a pastebin or something)
you can view it [in your browser](http://10.17.250.230:8080/xmlui/handle/123456789/3/mets.xml) or by doing a [copy-of](http://www.w3schools.com/xsl/el_copy-of.asp) and inspecting the HTML of the page.
Comment: I was able to solve the problem :) I'm posting an answer
Answer: I was able to achieve what I wanted with help from Antoine Snyers, terrywb and this link. As pointed out by terrywb the information which I needed to read, i.e, the bitstream address of the uploaded file, was stored in the metsDoc. Here's a screenshot of my metsDoc with the fileSec expanded:

To be able to access the fileSec of the metsDoc I changed this line in discovery.xsl and this line in common.xsl to <xsl:text>?sections=dmdSec,fileSec&fileGrpTypes=ORIGINAL,THUMBNAIL</xsl:text>.
Then I added/modified the following code to the itemSummaryList in discovery.xsl so that the title hyperlink now points to the file bitstream.
<xsl:variable name="filetype">
    <xsl:value-of select="$metsDoc/mets:METS/mets:fileSec/mets:fileGrp[@USE='CONTENT']"/>
</xsl:variable>

<xsl:variable name="fileurl">
    <xsl:value-of select="$metsDoc/mets:METS/mets:fileSec/mets:fileGrp[@USE='CONTENT']/mets:file/mets:FLocat[@LOCTYPE='URL']/@xlink:href"/>
</xsl:variable>

            <xsl:element name="a">
                <xsl:attribute name="href">
                    <xsl:choose>
                        <xsl:when test="$metsDoc/mets:METS/mets:dmdSec/mets:mdWrap/mets:xmlData/dim:dim/@withdrawn">
                            <xsl:value-of select="$metsDoc/mets:METS/@OBJEDIT"/>
                        </xsl:when>

            <xsl:when test="$filetype">
                <xsl:value-of select="$fileurl"/>
            </xsl:when>

                    </xsl:choose>

                </xsl:attribute>

Similarly, I also made changes to item-list.xsl file, and added this line <xsl:apply-templates select="mets:fileSec/mets:fileGrp[@USE='CONTENT']"
            mode="itemSummaryList-DIM"/> to the template itemSummaryList-DIM.
So finally I got my desired result:

As visible in the inspector, the href attribute of the title now points to the original bitstream of the file :)


Why Chart.JS showing an extra line

Question: I am using chart.js to display some data in the line chart. It's working fine except for one thing that why it's showing an extra line as highlighted by me in the attachment below:

I'm providing just one dataset like that:

It will show you a tooltip on hover on one line but it's showing nothing while hovering on the second line. Plz, tell me a way to remove that second line and tell me why it's showing.
Here is the codepen link
Here is the code, plz wait for some seconds after running the below code because it is fetching the data from api.

  var ctx = document.getElementById('myChart').getContext('2d');

  var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["2016-01-01T00:00:00Z", "2017-01-01T00:00:00Z", "2018-01-01T00:00:00Z", "2019-01-01T00:00:00Z", "2020-01-01T00:00:00Z", "2021-01-01T00:00:00Z", "2022-01-01T00:00:00Z",],
    datasets: [{
      label: 'Demo',
      data: [],

      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      //borderWidth: 0.2
    }]
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          unit: 'year' //show year on x-axis
        }
      }],

      yAxes: [ //show y-axis on right side
        {
        display: true,
        position: 'right',
        ticks: {
        //beginAtZero: true
        }},
        {
        display: false,
        position: 'left',
        }
      ]

    },

    responsive: true,
    maintainAspectRatio: false,
    elements: {
            line: {
            fill: false,
            borderWidth: 2,
            },
            point:{
              radius: 0
            }
    }
  }
});

function addData(chart, data) {
    //chart.data.labels.push(label);
    chart.data.datasets[0].data=data;
    // chart.data.datasets.forEach((dataset) => {
    //     dataset.data=data;
    // });
    chart.update();
}

$(document).ready(function(){
$.ajax({
url:'https://yfinance-backend.herokuapp.com/historical-data/sp500/',
type:'get',
data:{},
success:function(response,status,xhr){
  let chart_data=[];

  response.forEach(function(record, index){
    let obj={};
  obj.t=record.date;
  obj.y=record.close_value;

  chart_data.push(obj);
  });

  console.log(chart_data);
  addData(myChart, chart_data);
},
error:function(xhr,status,errorThrown){},
complete:function(xhr,status){
    var response=xhr.responseJSON;
}
});
});

  <canvas id="myChart" width="400" height="400"></canvas>
Answer: The behaviour of the line is because the points are not in the correct order in the data array, so it will jump back in the chart.
To fix this you will have to sort your data array first so that it's in the correct order.

Why Chart.JS showing an extra line


C++ unary right fold vs unary left fold with comma operator

Question: Why comma separated unary left fold produce the same result as the right one?
Live code
template<class ...Args>
void right_fold(Args... args){
    ((std::cout << args),...);
}

template<class ...Args>
void left_fold(Args... args){
    (...,(std::cout << args));
}

int main()
{
    right_fold(1,2,3,4);
    std::cout << std::endl;
    left_fold(1,2,3,4);
}

OUTPUT:
1234
1234

Shouldn't it be:
4321
1234

?
Comment: Simply put, recedence and order of evaluation is independent
Comment: Possible duplicate of [Operator Precedence vs Order of Evaluation](https://stackoverflow.com/questions/5473107/operator-precedence-vs-order-of-evaluation)
Answer: Left vs right folding is the difference between ((a,b),c) and (a,(b,c)), but they have exactly the same effect when the built-in , operator is used: they first evaluate a, then b and finally c. To see a difference, you'd need to use a type with a custom overloaded , operator.
The syntax may look as if it would reverse the arguments, but no, that won't happen.
Comment: @tower120 [A pair of expressions separated by a comma is evaluated left-to-right;](http://eel.is/c++draft/expr.comma#1.sentence-2).
Comment: @tower120 The first means "first, evaluate a then b, then, evaluate c". The second means "first, evaluate a, then evaluate b then c". The net effect is the same.
Comment: @tower120 Exactly. There are a few operators which force left-to-right evaluation, and those are called out specifically in the standard. As of C++17, there are some operators which force right-to-left evaluation, and those are also called out in the standard. For the other operators, the order is entirely up to the implemention.
Comment: Why both `((a,b),c)` and `(a,(b,c))` have the same execution order?
Comment: @tower120 Parentheses do work, but they never pretty much never specify evaluation order. This is no different from other operators. Given `f() * (g() + h())`, `f`, `g` and `h` may be called in any order. There is no requirement to call `g` and `h` first.
Comment: @tower120 What order do you expect in each case and why?
Comment: So... parentheses don't work with commas?...  I expected to see a,b,c order for ((a,b),c) because a,b in the deepest parentheses level, and left to right a then b.   And b,c,a for (a,(b,c))  because b,c in the deepest level, left to right b then c.
Comment: So if not this special rule http://eel.is/c++draft/expr.comma#1.sentence-2 , order of evaluation (in case with comma) would be unspecified / compiler dependent?
Answer: These folds respectively expand to:
((std::cout << 1), ((std::cout << 2), ((std::cout << 3), (std::cout << 4))))

... and:
((((std::cout << 1), (std::cout << 2)), (std::cout << 3)), (std::cout << 4))

Despite the flurry of parentheses, they are equivalent in terms of order of execution: left to right.
Answer: Because they are indeed the same thing:
((std::cout << 1, std::cout << 2), std::cout << 3), std::cout << 4;
std::cout << 1, (std::cout << 2, (std::cout << 3, std::cout << 4));

Both have output 1234.


Zero-inflated Poisson regression: how can I calculate contrasts for BACI (Before-after-control-impact) experiment?

Question: I am analyzing count data with a lot of zeros and found that although the data do not fit a poisson glm, they fit the zero-inflated poisson (ZIP) regression significantly better than the standard poisson glm.
This analysis is for a BACI study, in which I have data before, during, and after the treatment, in three zones: control, on-trail (treatment1) and off-trail (treatment2).
I am interested in the difference in change of detection rate of a species between the on-trail (treatment) site vs. control site, before and after the treatment. I have performed contrast on this data to determine this difference with a simple linear regression model (using lm), but I'm unsure how to find this difference using the zero-inflated poisson model.
The results of my ZIP model are here (ZP = Zone+Phase combined into one variable; the "After" phase is called "Open" in the dataset)
Call:
zeroinfl(formula = Deer ~ ZP | ZP, data = zinb)

Pearson residuals:
    Min      1Q  Median      3Q     Max
-0.6756 -0.5180 -0.4137 -0.1243 14.8998

Count model coefficients (poisson with log link):
             Estimate Std. Error z value Pr(>|z|)
(Intercept)  1.076730   0.031034  34.695  < 2e-16 ***
ZPCDuring    0.080611   0.055391   1.455    0.146
ZPCOpen     -0.696793   0.092432  -7.538 4.76e-14 ***
ZPFBefore    0.062467   0.042638   1.465    0.143
ZPFDuring    0.112727   0.067928   1.659    0.097 .
ZPFOpen     -0.765391   0.080475  -9.511  < 2e-16 ***
ZPTBefore   -0.008428   0.045729  -0.184    0.854
ZPTDuring   -0.063361   0.063193  -1.003    0.316
ZPTOpen     -0.717266   0.078422  -9.146  < 2e-16 ***

Zero-inflation model coefficients (binomial with logit link):
            Estimate Std. Error z value Pr(>|z|)
(Intercept)  0.40428    0.06617   6.110 9.97e-10 ***
ZPCDuring    0.85610    0.11076   7.729 1.08e-14 ***
ZPCOpen      0.79893    0.13448   5.941 2.84e-09 ***
ZPFBefore   -0.04894    0.09287  -0.527    0.598
ZPFDuring    1.51339    0.13035  11.610  < 2e-16 ***
ZPFOpen      0.20254    0.12932   1.566    0.117
ZPTBefore   -0.08598    0.09830  -0.875    0.382
ZPTDuring    0.98729    0.11720   8.424  < 2e-16 ***
ZPTOpen      0.17416    0.12823   1.358    0.174
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Number of iterations in BFGS optimization: 25
Log-likelihood: -8572 on 18 Df

and the code i have been using to get the contrasts using the lm model is here (based on this tutorial):
result.lm <- lm(Deer ~ Zone + PhaseBDO + Zone:PhaseBDO, data=counts)
options(contrasts=c(unordered="contr.sum", ordered="contr.poly"))
result.lsmo.SP <- lsmeans::lsmeans(result.lm, ~Zone:PhaseBDO)

contrast(result.lsmo.SP, list(bact=c(1, 0, -1, 0, 0, 0, -1, 0, 1)))
confint(contrast(result.lsmo.SP, list(bact=c(1, 0, -1, 0, 0, 0, -1, 0, 1))))

Can anyone suggest how I can calculate the contrast from my ZIP regression model to test for significant differences between the difference in detection rates between the two time periods (before/after) in the two zones (control/treatment)?
For example, I want to be able to say if there was a significantly larger increase (or decrease) in the detection rate of deer after the treatment was implemented, in the treatment zone compared with the control zone.
Thanks in advance for your suggestions.
Comment: um .. what's a BACI?
Comment: before-after-control-impact.  It's a common term in ecology/environmental impact assessment.
Comment: Thanks for the question - I've edited the title to make this more evident.
Answer: I think you can get what you need by inputting these methods for zeroinfl objects:
recover.data.zeroinfl = lsmeans:::recover.data.lm

lsm.basis.zeroinfl = function(object, trms, xlev, grid, ...) {
    m = model.frame(trms, grid, na.action = na.pass, xlev = xlev)
    contr = object$contrasts
    contr = contr[setdiff(names(contr), c("zero", "count"))]
    X = model.matrix(trms, m, contrasts.arg = contr)
    use = seq_len(ncol(X)) # use only the elts related to response
    bhat = coef(object)[use]
    V = vcov(object, ...)[use, use]
    nbasis = estimability::all.estble
    misc = list(tran = "log", inv.lbl = "rate")
    dffun = function(k, dfargs) NA
    dfargs = list()
    list(X = X, bhat = bhat, nbasis = nbasis, V = V,
        dffun = dffun, dfargs = dfargs, misc = misc)
}

Then run the lsmeans and contrasts stuff you had before. This will work for the count portion of the model. Another setup would be needed to use the zero part.
I'll work on supporting zeroinfl objects more fully in lsmeans.
Comment: THANK YOU, rvl! This does solve the issue and I'm able to calculate lsmeans and contrasts for the counts portion of the model. Do you have any code that would make the zero part of the model work as well?
Comment: All in due time. It is definitely possible. Also, the most useful thing would probably be to combine them into an estimate of the mean with the zeros included. But this will take several days at least.
Comment: Thanks, that is great, no hurry. I'm a bit confused what you mean by "combining them into an estimate of the mean with zeros included". Do you mean to take a raw mean of all lines to get the mean detection rate (number of observations/effort)? Or do you mean that it would be possible to combine the "counts" and "zero" portions of the zero-inflaed poisson output, and run lsmeans and contrasts on that combined result? The second (combining counts and zeros from zeroinfl output) would be very interesting and I'd be interested in how to interpret this as well. Thanks again!
Comment: I'm talking about the mean of the distribution that is zero with probability $p$, and Poisson with probability $1-p$. If you send an email to the lsmeans developer, I'll try to keep you apprised of new developments in this type of model.
Comment: Thanks, I'll email the developer. I am also trying to run the baci contrasts on results from an occupancy analysis performed using Rmark. Do you know if there's a way to calculate lsmeans from occupancy results to complete the contrasts analysis on this type of model?


Using views to display content based on taxonomy terms?

Question: I have created a faculty profile system on our university departments site. Every faculty member is tagged with terms regarding an area of expertise (either in teaching or in research).
What I need is to create a view that takes the areas of expertise from a specific faculty members page, and displays the other faculty members that also work within those areas. (but only those areas)
What I have done  so far is a view that wants to show ALL the terms on EVERY faculty content type, but I need to have the view filtered somehow based on the specific page that is being viewed. Here is what I have:
http://sustainable.unt.edu/irene-klaver
Here is an example of what I need: http://sustainability.asu.edu/people/persbio.php?pid=188
The faculty nodes are a custom content type (CCK). The view uses Imagecache/Imagefield to use the thumbnails. The terms have their own vocabulary in Taxonomy, specifically for this purpose. I am using Drupal 6.
I have been told by a few that this might not be able to happen with Drupal, and that I have to create some custom php code in my node-faculty.tpl.php file. Since the ASU site aboves developer doesn't use Drupal, they couldn't really help me out much. I find it hard to believe that someone hasn't needed a function that is similar to this before... If anyone can at least point me in the right direction, I would greatly appreciate it!
Thanks!
Answer: Drupal Views can easily do this :)

Create your view and call it "example", and for this example, put Node Title in the Fields.
Add in an argument.  Here select Taxonomy: Term ID.
In "Action to take if argument is not present:" select "Provide Default Argument"
There, select "Taxonomy Term ID from URL" and then click "Load default argument from node page, thats good for related taxonomy blocks" and if you want, you can also limit it to specific vocabulary(ies) by clicking "Limit terms by vocabulary" and clicking on the one(s) you want.
Create a "Block Display" and save everything.
Goto your Site Building/Block Admin Page and look for "Views: example" and put it in a region of your theme.

Now, if all is well in the world, that block will appear and will display the titles of all nodes that also have the same taxonomy term as the node it is displayed on.  Of course, you will probably want this block displayed only on certain pages, but you can do that in your block UI as well.  And of course you'll also probably want to be fancier than just the node title, etc, but there you would include the fields in the specific nodes, etc.
ADDITION:
This is what I see here for a taxonomy term id argument with D6 and Views3:

UGLY SOLUTION:
I was sure there would be a solution to this using just Views, but I can't figure it out for the life of me.  Grrrr, I hope someone out there says Duh, this is how you do it. But, if you have the PHP Input Filter enabled, you can create a block that will do this instead of creating a custom module.  The PHP Input Filter is UGLY.  It should be killed with that dull ax I often use, but here goes:
Add a new block via the blocks UI with this as the block body:
<?php

$node=menu_get_object();

if (isset($node->type) && $node->type=='Faculty') {

  $vid = db_result(db_query('SELECT vid FROM {vocabulary} WHERE name = "Expertise"'));

  if (!empty($node->taxonomy)) {
    foreach($node->taxonomy as $term) {
      if ($term->vid == $vid) {
         print '
' . $term->name . '
';
         print '
' . views_embed_view('faculty_expertise_test2', 'default', $term->tid) . '
';
      }
    }
  }

}

?>

Make sure you select PHP Code as the Input Filter.  Select a Block description and title and save the block.  Place it in whatever region you want.  Cross fingers and see what happens :) Basically all this does is loop through all taxonomy terms of your Expertise vocabulary in the node shown and then calls the view with that argument. I think I have everything capitalized correctly from your examples, but the key things to customize about are Faculty, Expertise and faculty_expertise_test2, which are your node type, vocabulary and view.  If all works, then it's up to you to CSS things to your liking.  Hope this helps!
PS
I just realized that the view will most probably return the faculty member her/himself but that can be dealt with another day :)
Comment: Jimajamma, first off thank you so much for your quick reply and willingness to help! Secondly, I got to the part where you said click "Load default argument from node page, thats good for related taxonomy blocks"...I'm not seeing anything like that in Views...:( I would add a screenshot but since I'm a new user this website isn't letting me. Do I need a different version? Thanks again for your help!
Comment: I've added a screen shot of what I see, maybe I am forgetting a click or two in there.  I am using D6 with Views 3.  Let me know if this helps or if I can be of any more.
Comment: Ok, I'm going to have to ask our Web department to update my Views to 3. They don't let us update/install our own modules, and they don't update things automatically as things come out. When they do the update I'll let you know if this works or not. UGH. I'll keep you updated after it's installed. Thanks again! You're helping out a very confused Drupal novice...:D
Comment: quite welcome anytime!
Comment: Ok, so I finally got Views 3 and I was able to click on all the new goodies that come with it, except now it isn't working. It's not even displaying the block...help? :)
Comment: have you created a block display in views and then gone into your block admin page and made sure it is showing up in the region you want it in?
Comment: Yes I created a block display, but I use Context so that it only shows up in a certain content type (as oppose to the Block UI).
Comment: I've never used the Context module, but it *"shouldn't"* matter as it will still be displayed with the node/content type.  If you could grab a screen capture or two I might be able to see if you clicked something wrong
Comment: https://sustainable.unt.edu/sites/all/files/slideshow/ss1.png
Comment: https://sustainable.unt.edu/sites/all/files/slideshow/ss2.png
Comment: Sorry it wasn't letting me add the screenshots, since I don't have a reputation of 10 or higher. The first link is the whole views stuff, I just cloned the the view I was working from. The second one is what I selected for the taxonomy term ID.
Comment: you have both load default argument from term page AND load default argument from node page.  unclick the first one and let's see what happens...
Comment: Alright, now it's at least showing up, (and I kind of feel like an idiot), but it's only showing the very first term for each page (which is actually really exciting, because that's the closest I've ever got!). I tried clicking on "Allow multiple terms per argument" at the bottom but it still didn't work. How can I have the view show all the terms for that node?
Comment: D'oh.  Yeah, you're right.  Hmm.  Let me ponder this for a bit.  The issue I think is you want to OR the results, eg, you don't want to list everyone who has exactly the same areas of expertise, you want to list everyone that has at least one of them, right?  This is easily done with some php programming, I am just digging around to see how it might be done automagically inside of views.
Comment: I want to list all of the faculty members who have the same areas of expertise as the faculty member that is being viewed. For example, using the faculty member that I link above in the question that began the thread, (Irene Klaver), I want all the faculty listed that are also experts in Aesthetics, Cultural Studies, Environmental Philosophy, Philosophy of Water, Twentieth Century Continental Philosophy, and Water Quality. But I only want the faculty for those terms (but still want all the faculty for each term). Let me know if this doesn't make any sense, and I can try and explain it better.
Comment: got it.  You want a list of Aesthetics experts, a list of Cultural Studies experts, a list of... etc.
Comment: Yep! Of course the areas of expertise that are shown will depend on who's profile the viewer is looking at, but that's pretty much what I'm going for. And where you've gotten be so far is the closest I've gotten, so thanks AGAIN for being awesome. I'm not too knowledgeable with PHP, but if you even pointed me in the right direction I would greatly appreciate it!
Comment: I'm getting a syntax error: Parse error: syntax error, unexpected '{' in /export/nfs-mounts/nas2.cws.private.unt.edu/virtual/sustainable-dev_unt_edu/includes/common.inc(1731) : eval()'d code on line 9 ......I copied it into Dreamweaver and it said the syntaxt error was the line that says " if (!empty($node->taxonomy) { "
Comment: opps. and another ) :)
Comment: Hm, it's pulling the view but it's not showing anything within it...strange. Alrighty, I think I've bugged you enough, you've been super awesome and amazing and I am sending massive digital hugs your way. With this I think I can mess around with the PHP until it bends to my will (or something like that). I mean at this rate you've helped me for like a week straight and I'm going to have to start paying you pretty soon ;) Thanks again, if I end up figuring it out, I'll put it up here.
Comment: anytime seriously, glad I could help out a little bit.  usually when things like this don't work it's because of `off by one` errors, so check upper vs lower case in everything, eg, make sure it's Expertise not expertise, etc.  Also, I am assuming `default` in the view is correct.  If the argument isn't in there, eg, you've overridden your block display view to put it there only, that could be it.
Comment: Ok I'll check those things and see if that doesn't work. Seriously, you've been a great help!
Answer: I FOUND AN ANSWER! YAY!
Ok so I figured it out with the help of someone who knows WAY more PHP than I do (and could site me down and actually show me in person), so I'm not going to take credit for this. :) You have to edit the theme of your site, but I actually like this better way better because I can make it pretty with CSS a lot easier. (No more dull axing)
First, create a template file for the content node type (I called mine node-faculty.tpl.php). Then I added this code directly into my template file to call the view:
<?php

foreach( $node->taxonomy as $tid ) {
print views_embed_view('faculty_expertise_test2', 'default', $tid->tid);
}
?>

AND IT WORKS. Phew! Ok, but I couldn't do it without you. Getting as far as you got me helped someone else help me through the finish line. :)
Comment: You can see a live example here (without any CSS to make it pretty yet): http://sustainable.unt.edu/irene-klaver


Deriving $\frac{\cos(n+1)\varphi\sin n\varphi}{\sin\varphi}$?

Question:
I am trying to understand this derivation provided in another answer:$$s'_n(\theta)
= {\bf Re}(e^{i\theta}+e^{i\theta}+...+e^{ni\theta}) \\
= \dfrac{-1+\cos\theta+\cos n\theta-\cos(n+1)\theta}{2(1-\cos\theta)} \\
= \dfrac{-2\sin^2\theta/2+2\sin(n+\theta/2)\sin\theta/2}{4\sin^2\theta/2} \\
= \frac{\cos(n+1)\varphi\sin n\varphi}{\sin\varphi}$$

Note:$\frac{\theta}{2}=\varphi$
I am stuck on the following point:
I used $\cos\theta=\cos^2(\frac{\theta}{2})-\sin^2(\frac{\theta}{2})=1-2\sin^2{\frac{\theta}{2}}$
After repacing I got:$\dfrac{-1+\cos\theta+\cos n\theta-\cos(n+1)\theta}{2(1-\cos\theta)}=\dfrac{-2\sin^2(\frac{\theta}{2})-2\sin^2(\frac{n\theta}{2})+2\sin^2(\frac{(n+1)\theta}{2})}{4\sin^2(\frac{\theta}{2})} $
However, after some search I did not find any identity that replaced would yield me the expression $$\frac{\cos(n+1)\varphi\sin n\varphi}{\sin\varphi}.$$
Question:
How can I go from $\dfrac{-2\sin^2(\frac{\theta}{2})-2\sin^2(\frac{n\theta}{2})+2\sin^2(\frac{(n+1)\theta}{2})}{4\sin^2(\frac{\theta}{2})}$ to $\dfrac{\cos(n+1)\vartheta\sin n\varphi}{\sin\varphi}$
Thanks in advance!
Comment: `this derivation provided in another answer` Please include the respective link. You likely miscopied what was written there.
Comment: Are you sure the second yields the third one?
Answer: Without considering real or imaginary versions it can be seen that:
\begin{align}
\sum_{k=1}^{n} e^{i k \theta} &= \frac{e^{i \theta} (1 - e^{i n \theta})}{1 - e^{i \theta}} = \frac{e^{i \theta} (1 - e^{- i \theta}) (1 - e^{i n \theta})}{(1 - e^{i \theta})(1 - e^{- i \theta})} \\
&= \frac{(e^{i \theta} - 1)(1 - e^{i n \theta})}{2(1- \cos\theta)} \\
&= - \frac{e^{i(n+1)\theta/2} (e^{i \theta/2} - e^{- i \theta/2})(e^{i n\theta/2} - e^{- i n\theta/2})}{4 \sin^{2}(\theta/2)} \\
&= - \frac{(2 i)^2 \sin(\theta/2) \sin(n \theta/2)}{4 \sin^{2}(\theta/2)} \, e^{i (n+1)\theta/2} \\
&= \frac{\sin(n \theta/2)}{\sin(\theta/2)} \, e^{i (n+1)\theta/2}.
\end{align}
Now take the real and imaginary components to obtain
\begin{align}
Re\left(\sum_{k=1}^{n} e^{i k \theta}\right) &= \frac{\sin(n \theta/2) \cos((n+1)\theta/2)}{\sin(\theta/2)} \\
Im\left( \sum_{k=1}^{n} e^{i k \theta} \right) &= \frac{\sin(n \theta/2) \sin((n+1)\theta/2)}{\sin(\theta/2)}
\end{align}
For the case of taking the Re component first:
\begin{align}
Re\left(\sum_{k=1}^{n} e^{i k \theta} \right) &= Re\left( \frac{(e^{i \theta} - 1)(1 - e^{i n \theta})}{2(1- \cos\theta)} \right) \\
&= \frac{\cos\theta - \cos(n+1)\theta + \cos n\theta -1}{2(1-\cos\theta)} \\
&= \frac{\cos(n \theta) - \cos((n+1)\theta) - 2 \sin^{2}(\theta/2)}{4 \sin^{2}(\theta/2)} \\
&= \frac{\sin(n\theta + \theta/2) - \sin(\theta/2)}{2 \sin(\theta/2)} \\
&= \frac{\sin(n\theta/2) \cos((n+1)\theta/2)}{\sin(\theta/2)},
\end{align}
where
\begin{align}
\cos\theta - \cos\phi &= - 2 \sin\left(\frac{\theta + \phi}{2}\right) \sin\left(\frac{\theta - \phi}{2}\right) \\
\sin\theta - \sin\phi &= 2 \sin\left(\frac{\theta - \phi}{2}\right) \cos\left(\frac{\theta + \phi}{2}\right)
\end{align}
was used.


Tobit for corner solution models: normality and homoskedasticity tests

Question: I would like to regress several explanatory variables (called X) on a dependent variable called Y where Y is strictly positive and continuous. It is left-censored at 0. Y represents how much a household is willing to pay to protect the environment in a specific area.  It is cross-section data.
I asked R to run a Tobit I model using censReg package or AER package:
tobit <- tobit(Y ~ X, left=0, data = mydata)

or
tobit2 <- censReg(Y ~ X, left=0, data = mydata)

and then
plot(fitted(tobit), residuals(tobit))

When observing the residuals' plot, I see the distribution is not normal  whereas it's necessary that the errors from this regression be normally distributed and homoskedastic.
Does anyone know how I can test these errors for normality and heteroskedastcity in R with the specific censored data issue? Using bptest() from the lmtest package - the Breuch Pagan test- does not work. I know that in some programs, like Stata, it's pretty straightforward to test residuals, but I have no idea how in R.
Thank you!
Mareen
Comment: Thank you Ackim. Is there any material example I can follow to test for heteroskedasticity like you explained
Answer: The residuals from such tobit models will often look non-normal (typically right-skewed) due to the censoring. This makes it difficult to apply standard classic techiques such as graphics or diagnostic tests for linear regression models (like the Breusch-Pagan test).
One thing you can do, though, is to fit a heteroskedastic tobit model where the dependence of the variance on some covariates is included. And instead of using a latent normal distribution you could also employ a distribution with heavier tails such as the logistc or t distribution. All these approaches are available in the R package crch (for censored regression with conditional heteroskedasticity). So you can fit models, say with constant variance and with heteroskedasiticy, and then compare these models by means of information criteria (AIC, BIC, ...) or likelihood ratio tests etc.
Of course, there are further sources of misspecification problems, e.g., omitted regressors, misspecified functional form etc.


How to fill all fields from a form with uiautomator

Question: Currently I'm trying to fill all fields from a form using Python + uiautomator
My Code:
d = UIDevice(adb.deviceList[0].device)

last_item_exists = d(text='Memo').exists

while not last_item_exists:
    print "Searching for fields on screen"
    fields = d(className = 'android.widget.EditText', focusable = True)
    for field in fields:
        if not (field.text == '0' or field.text == '50'): #Skip fields with 0 or 50
            print "Writing on the field"
            field.click()
            d.press(0x0000001d, 0x00001000)
            d.press('del')
            field.set_text('50')
        else:
            print "Skipping field"
    print "Searching for Memo field"
    last_item_exists = d(text='Memo').exists
    print "Scrolling down"
    d(scrollable=True).fling()

d(text='Confirm').click()

The Problem:
Depending on device resolution, this error may occur:
uiautomator.JsonRPCError: JsonRPC Error code: -32002, Message: com.android.uiautomator.core.UiObjectNotFoundException: UiSelector[CLASS=android.widget.EditText, INSTANCE=9, FOCUSABLE=true, RESOURCE_ID=com.salab.ABRT:id/task_info_item_count]

This is happening, because when I click on the last visible field field, the screen sometimes scrolls down a bit and the top field is not visible anymore.
Is there a workaround for this kind of problem, or I must change my logic(Can't think about anything right now...) ?
Answer: UiAutomator only sees what is visible on the screen at each moment. So if you scroll down (or the app does) then it can't interact with it.
You either change your logic or you swipe the screen up and down verifying if everything is filled and, if not, fill it.
Comment: Hi Inês, thank for your answer. Is there a way to check if the screen is changed ? Because the problem is on this line: `field.click()`. When the field is clicked, the screen scrolls down a bit because the field isn't totally visible
Comment: Directly with UiAutomator you can't know if the screen changed. However, you can use UiAutomation (note the difference) to read the contents of the screen and compare them as you wish.
Nevertheless, if you fill the fields by the order they appear in you should be fine.
One last thing, I've dealt with problems interacting with objects when they are not completely drawn in the screen and so I verify the bounds to see if they are completely inside the screen before interacting with it. I don't know if this extra info is of any use to you though.
Comment: Your comment helped me a lot.
I think the easiest approach is to scroll down if the field is not fully visible. What do you think ?
Comment: I think that's your best choice :)
Comment: There is yet another option:
You can click the field (which will make it scroll on its own) and then find the object again. Now it will be fully visible.
Both should work just fine.
Comment: Ok Inês, I think I got it... Thank you very much..

Can you give just another help how to check the bounds ? Because the EditText is inside a SrollView, I've got the ScrollView bounds and the EditText bounds, but I could not figure out how to know if the EditText is fully visible or not
Comment: Having the UiDevice d, you can do d.getDisplayHeight() and d.getDisplayWidth(). With those you have the max y and x bounds. The minimal x is 0, the minimal y... Well it should be 0 lol but you have the notification bar (unless it's a fullscreen app) and so if you know the top y value of the root of the screen you know the minimal y of your app.
Comment: You can find everything about the UiDevice API here http://developer.android.com/intl/es/reference/android/support/test/uiautomator/UiDevice.html


Which servers require an enterprise license for event-based pull replication?

Question: I am looking to utilize event-based pull replication between two Artifactory servers.
My question is, which of the two servers requires the Enterprise license? Is it just the destination server that is doing the pulling replication that requires the Enterprise license? Can the source server be a lesser license like OSS or Pro?
Answer: For using event-based pull replication between two Artifactory servers, the target server is the server that most have an Enterprise license.
By target server we refer to the server that you enable the event-based pull replication checkbox at.
However, it would not work pulling from the OSS version even if the target has Enterprise license, as replication with remote open-source Artifactory instance is not possible.
One the artifact is replicated, you should see it at the (remote-repo-name)-cache repository


How compare AIC (akaike information criterior)?

Question: I have two function. First function have a positive value for AIC and the second function have a negative value fir  AIC. How to make comparisons? algebraic or absolute values?? Thanks :)
Comment: Welcome to Cross Validated! Could you please explain a little more what you're trying to do? AIC is calculated from the likelihood of fitted models & the number of parameters, & the difference in AIC between models is used to compare their likely predictive ability; I'm not sure what these 'functions' are, or what the difference between 'algebraic' & 'absolute' values is.
Comment: +1 to Scortchi's comment. It's hard to tell exactly what you're trying to do and therefore it's impossible to give an answer. For example, if these two "functions" are based on fitted models with different outcome variables, you shouldn't be comparing them with AIC at all.
Comment: What are the two function?, One function (distribution) is sub model of the other or you fit one data on two function(distribution)?
Answer: When you have two models and you do model selection with AIC, you prefer the model with the minimum value for AIC. So you don't have to take the absolute value of anything and you'd prefer the model with negative AIC in this case.
Comment: Thanks everybody for the answers! And thanks Stijn...that's all I needed to know :)


Complexidade de algorítimo simples

Question: estou tendo dificuldade nesse exercício de complexidade de algorítimos, alguém pode dar uma luz?
Provar que, se f(n) = -n então f(n) é O(1).
Uma ideia que tive foi que para qualquer n positivo, f(n) será menor que n. Não sei se está correto
Comment: "*para qualquer n positivo, f(n) será menor que n*", não vejo como isso possa afetar a complexidade do algoritmo. No caso, acho que bastaria comentar que o número de operações executadas para calcular a saída é constante, portanto é O(1).
Comment: Acho que  entendi seu ponto, mas e para "provar" isso? não teria que ter alguma linguagem matemática?
Comment: @Bakun, basta mostrar que a quantidade de operações executadas não é afetada pelo tamanho do entrada. Isso é, por sinal, a definição de `O(1)`
Answer: Tudo que f(n) faz é retornar -n. Calcular o negativo de um número é uma operação de complexidade constante, é igual para todos os números. E um algoritmo de complexidade constante (seja grande ou pequena) é O(1).

Complexidade de algorítimo simples


How can I cycle all the vertex that are connected?

Question: In JanusGraph I have 4 nodes.
A(name=alice) -> B
B -> C
C -> D
D -> A

I want to get all the cycles from node A.

g.V().has('name', 'alice').both().both().cyclicPath().path().by('name')
I can get A->B->A and A->D->A. But I can't get A->B->C->D->A.
I want to get all the path from vertex A to Vertex A.
How can I get it using groovy language?
Answer: You are only traversing away from "alice" twice with both().both() therefore your path can only be length 3 which would include the "alice" vertex and the two vertices at each step away from "alice" (i.e. both() is one step and the second both() is the next step). If you want to get do "D" you have add yet another both() so that Gremlin can traverse another set of edges and I would think yet another to get back to "alice" from "D".
Or, you could simply use repeat():
g.V().has('name', 'alice').
  repeat(both()).emit().times(4).
  cyclicPath().
  path().by('name')

Note that I controlled the loop with times(4) to define how many steps away from "alice" I wanted to traverse both(). You could also use until() to control that for a more dynamic way to control loop termination - see repeat() for more information.


Convergence in distribution and limit inferior of expectation

Question: I am trying to solve this exercise in Probability Theory by A. Klenke (3rd version) by applying the continuous mapping theorem or the portemanteau theorem but with no results:
Let $X,X_1,X_2,...$ be real random variables with $X_n$ converging in distribution to $X$. Show that $E(|X|)\leq \liminf_{n\to \infty} E(|X_n|)$.
In order to apply the continuous mapping theorem I think I need to know if $P_X({0})=0$, as it requires, as a premise, that the set of points of discontinuity has measure zero. But I don't know anything about it.
Any suggestions?
Thank you.
Comment: Fatou's Lemma and Skhorohod Theorem give the answer immediately.
Comment: Could you articulate a little bit more? For the application of the Fatou's lemma I don't know if $X_n>X$ a.e. This premise is requested in the lemma, as I learnt it. Thanks.
Comment: See: https://en.wikipedia.org/wiki/Skorokhod%27s_representation_theorem
Answer: For a fixed $M>0$, let $\varphi_M$ be the function defined by $$\varphi_M(x)=\begin{cases}-M&\mbox{ if }x\leqslant -M\\
  x&\mbox{ if }-M<x\leqslant M\\
  M&\mbox{ if } x>M\end{cases}.$$
Since $x\mapsto\varphi_M(\lvert x\rvert)$ is continuous and bounded, it follows that for each fixed $M$,
$$
\mathbb E\left[\varphi_M\left(\lvert X\rvert\right)\right]=\lim_{n\to\infty}
\mathbb E\left[\varphi_M\left(\lvert X_n\rvert\right)\right]=\liminf_{n\to\infty}
\mathbb E\left[\varphi_M\left(\lvert X_n\rvert\right)\right].
$$
Moreover, since $\varphi_M(\lvert x\rvert)\leqslant \lvert x\rvert$, we get that
$$
\mathbb E\left[\varphi_M\left(\lvert X\rvert\right)\right]\leqslant \liminf_{n\to\infty}
\mathbb E\left[ \lvert X_n\rvert \right].
$$
We conclude by monotone convergence, letting $M\to\infty$.
Comment: Thank you! I didn't think about using a bounded function that mimics the absolute value at the limit. I've learned a new technique, as I am new to these topics.


Apache 2.2.21 installation on Linux 6 but got error while accessing in browser

Question: I am very new to linux.
I have installed apache 2.2.21 on linux 6 platform. While I am using ./apachectl start or ./apachectl -k start command it shows that apache is started. But while i am trying to access apache default page in any browser using http://<servername>:8080
it shows page cannot be displayed.
Can any one help me on this issue? Please its urgent.
I am also enclosing the error_log file as below.
error_log file:
[Thu Nov 24 08:57:23 2011] [notice] Apache/2.2.21 (Unix) DAV/2 configured -- resuming normal operations
[Fri Nov 25 01:45:58 2011] [notice] caught SIGTERM, shutting down
[Fri Nov 25 01:46:12 2011] [notice] Digest: generating secret for digest authentication ...
[Fri Nov 25 01:46:12 2011] [notice] Digest: done
[Fri Nov 25 01:46:13 2011] [notice] Apache/2.2.21 (Unix) DAV/2 configured -- resuming normal operations
[Fri Nov 25 01:54:58 2011] [notice] caught SIGTERM, shutting down
[Fri Nov 25 01:55:10 2011] [notice] Digest: generating secret for digest authentication ...
[Fri Nov 25 01:55:10 2011] [notice] Digest: done
[Fri Nov 25 01:55:11 2011] [notice] Apache/2.2.21 (Unix) DAV/2 configured -- resuming normal operations
[Fri Nov 25 01:58:10 2011] [notice] caught SIGTERM, shutting down
[Fri Nov 25 01:59:41 2011] [notice] Digest: generating secret for digest authentication ...
[Fri Nov 25 01:59:41 2011] [notice] Digest: done
[Fri Nov 25 01:59:42 2011] [notice] Apache/2.2.21 (Unix) DAV/2 configured -- resuming normal operations
[Fri Nov 25 03:23:14 2011] [notice] caught SIGTERM, shutting down
[Fri Nov 25 03:27:36 2011] [notice] Digest: generating secret for digest authentication ...
[Fri Nov 25 03:27:36 2011] [notice] Digest: done
[Fri Nov 25 03:27:37 2011] [notice] Apache/2.2.21 (Unix) DAV/2 configured -- resuming normal operations
[Fri Nov 25 08:52:27 2011] [notice] caught SIGTERM, shutting down
[Fri Nov 25 08:52:43 2011] [notice] Digest: generating secret for digest authentication ...
[Fri Nov 25 08:52:43 2011] [notice] Digest: done
[Fri Nov 25 08:52:44 2011] [notice] Apache/2.2.21 (Unix) DAV/2 configured -- resuming normal operations
[Fri Nov 25 09:21:39 2011] [notice] caught SIGTERM, shutting down
[Fri Nov 25 09:21:57 2011] [notice] Digest: generating secret for digest authentication ...
[Fri Nov 25 09:21:57 2011] [notice] Digest: done
[Fri Nov 25 09:21:58 2011] [notice] Apache/2.2.21 (Unix) DAV/2 configured -- resuming normal operations
[Mon Nov 28 01:06:58 2011] [notice] caught SIGTERM, shutting down
[Mon Nov 28 01:07:58 2011] [notice] Digest: generating secret for digest authentication ...
[Mon Nov 28 01:07:58 2011] [notice] Digest: done
[Mon Nov 28 01:07:59 2011] [notice] Apache/2.2.21 (Unix) DAV/2 configured -- resuming normal operations

Comment: http://:8080 ??? why is there port 8080 standart is 80 and what kind of adres is that ? you should put http://yourdomain.com or your ip
Comment: Linux 6? I believe time machine is not yet invented. Latest version of Linux is 3. You are talking about RHEL/CentOS version 6. Please correct it in your question.
Answer: There is nothing in the error log that you provided that suggests there is any problem, with apache running.
Have you really configured your system to listen on port 8080? Check the Listen statement in /etc/httpd/conf/httpd.conf it should be something like
Listen 8080

if you have. If it says
Listen 80

Then apache is listening on the standard port and you can contact it with http://<servername>.
Edit:
Assuming Linux 6 means RHEL6 or CentOS6 then you most likely haven't opened port 8080 on your firewall.You can open port 8080 with the following command
iptables -I INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT

If that works then don't forget to save the firewall configuration with
service iptables save

Comment: yes the listening port is 8080.
Comment: i have also checked http://:8080 but in the browser it shows page cannot be displayed.
Comment: Check your firewall is allowing traffic on port 8080 - see my edit.
Comment: i have the firewall is not running on , that means port 8080 is allowable,but still i am unable to access apache in web browser.
Comment: In that case your problem lies elsewhere.


SVN parent listing returns 403 when using authz

Question: I have an svn set up at svn.example.com
I have the SVNParentPath set to list all repos in a directory.
When I enable my AuthzSVNAccessFile the listing page returns a 403 while I can correctly access repos directly at svn.example.com/repo name.
Apache conf:
<VirtualHost *:80>
        ServerName svn.example.com

        DocumentRoot /var/www/svn

        <Location />
                DAV svn
                AuthType Basic
                AuthName "svn.example.com"
                AuthUserFile /etc/apache2/svn/users.passwd
                AuthzSVNAccessFile /etc/apache2/svn/authz
                SVNParentPath /var/svn
                SVNListParentPath on

                Require valid-user
        </Location>

</VirtualHost>

Authz File:
[groups]
admin = user1. user2, user3

[/]
@admin = rw

Here is what I see in the error log;
The URI does not contain the name of a repository.  [403, #190001]
Could not fetch resource information.  [500, #0]
Could not open the requested SVN filesystem  [500, #2]
Could not open the requested SVN filesystem  [500, #2]

Access Log
svn.example.com:80 *myIP* - user1 [18/Nov/2010:13:56:53 +0000] "GET / HTTP/1.1" 403 274 "-" "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7"

Answer: On further review, I second iiegn's answer.  I was able to remove the problem with SVN 1.6.13 by adding a trailing slash and an alias without the slash like the article suggests.

Previous Response:
I found an answer to this on StackOverflow at https://stackoverflow.com/questions/488778/how-do-i-list-all-repositories-with-the-svnparentpath-directive-on-apachesvn, and it states to add:
SVNListParentPath On

This matches the what's at http://svnbook.red-bean.com/en/1.5/svn.ref.mod_dav_svn.conf.html, where it states:

SVNListParentPath On|Off
When set to On, allows a GET of SVNParentPath, which results in a listing of all
repositories under that path. The default setting is Off.

This should fix the 403 problem.
Comment: I already have SVNListParentPath On, as shown in my question. This works when AuthzSVN is disabled, but when AuthzSVN is enabled I get the 403.
Comment: Whoops!  Sorry about that.
Comment: I have auth using AuthType Basic and a file and found the same issue.  Adding SVNLIstParentPath fixed the issue.  Wierdly it's worked without that for years.
Answer: ...have you tried a <Location /svn/> - with trailing slah! there: http://www.svnforum.org/2017/viewtopic.php?t=6443
people seem to have solved the problem for the 'non root-dir case.'
...then, at least, you know where to look further (mod-rewrite...?).
Comment: Yeah, that does work, but I want the listing in the root of the domain (svn.exmaple.com rather than the redundant svn.example.com/svn/).
Answer: AuthzSVNAnonymous On
AuthzSVNNoAuthWhenAnonymousAllowed On
Satisfy Any

Firstly you need the Satisfy Any directive, also you will need the Anonymous lines if running a combined open / auth repo (i.e. I have some areas containing open source some closed source).
As I blogged here on upgrade: http://www.saiweb.co.uk/linux/mod_authz_svn-mod_dav_svn-prompting-for-password
Verify that SVNParentPath /var/svn path exists at /var/svn and it is accessible and writable by the apache use, chances are you left this owned by root:root chown -R apache:apache /var/svn
Comment: Thanks for your comments - I don't want any anonymous access - I want it to always prompt for a user - but I want the root to list accessible repos (i.e repos the user has permission to read). At the moment even authorised users get 403 on the parent path while repos do work.

I have checked perms on /var/svn they are correct
Comment: The error log `Could not open the requested SVN filesystem  [500]` suggests otherwise, are you running with SELinux enabled? what are the results of `getenforce` ? can you please also provide a line from the access_log that shows the URI causing the 403?
Comment: It's the root path (svn.example.com) that is causing the 403 (line from access log added to my original post). URL's that actually are reading from the SVN file system (evn.example.com/repos1) work as expected.

getenforce: command not found
Comment: I found that the "Could not open the requested SVN filesystem [500]" message was actually coming from the request for a favicon (svn.example.com/favicon.ico), I've blocked that and no longer get the above error but I still get the 403 errors
Answer: I'm having the same issue, hosting Subversion on its own subdomain. It seems like there needs to be a configuration like [],  but that seems to just cause a silent error, rendering the file to be ignored altogether. Here's the jist of a workaround that I can't get to work, but might give you some ideas:

Redirect / to /index/ (or whatever suits your taste)
Duplicate the <location /> section and rename the first one to <location /index/> section
Add a rewrite rule matching /index/* to redirect to /$1
Add an [/index/] section to the authz file

I spent a few minutes trying this out, but didn't have much luck. I'll update this answer if I find a way to make that work, or a better solution.
Answer: I had the same problem and found the following workaround. Main idea is to not apply "AuthzSVNAccessFile" to the root but apply for the rest. Works for me in apache2.2 (Ubuntu Server 12.04).
<VirtualHost *:80>
    ...
    <Location />
        ...
    </Location>
    <Location /.+>
        AuthzSVNAccessFile /path/to/the/access/file
    </Location>
</VirtualHost>

Update (full config):
<VirtualHost *:80>
    ServerAdmin firstname.lastname@example.com
    ServerName svn.company.lan
    <Location />
        # Enable Subversion
        DAV svn

        # Directory containing all repository for this path
        SVNListParentPath on
        SVNParentPath /opt/subversion

        # LDAP Authentication & Authorization is final; do not check other databases
        AuthzLDAPAuthoritative on
        AuthBasicProvider ldap

        # Do basic password authentication in the clear
        AuthType Basic

        # The name of the protected area or "realm"
        AuthName "Subversion Repository"

        # The LDAP query URL
        # Format: scheme://host:port/basedn?attribute?scope?filter
        # The URL below will search for all objects recursively below the basedn
        # and validate against the sAMAccountName attribute
        AuthLDAPURL "ldap://dc1.company.com/dc=serv,dc=company,dc=com?sAMAccountName?sub"
        AuthLDAPBindDN "CN=svn1user,OU=ou1,DC=company,DC=com"
        AuthLDAPBindPassword "PASS"

        # Require authentication for this Location
        Require valid-user
    </Location>

    # <LocationMatch /.+> is a really dirty trick to make listing of repositories work (http://d.hatena.ne.jp/shimonoakio/20080130/1201686016)
    <LocationMatch /.+>
        AuthzSVNAccessFile /opt/subversion/subversion.perm
    </LocationMatch>
</VirtualHost>

Comment: No, it wouldn't, please have a look to the answer again, I've added a full config that we use in production.


How to display the vowels instead of just counting it(vowels)?

Question: Here's a code that counts the vowels. How to display the vowels instead of just counting them?.
System.out.println("Enter the String:");

String text = we.readLine();

int count = 0;
for (int i = 0; i < text.length(); i++) {
    char c = text.charAt(i);
    if (c=='a' || c=='e' || c=='i' || c=='o' || c=='u') {
        count++;
    }
}
System.out.println("The number of vowels in the given String are: " + count);

Comment: How did you display the message `The number of vowels in the given String are:`?
Comment: I'm not even entirely sure what you're asking here. Are you wanting to display how many occurrences for each vowel is present?
Comment: instead of counting how many vowels,the output must show the vowels. example "programming" the vowels are: o a i
Answer: For an alternate, you can create a char array of vowels, turn the String into a char array and compare each index:
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
String text = "Programming";

for (char c : text.toCharArray()) {
    for (char vowel : vowels) {
        if (c == vowel) {
            System.out.println(text + " contains the vowel: " + vowel);
        }
     }
}