ST_PointN to get Points from Geometry Column

Question: I have a Shapefile from which I am extracting Geometry column and storing it into Table.
This is sample data stored in Geometry column which has 432 points.

0x000000000104AC010000AB3E57ABBBC4384127A08938705B57414F401361C3C43841C9E53F846C5B574190A0F8E1F6C438410F0BB5766E....

Now I want to extract each and Every point i.e. 432 points from the Geometry column and store it into another table. For that I am using ST_PointN column but it only gives me 1 point at a time. ST_NumPoint will give me 432 number but not all the points.
How do I extract each and every point from Geometry column and store it into DB?
Cheers,
Comment: The answer that I gave to [this question](http://stackoverflow.com/questions/12809201/storing-point-column-from-shapefile/12809687 "this question") will be helpful to you.
Comment: I didn't quite get it. You want to read the points from a geometry and create one row for each point in another table. Is that it?
Comment: What is the problem with using ST_PointN?
Comment: If i use ST_PointN it will give me one point at a time. How can I extract all the points?
Answer: Take a look in first example of ST_PointN documentation:
https://postgis.net/docs/ST_PointN.html
and pay attention to generate_series part.
It seems, your geometry is Linestring? Assuming, your geometry is in 'lines' table and you want to create 'points' table, something like that should work:
SELECT ST_PointN(a.the_geom, generate_series(1, ST_NPoints(a.the_geom)))
INTO points
FROM lines a;

In case, your original geometry is polygon, you have to tweak that query little bit, because ST_PointN takes linestrings as parameter:
SELECT ST_PointN(
    ST_ExteriorRing(a.the_geom),
    generate_series(1, ST_NPoints(a.the_geom) - 1)
)
INTO points
FROM lines a;

First and last point will be same in ExteriorRing of polygon. It's up to your needs, whether you use ST_NPoints(a.the_geom) - 1 or ST_NPoints(a.the_geom). In first case, first point will be present also as last point.
Comment: Thanks for this. But it seems that I can't run this query on SQL Server.
Comment: Sorry! My mistake, I didn't notice you answered about SQL Server, that example works with PostgreSQL.


Comparing numbers in EL expression does not seem to work

Question: In JSP, I want to compare two variables
If I do:
<c:set var="pagerTotDisp" value="9"/>
<c:if test="${pagerTotDisp > 8}">
  pagerTotDisp above 8
</c:if>

It displays "pagerTotDisp above 8" as expected
<c:set var="TotalPages" value="10"/>
<c:if test="${TotalPages > 2}">
  TotalPages above 2
</c:if>

It displays "pagerTotDisp above 8" as expected
But then if I do
<c:set var="pagerTotDisp" value="9"/>
<c:set var="TotalPages" value="10"/>
<c:if test="${TotalPages < pagerTotDisp}">
  This condition is not true. This text should not be displayed
</c:if>

It displays "This condition is not true. This text should not be displayed".
What's going on?
Is that JSP not being able to handle two variables in a same condition??
thanks
Answer: You're hardcoding the value in the value attribute of <c:set>. The <c:set> treats the hardcoded values as String. EL is therefore also evaluating them as String. Lexicographically, 9 is greater than 10, because 9 is at a further numerical position than 1.
There are two ways to solve this:

Set the value via an EL expression. It will be interpreted as Long instead of String.
<c:set var="pagerTotDisp" value="${9}" />
<c:set var="TotalPages" value="${10}" />

Or, use <fmt:parseNumber>, which would be the only solution if you have those as String variables from elsewhere which you have no control over.
<fmt:parseNumber var="pagerTotDisp" value="9" />
<fmt:parseNumber var="TotalPages" value="10" />

Comment: thanks! it worked. You might want to add that the fmt taglib needs to be added:
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
Answer: It treats both values as Strings, and compares them lexicographically.
Try
<c:set var="pagerTotDisp" value="${9}"/>
<c:set var="TotalPages" value="${10}"/>
<c:if test="${TotalPages < pagerTotDisp}">
  This condition is not true. This text should not be displayed
</c:if>


Best way to indicate L.H over in piano

Question: I have piano sheet music that has this:

But I wanted to change the right hand clef to be lower to get rid of all the ledger lines:

But then I realized I could put the left hand over part on the bottom staff like this:

I am just wondering:

what is the most common thing to do in a situation like this?
Is it too jarring changing the clef and back so quickly and in the middle of a measure?
Is it really necessary to write "L.H. over" or something like that?  (If so, what is the best thing to write?).  Or should the pianist "just know"?
Comment: The third version is easiest to understand. If you think a hint is necessary, L.H. is sufficient
Answer: Firstly, piano players would much prefer to see an 8va (even over a long stretch) to an octave clef —  octave clefs are not for piano.
Having said that, that octave of C's in the bass isn't even low enough to require an 8va — two leger line below bass clef is instantly identifiable as C, and the interval of an octave is quite recognisable.  (See some of the examples in: Why use 5 or more ledger lines below the bass clef instead of ottava bassa lines for piano sheet music?.)
So, your third option would be fine if you simply got rid of the octave clef:

This type of brief clef change isn't too bad or uncommon for piano (as long as it's not interrupting a melodic phrase).

When necessary, left and right hands are usually indicated with the Italian abbreviations: m.s. and m.d. (for mano sinestra and mano destra) respectively, though French: m.g. and m.d. (main gauche and main droite) are often seen, and English: LH and RH would also be fine.
Another way to separate each hand's part on the same staff is with half bracket symbols: ⸢ & ⸤, as seen in arpeggiated chord and half bracket symbol - what does it mean? (piano).
Hand crossing can be marked with sopra for over, and sotto for under.  But this is not required in your example — it's obvious that the left hand has to go over.

Each hand usually sticks to a stave of its own, but it is sometimes okay to move one hand's voice across to the other staff (and I think it makes sense for this passage).  My proposal is below, but it is hard to tell if this would work for the rest of the piece.  Note the position of the rest.
Answer: Of the solutions you suggest the third solution is the best, particularly as it makes it clear that you want a half note. There are other, even better solutions (see the answer by @ElementsinSpace). No pianist would have any trouble understanding what you mean. There's absolutely no need to add "over" and "L.H." is probably superfluous as well.
Answer: TL;DR
Sample 3 is the way to go. It's fine to change clefs, and no "over" indication is needed. This is clearly illustrated in a passage from Beethoven's "Pathetique" sonata (Op. 13, mm. 49–56). The right hand repeatedly crosses over the left, indicated only by clef changes in the right-hand part.

(Image source: IMSLP)

1. What is the most common thing to do in a situation like this?
For a single note/chord, it can be written as in the third example. In the below passage from Debussy's "Le Petite Negre" (mm. 6–11) the hand-crossing (mm. 9–11) is given no explicit indication, but is clear to the pianist.

(Image source: IMSLP)
2. Is it too jarring changing the clef and back so quickly and in the middle of a measure?
Not at all. This is quite common. Chopin does this at the end of his etude in Gb major, Op. 10 No. 5. For the penultimate chord, the left hand jumps to the treble clef, then back to the bass clef.

(Image source: IMSLP)
3. Is it really necessary to write "L.H. over" or something like that? (If so, what is the best thing to write?). Or should the pianist "just know"?
It's not necessary to give an explicit indication (the above Debussy, for example). However, it is sometimes done when the extra clarity is needed. The below image is the final measure of Serge Bortkiewicz's Prelude III in E major (Op. 40, 1931, first edition)

(Image source: IMSLP)
The left hand starts the arpeggiation from the bass staff, the right hand takes over in the treble staff, but the left hand then crosses over the right to play the final note of the arpeggio. "M.S." (mano sinestro) is the Italian abbreviation for "Left Hand", and reinforces the use of stem direction as clarification of how the arpeggio should be played.
Other options for hand-crossing
Third staff
When the hand-crossing is extensive, it can be easier to read by adding a third staff. Liszt's etude "Un Sospiro" does this, along with stem direction to indicate which hand should play the given note. Measure 3 and 4 are shown here.

(Image source: IMSLP)

A related notation is discussed in What does the L-shaped symbol attached to C5 and G4 on the top staff mean?. In this case the notation indicates when the left or right hand should play a note that would otherwise be understood as played with the other.

Best way to indicate L.H over in piano


Como usar o new em SQL?

Question: Meu objetivo é: assim que inserir um elemento em banco1.Clientes o mesmo seja inserido em banco2.Clientes através de uma trigger. Caso esse elemento já esteja no banco, deve haver um update. Mas não consigo usar o NEW corretamente.
Código da trigger:
DELIMITER $$
CREATE TRIGGER insereBanco1 AFTER INSERT
ON banco1.clientes FOR EACH ROW

BEGIN
    /* insercao */
    BEGIN
            IF (NEW.id NOT IN (SELECT id FROM banco2.Clientes)) THEN
            INSERT INTO banco2.Clientes VALUES (NEW.id, NEW.nome, NEW.dat_nascimento, NEW.cpf, NEW.rg, NEW.endereco,
            NEW.numero, NEW.bairro, NEW.cidade, NEW.estado, NEW.cep);
            ELSE
                UPDATE banco1.Clientes, banco2.Clientes SET banco2.Clientes.nome = banco1.Clientes.nome,
                banco2.Clientes.dat_nascimento = banco1.Clientes.dat_nascimento, banco2.Clientes.cpf = banco1.Clientes.cpf,
                banco2.Clientes.rg = banco1.Clientes.rg, banco2.Clientes.endereco = banco1.Clientes.endereco, banco2.Clientes.numero = banco1.Clientes.numero,
                banco2.Clientes.bairro = banco1.Clientes.bairro, banco2.Clientes.cidade = banco1.Clientes.cidade, banco2.Clientes.estado = banco1.Clientes.estado, banco2.Clientes.cep = banco1.Clientes.cep
                WHERE banco1.Clientes.id = banco2.Clientes.id;
            END IF;
    END;
END;

$$

O erro:
Error Code: 1146. Table 'banco1.NEW' doesn't exist

Comment: SQL é a linguagem, e parece que seu problema é específico da linguagem. MySQL é o servidor em si.
Comment: Mude o INSERT para algo assim: INSERT INTO BANCO2.CLIENTES VALUES ( new.id, new.nome....)

Retire a constraint da tabela CLIENTES, por enquanto, para você ver como os registros estão sendo inseridos. Quando estiver tudo correto habilite a constraint.
Comment: Reginaldo, boa tarde! Fiz as devidas alterações, e agora o erro é o 1442: "Error Code: 1442. Can't update table 'clientes' in stored function/trigger because it is already used by statement which invoked this stored function/trigger."
Comment: Inseri a trigger modificada no topico
Answer: Você está misturando o banco1 e o banco2 no update. Embora seja possível, é muito mais fácil de ler e implementar usando as variáveis do NEW que estão disponíveis dentro do escopo da trigger.
Remova todas as referências a banco1.Clientes do update e as substitua pelos valores equivalentes de NEW.
Algo como:

CREATE TRIGGER insereBanco1 AFTER INSERT
ON banco1.clientes FOR EACH ROW
BEGIN
    IF (NEW.id NOT IN (SELECT id FROM banco2.Clientes)) THEN
      INSERT INTO banco2.Clientes VALUES (
        NEW.id,
        NEW.nome,
        NEW.dat_nascimento,
        NEW.cpf,
        NEW.rg,
        NEW.endereco,
        NEW.numero,
        NEW.bairro,
        NEW.cidade,
        NEW.estado,
        NEW.cep);
    ELSE
        UPDATE banco2.Clientes
           SET banco2.Clientes.nome = NEW.nome,
               banco2.Clientes.dat_nascimento = NEW.dat_nascimento,
               banco2.Clientes.cpf = NEW.cpf,
               banco2.Clientes.rg = NEW.rg,
               banco2.Clientes.endereco = NEW.endereco,
               banco2.Clientes.numero = NEW.numero,
               banco2.Clientes.bairro = NEW.bairro,
               banco2.Clientes.cidade = NEW.cidade,
               banco2.Clientes.estado = NEW.estado,
               banco2.Clientes.cep = NEW.Clientes.cep
        WHERE banco2.Clientes.id = NEW.id;
    END IF;
END;

Como usar o new em SQL?


Tautology, Valid, Contingent, Unsatisfiable, Contradiction: relationship?

Question: I am trying to clear my doubts about various terms: tautology, contradiction, contingent, satisifiable, unsatisfiable, valid and invalid. I have read on them from various sources and was thinking about them. I am putting all my understanding below in points. Some points are definitions straight up from other sources, so they must be correct. Some points I have prepared from understanding I got after reading and thinking. I need confirmation whether they (below text in quotes / highlights) are correct or not.

These are definitions:

Tautology:  a formula or assertion that is true in every possible interpretation (that is, for all assignment of values to its variables). Ref
Contradiction:  a formula or assertion that is false in every possible interpretation.
A formula that is neither a tautology nor a contradiction is said to be logically contingent.
  Such a formula can be made either true or false based on the values assigned to its propositional variables.
A formula is satisfiable if it is true under at least one interpretation.
  So, its either contingent or tautology. Ref
If a logic is a contradiction then it is said to be unsatisfiable.
A formula is valid only if it is tautology. Ref
A formula is invalid if it is contradiction or contingent.

Based on these definitions, I tried preparing diagram highlighting how these concepts overlap:

Based on this diagram, I tried to give answers to some problems.
For example, what is negation of tautology? From above diagram, I felt that it could be either contradiction or contingent. But seems that I was wrong. Above diagram means:
"Given an assertion, if it is not tautology, it can be either contradiction or contingent."
But it does not means:
"Negation of assertion which is tautology can be contingent or contradiction"
I asked this doubt earlier. As pointed out by J.G. in his comment, that I was simply negating definitions above, where I should have actually tried investigating how model (set of values assigned to variables of formula) satisfying given formula behaves for negation of that formula. It took a while for me to grasp that. However I feel I understand it now. I have come up with  following relations of nature of any given assertion and nature of its negation:

Purpose of above table: Given any assertion, above table gives nature of its negation.
Purpose of below table: Given fact that certain assertion is not of certain nature, below table tells what could be possible nature of that assertion.
(I have given examples in brackets to support the facts.)

Can someone please confirm that my understanding which I put above in various points in yellow highlights / quotes is indeed correct. I dont know if I am overthinking. But I just want exhaustive understanding and know all possibilities, especially because in exam, they ask truthfulness of subtle fact and check out understanding. So trying to know and think exhaustively beforehand.
Comment: The bottom part of this question is new and not included in the previous question.
Comment: I will like people to hold on. I am doing an edit to extend bottom part. Also that old question is not fully answered. I touched this topic long back and left without conclusion as I did not had time to dig deep due to exams. I completely forgot that question. I wanted exhaustive relations between all those terms. The answer on older question touches only few terms (answerer also said so in the comments on the answer, may be because some terms are old usage).
Comment: @DougSpoonwood done with the editing. Added all facts which I can think exhaustively. Can you please confirm if they are correct?
Comment: Your [previous question](https://math.stackexchange.com/questions/3081783/understanding-connection-between-terms-tautology-contradiction-contingent-sat) already received answers.
Comment: The table above with 15 rows is quite complicated... As per previous answers, there are two **basic** cases : *(i)* the formula $\varphi$ is a *tautology*, in which case its negation $\lnot \varphi$ is *unsatisfiable*. Reason why : if $\varphi$ is TAUT, then every truth assignment satisfies it. Thus, no truth assignment will satisfy its negation.
Comment: *(ii)* The formula $\varphi$ is *satisfiable* : this means that **some** (one, many, possible all, but at least one) truth assignment will satisfy it. From it, the only thing we can conclude is that its negation $\varphi$ is **not** a *tautology* (same argument above).
Comment: Yes I get both cases. I feel case (i) corresponds to point 10 in my question and case (ii) corresponds to point 9. But exam asks True/False questions like: (a) if assertion is invalid, then its negation can be invalid (b) if assertion is invalid, then its negation can be unsatisfiable (c) if assertion is not a tautology, then it can be valid (d) if assertion is not invalid, then it can be unsatisfiable. As per facts in tables: (a) True (b) False (c) False (d) False. But first need someone to confirm those tables. (I just realized I missed, "negation of contingent" and "not a contingent")
Answer: The notions and their negations will get clearer once you realize the meta-logical quantifications they involve, and how these quantifications systematically behave under negation.
All the definitions you listed quantify over interpretations: A statement is valid iff it is true under all interpretations, satisfiable iff it is true under some interpretation, contradictory iff it is valid under no interpretation, and so on.
In general, we have

"not all interpretations" = "there exists some interpretation such that not";
"not some interpretation" = "for all interpretations not";
"not no interpretation" = "there exists some interpretation such that".

So let's apply these equivalences to each of the definitions*:
<code>-------------------------------------------------------------------------------------------------------------------------
Notion          Definition                           Negation of definition                  Negation of notion
-------------------------------------------------------------------------------------------------------------------------

tautological    all i. true (= no i. false)          not all i. true (= some i. false)       contradcictory or contingent

contradictory   all i. false (= no i. true)          not all i. false (= some i. true)       satisfiable
(= unsatisfiable)

contingent      some i. true and some i. false       not (some i. true and some i. false)    contradictory or tautological
                                                     = (not some i. true) or (not some i. false)
                                                     = no i. true or no i. false
                                                     = all i. false or all i. true

satisfiable     some i. true (= not all i. false)    no i. true (= all i. false)             contradictory

unsatsifiable   no i. true (= all i. false)          some i. true (= not all i. false)       satisfiable
(= contradictory)

valid           (see tautological)
(= tautological)

invalid         not valid = not all i. true          all i. true                             tautological
</code>
So we have
<code>---------------------------------------------------------------------
Notion              Negation               can but doesn't have to be
---------------------------------------------------------------------
not tautological    = not valid
                    = invalid
                    = contradictory        unsatisfiable (if contradictory),
                      or contingent        satisfiable (if contingent)

not contradictory   = not unsatisfiable    tautological,
                    = satisfiable          contingent,
                                           invalid

not contingent      = contradictory        unsatisfiable, invalid (if contradictory),
                      or tautological      satisfiable (if tautological)

not satisfiable     = unsatisfiable        invalid (must be)
                    = contradictory

not valid           = invalid
                    = not tautological
                    = contradictory        unsatisfiable (if contradictory),
                      or contingent        satisfiable (if contingent)

not invalid         = valid                satisfiable (must be)
                    = tautological
</code>
The problem with the negations your first table is that your negation is to strong: The negation of "all interpretations" is just "not all interpretations", i.e. "there are some interpretations such that not", and not (as you did) "no interpretation". So the negation of "valid" is just "not true under all interpretations", which can be contradictory or contingent, and not "true under no interpretation", which would be contradictory. Likewise, the negation of contradictory (= false under all interpretations) is just "not false under all interpretations", i.e. "true under some interpretations", which satisfiable, and not the stronger statement "true under all interpretations", which would be tautological.
The diagram you made is correct, and explicates the misunderstanding as follows: Negation does not mean opposite. Negating a notion does not get you to the other extreme of the diagram, only to the complementary half, i.e. the entire part not covered by that notion: "not contradictory" gives you everything in the range of "satisfiable", not just the extreme "tautology". "not tautological" just gives you "invalid", not the opposite "contradictory". "Not satisfiable" is "contradiction", not "invalid", "not invalid" is "tautology", not "satisfiable", and lastly, if something is "not contingent" it must be in either "contradiction" or "tautology". That covers all the possible cases.
* Note that in the case of first-order logic, sometimes a distinction is made between a formula that is valid (true in all first-order interpretations) and one that is tautological (a first-order instance of a propositional tautology, i.e. one that has the form of a tautological propositional formula but with predicate logical formulas in the place of propositional variables). All tautological formulas are also valid, e.g. $\forall x P(x) \lor \neg \forall x P(x)$, but not all first-order validities are merely instances of propositional tautologies, e.g. $\forall x (x = x)$.
Comment: Ohh I just revised question to add a line in each of those table. Will take some time to read your answer.
Comment: Please dont feel annoyed, but I found the language of a answer a bit difficult to get hold of. So, I skipped to your tables. Very first row of your first table says `Notion=tautological` and `Negation of notion=contradcictory or contingent`. That is definitely not correct, right? I said that already in my above question referring to exact same question I asked more than [an year earlier](https://math.stackexchange.com/questions/3078685). Negation of tautology is contradiction (which is unsatisfiable), it cannot be contingent, right? Or am I misinterpreting your answer?
Comment: I just realized that you were asking two different questions in your posts, and my answer was about one question (and what I said there certainly is correct) while in this post you seem to be more interested in something different (for which what I wrote does not apply). I'll rewrite my answer clarify the difference and address both.
Comment: also can you please point out **(1)** if I made any mistake in those two tables **(2)** if there is any piece of information (about relation between those terms) which those two tables dont contain
Comment: Thank you for the tables @lemontree, they are very helpful. I noticed that the first table treats "tautological" and "valid" as equivalent, whereas other authors draw a distinction bewteen the two by defining a first-order tautology as a WFF whose truth-functional form is a tautology and that the set of FOL tautologies is a strict subset of logically valid WFFs (i.e. those that are true under all interpretations). Would you know why this is? I'm not sure which definition to go with.
Comment: @user51462 The distinction is not universally made, some treat the two as synonymous, but it is perhaps better to avoid any confusion. I'll add a note.
Answer:

(Please refer to point #4 below for a refinement of the above diagram.)

Every formula that's not valid is invalid.
Every formula that's not satisfiable is unsatisfiable.

On the other hand,

The negation of every valid formula is unsatisfiable (not merely invalid).
The negation of every satisfiable formula is invalid (not necessarily unsatisfiable).

Equivalently:

Valid and Invalid are complementary sets.
Satisfiable and Unsatisfiable are complementary sets.
The negation of every unsatisfiable formula is valid (not merely satisfiable).
The negation of every invalid formula is satisfiable (not necessarily valid).

To wit:

$\big(\forall x\,P(x)\big)$ and its negation $\big(\exists x\,¬P(x)\big)$ are both satisfiable.
$\big(\forall x\,P(x)\big)$ and its negation $\big(\exists x\,¬P(x)\big)$ are both invalid.
$(\forall x\:x=x)$ is valid, and its negation $(\exists x\,x\ne x)$ is unsatisfiable, not merely invalid.
$(\exists x\,x\ne x)$ is unsatisfiable formula, and its negation $(\forall x\:x=x)$ is valid, not merely satisfiable.

Tautology:  a formula or assertion that is true for all assignment of values to its variables
Contradiction:  a formula or assertion that is false in every possible interpretation.
A logically contingent formula can be made either true or false based on the values assigned to its propositional variables.

Notice that collectively, these three terms are being defined in terms of a formula's truth-functional form; as such, in first-order logic, the contingent formulae actually form a proper superset of the satisfiable but invalid formulae; in this case:

$(\forall x\:x=x)$ is contingent and (first-order) valid.

$(\exists x\,x\ne x)$ is contingent and (first-order) unsatisfiable.

These corollaries are false:

A formula is (first-order) valid only if it is tautology.
A formula is (first-order) invalid if it is contradiction or contingent.

Related: Complement versus Negation


Use Fusion Table like a database with PHP and how to dismiss the prompt page when using oauth

Question: I am developing a PHP application which would use Google Fusion Tables only as a database in the background. The application includes a simple login section for basic security.
I downloaded the google-api-php-client and successfully built up a connection to my Fusion Table using oAuth. Thats fine. However, I want to get rid off the prompt screen, that says that my registered application want to access Fusion Tables and asks me to allow or disallow.
Since the app would use a Fusion Table being hosted on my account, I think there is no need to ask this question from the user.
Can you advise me any workaround to this? I plan to keep it as simple as possible, and would be really happy if there would be a way to get the authentication done without prompting the user with any additional screens.
Thanks so much for your help!
https://developers.google.com/fusiontables/docs/articles/oauthfusiontables
Answer: The OAuth prompt you describe is needed if you want to access a users Fusion Table, so you basically ask the user for access to his account so you can use it to create tables and stores/retrieve data.
But in your case you want to give your users access to your Fusion Tables that you created with your account. Google introduced for this use case so called Service Accounts.
All you have to do is:

create a Service Account (you can do this in the Google API console -> "Access API")
download the private key
give the Service Account access to you table (click on the "Share" button in the Fusion Tables web UI)
use the Service Account in your code to access Fusion Tables

Some time ago I created a simple UPDATE example using a Service Account.
Comment: Hey Odi,Thanks for you answer. I followed the steps you have advised and would have a couple of questions, which I will include in the next comment.
Answer: Also, if you really do not need the sharing, visualization and publishing features of Fusion Tables, and just need a cloud database, consider using Google Cloud SQL which is designed for that usage.
https://developers.google.com/cloud-sql/docs/introduction


Mail don't reach server

Question: I have VPS and serve several domains.
DNS/MX config should be ok, as for *.com domains mails are both sent and received.
Problem is with my country domain - *.hr (Croatia) - mails are sent, but replied/new mail never reach my server (even tail -f log but nothing happens).
MX records are standard - mail.domain-name.com/hr
Can it be something specific with country domain?
Thanks,
Vedran newbie in server world
EDITED:
Site is prva-liga.hr
http://www.intodns.com/prva-liga.hr
ERROR: Some of your DNS servers do not have A records at all. I could not find any A records for the following DNS servers:
ns2.tkojemile.com
ns1.tkojemile.com
You must have A records for all of your nameservers.
But let's say for *.com domain mivean.com - all works really fine with same configuration.
http://www.intodns.com/mivean.com
Don't have a clue even when reading tons of content on this issues.
Thanks,
Vedran
ADITIONAL DATA:
Zone file:
$TTL 10800
@ IN SOA prva-liga.hr.    postmaster.prva-liga.hr. (
    2014101409  ;serial
    21600    ;refresh after 6 hours
    3600    ;retry after 1 hour
    604800   ;expire after 1 week
    86400 )    ;minimum TTL of 1 day
@    3600    IN    A    22.214.171.124
mail    86400    IN    A    188.8.131.52
ns1    172800    IN    A    22.214.171.124
ns2    172800    IN    A    22.214.171.124
www    3600    IN    CNAME   @
ftp    3600    IN    CNAME   @
cp    86400    IN    CNAME   @
@    86400    IN    MX    10  mail.prva-liga.hr.
@    172800    IN    NS    ns1.tkojemile.com.
@    172800    IN    NS    ns2.tkojemile.com.

Comment: Please don't force us to navigate through an adware-ridden file sharing site. Edit your question and include relevant portions of your file.
Comment: Please name the domain in question.
Comment: This is zone file: http://www.speedyshare.com/HTt2A/zones.txt
Comment: Ok, sorry, I posted zone file in question.
Answer: Its very difficult to debug the problem without knowing more, but the steps you might take would be :

Do a DNS lookup on the MX record for the .hr domain (for example, from a linux box - "dig @184.108.40.206 domainname.hr mx") which will tell you the MX record for the domain.  Make sure the MX records ends with a "." - for example mail.domainname.com. would be correct where mail.domainname.com would not be - common mistake.

Once you know the dns record for the domain, telnet to it on port 25 like so: "telnet mail.domainname.hr"   (no . at the end here) and see if you get a "Helo banner" from your server.   If not, then you should start looking at your firewall if the IP resolves correctly, or your DNS record if it doesn't.
You may also want to use "tcpdump -n port 25" when trying to send mail to your server to see if there is a connection attempt to your mail server.  This will tell if the mail traffic is actually getting to your server but being ignored by Postfix.
Comment: This is output:
[root@server ~]# dig 126.96.36.199 prva-liga.hr mx

; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.23.rc1.el6_5.1 <<>> @184.108.40.206 prva-liga.hr mx
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 28526
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;prva-liga.hr.                  IN      MX

;; Query time: 153 msec
;; SERVER: 126.96.36.199#53(18.104.22.168)
;; WHEN: Wed Oct 15 17:09:24 2014
;; MSG SIZE  rcvd: 30
Answer: The problem is that neither of your listed name servers actually exist.
Who serves .hr?
[me@risby ~]$ dig ns hr.
[...]
;; ANSWER SECTION:
hr.                     14400   IN      NS      dns-hr.univie.ac.at.
hr.                     14400   IN      NS      sns-pb.isc.org.
hr.                     14400   IN      NS      pch.carnet.hr.
hr.                     14400   IN      NS      hr-ns-1.carnet.hr.
hr.                     14400   IN      NS      n3ns.nic.es.

OK, let's ask one of them who serves prva-liga.hr:
[me@risby ~]$ dig ns prva-liga.hr. @pch.carnet.hr.
[...]
;; AUTHORITY SECTION:
prva-liga.hr.           14440   IN      NS      ns2.tkojemile.com.
prva-liga.hr.           14440   IN      NS      ns1.tkojemile.com.

OK, let's ask them about your MX record:
[me@risby ~]$ dig mx prva-liga.hr @ns1.tkojemile.com.
dig: couldn't get address for 'ns1.tkojemile.com.': not found
[me@risby ~]$ dig mx prva-liga.hr @ns2.tkojemile.com.
dig: couldn't get address for 'ns2.tkojemile.com.': not found

I don't know who's supposed to be providing tkojemile.com's DNS infrastructure, but they're not doing a very good job.  Once you pick some working nameservers, the internet should be able to find your mail server, and the mail should flow.  Until you fix this, it won't.
I take your point about mivean.com working, but that's a happy accident, caused by both tkojemile.com and mivean.com being under .com.  When recursing down to the MX record for mivean.com., the nameservers for .com are passing addresses for ns[12].tkojemile.com back as part of the glue.  Queries for zones in .hr don't touch the .com servers, and don't get that handy glue.
Comment: thanks a lot! :)
I completely forgot to add tkojemile domain and dns data to my server. Now it works fine. Thanks once again, you opened my eyes :)

Mail don't reach server


Invalid MEX-file error CascadeClassifier_.mexmaci64, libopencv_ocl.2.4.dylib

Question: I am on OSX  10.10.
I am trying to run a demo of a project which uses the following libraries and programs:

MATLAB R2014b 64-bit.
OpenCV 18.104.22.168 installed through Homebrew.
VLFeat 0.9.20.
mexopencv.

I have run mex -setup in MATLAB which sets the compiler to clang.
The path of VLFeat and mexopencv have been added in the startup.m file in MATLAB.
When I try to run demo_test.m file I get the following errors in MATLAB:
Invalid MEX-file '/Users/maverick/Documents/Project/mexopencv-master/+cv/private/CascadeClassifier_.mexmaci64':
dlopen(/Users/maverick/Documents/Project/mexopencv-master/+cv/private/CascadeClassifier_.mexmaci64, 6): Symbol not found:
__ZN2cv3ocl12getOclMatRefERKNS_11_InputArrayE
  Referenced from: /usr/local/lib/libopencv_superres.2.4.dylib
  Expected in: /Applications/MATLAB_R2014b.app/bin/maci64/libopencv_ocl.2.4.dylib
 in /usr/local/lib/libopencv_superres.2.4.dylib

Error in cv.CascadeClassifier (line 33)
            this.id = CascadeClassifier_(filename);

Error in faceAlign (line 8)
    detector = cv.CascadeClassifier('haarcascade_frontalface_alt2.xml');

Error in regressionFit (line 11)
            [shape, rat, ~, init_s] = faceAlign(img, [], [], R{round_number}, b{round_number}, [], pad, [1:66], 0);

Error in demo_test (line 16)
shape = regressionFit(img, [], R, b);

I know the project works because I have tried it on another computer.
How do I resolve this error and get the project to run? Thanks.
EDIT 1:
This is the output when I run otool -L (equivalent of ldd)...
    $ otool -L /Applications/MATLAB_R2014b.app/bin/maci64/libopencv_ocl.2.4.dylib

/Applications/MATLAB_R2014b.app/bin/maci64/libopencv_ocl.2.4.dylib:
    @rpath/libopencv_ocl.2.4.dylib (compatibility version 2.4.0, current version 2.4.5)
    @rpath/libopencv_core.2.4.dylib (compatibility version 2.4.0, current version 2.4.5)
    @rpath/libopencv_imgproc.2.4.dylib (compatibility version 2.4.0, current version 2.4.5)
    @rpath/libopencv_objdetect.2.4.dylib (compatibility version 2.4.0, current version 2.4.5)
    @rpath/libtbb.dylib (compatibility version 0.0.0, current version 0.0.0)
    /System/Library/Frameworks/OpenCL.framework/Versions/A/OpenCL (compatibility version 1.0.0, current version 1.0.0)
    /usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 52.0.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 159.1.0)

EDIT 2:
This is the output of otool -L on CascadeClassifier_.mexmaci64
$ otool -L Documents/Project/mexopencv-master/+cv/private/CascadeClassifier_.mexmaci64
Documents/Project/mexopencv-master/+cv/private/CascadeClassifier_.mexmaci64:
    /System/Library/Frameworks/Cocoa.framework/Versions/A/Cocoa (compatibility version 1.0.0, current version 20.0.0)
    /usr/local/lib/libopencv_calib3d.2.4.dylib (compatibility version 2.4.0, current version 2.4.10)
    /usr/local/lib/libopencv_contrib.2.4.dylib (compatibility version 2.4.0, current version 2.4.10)
    /usr/local/lib/libopencv_core.2.4.dylib (compatibility version 2.4.0, current version 2.4.10)
    /usr/local/lib/libopencv_features2d.2.4.dylib (compatibility version 2.4.0, current version 2.4.10)
    /usr/local/lib/libopencv_flann.2.4.dylib (compatibility version 2.4.0, current version 2.4.10)
    /usr/local/lib/libopencv_gpu.2.4.dylib (compatibility version 2.4.0, current version 2.4.10)
    /usr/local/lib/libopencv_highgui.2.4.dylib (compatibility version 2.4.0, current version 2.4.10)
    /usr/local/lib/libopencv_imgproc.2.4.dylib (compatibility version 2.4.0, current version 2.4.10)
    /usr/local/lib/libopencv_legacy.2.4.dylib (compatibility version 2.4.0, current version 2.4.10)
    /usr/local/lib/libopencv_ml.2.4.dylib (compatibility version 2.4.0, current version 2.4.10)
    /usr/local/lib/libopencv_nonfree.2.4.dylib (compatibility version 2.4.0, current version 2.4.10)
    /usr/local/lib/libopencv_objdetect.2.4.dylib (compatibility version 2.4.0, current version 2.4.10)
    /usr/local/lib/libopencv_ocl.2.4.dylib (compatibility version 2.4.0, current version 2.4.10)
    /usr/local/lib/libopencv_photo.2.4.dylib (compatibility version 2.4.0, current version 2.4.10)
    /usr/local/lib/libopencv_stitching.2.4.dylib (compatibility version 2.4.0, current version 2.4.10)
    /usr/local/lib/libopencv_superres.2.4.dylib (compatibility version 2.4.0, current version 2.4.10)
    /usr/local/lib/libopencv_video.2.4.dylib (compatibility version 2.4.0, current version 2.4.10)
    /usr/local/lib/libopencv_videostab.2.4.dylib (compatibility version 2.4.0, current version 2.4.10)
    @rpath/libmx.dylib (compatibility version 0.0.0, current version 0.0.0)
    @rpath/libmex.dylib (compatibility version 0.0.0, current version 0.0.0)
    @rpath/libmat.dylib (compatibility version 0.0.0, current version 0.0.0)
    /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 120.0.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1197.1.1)

Am I missing some library? Is the PATH not configured correctly ?
Comment: Look for the opencv ocl library.  But in general you can run `ldd mexfilw.asdf` outside if MATLAB and set `LD_RUN_PATH`.
Comment: clearly missing this symbol __ZN2cv3ocl12getOclMatRefERKNS_11_InputArrayE.  could be that a dylib is missing or is not pathed properly.
Comment: @chappjc : I installed OpenCV library from Homebrew
Comment: @no10downingstreet that doesn't mean the mex file can find it.  Just look for the file yourself
Comment: @chappjc : I didn't understand what you said, sorry. I am on OSX. ldd runs on Linux. Could you please elaborate a little, I'm new to this.
Comment: Search your filesystem for a file like libopencv*.dynlib with ocl or opencl in the file name. Not sure if it starts with libopencv or just opencv. I don't have a Mac.
Comment: Try the `ldd` system command first so you know the exact name of the file you need to find.
Answer: Matlab comes bundled with its own computer vision libraries. So it tries to use them first, even if you have OpenCV installed.
The solution is to move those bundled libraries to another folder (for backup in case something goes wrong) and then sym link the actual OpenCV libraries to the location previously populated by the bundled libraries.
If, after doing this, you get any error, then it is probably because Matlab is using its own library again. Do the same process again for this library too.


Multilanguage setup breaking View results layouts

Question: Background:
We're trying to setup multilanguage options on our site (to allow English/Welsh options). We're using the Internationalization module primarily, with the language detection set to URL.
The problem:
The static content pages work fine, but when a page containing views is translated it seems to break the order and div styling of the Views results.
Any ideas what might be causing this (e.g. have I missed a setting in the Block/View somewhere to apply a div style to the translated version of the page)?
E.g. see below - in pic 2, the results are wrongly shown single column rather than in a 4 column grid, and are displayed before the rest of the main content rather than after):
Comparison of default (www.../resources) and translated (www.../cy/resources) page layouts
Answer: Turns out this was due to an error in the logic of a custom template not taking in to account variable languages.


2nd order linear ODE with constant driving term

Question: I have this DE$$y''+ay'=c $$
I tried with undetermined coefficient method, but the ansatz of particular solution being a zeroth order polynomial obviously doesn't work(LHS is 0). How do I solve this problem? do I have to use variation of parameters or the ansatz is not right?
Comment: You can view it as a DE in $y'$ and solve that using the integrating factor method.

Otherwise your particular integral here will be $y = \frac{c}{a}x$ for example
Answer: Integrating factor method works fine
$$y''+ay'=c$$
use $\mu(x)=e^{ax}$ as integrating factor
$$(y'e^{ax})'=ce^{ax}$$
Integrate
$$y'e^{ax}=c\int e^{ax}dx =\frac ca {e^{ax}}+K$$
$$y'=e^{-ax} \left (\frac ca {e^{ax}}+K \right )$$
$$y'=\frac ca+Ke^{-ax}$$
Integrate again
$$\boxed{y=\frac cax+K_1e^{-ax}+K_2}$$
Answer: Integrating once
$$
y'+ay=c x+C_1
$$
and now the first order linear differential equation with solution
$$
y = \frac{c (a x-1)+a C_1}{a^2}+C_2 e^{-a x}
$$


What does Infimum of Upper Sum and Supremum of Lower Sums mean?

Question: I'm trying to figure out the Darboux Integral definition as it states:
$f$ is integrable if $inf${U($f$,$P$)} = $sup${L($f$,$P$)}, where U($f$,$P$) is the upper sum, L($f$,$P$) is the lower sum of $f$ and $P$ is a parition of $f$.
I'm not understanding what the $sup$/$inf$ of the sums mean. When calculating, they are a finite value (ie. L($f$,$P$) = $\sum_{i=1}^n m_i (x_i - x_{i-1})$)

Consider:

$$f(x) = 2x, x \in [0,1];~ P = \{0,\frac{1}{4},\frac{1}{2},1\}.$$

Since $P$ has 4 elements, n=3, thus 3 subintervals of $[0,1]$, can you definte these 3 subintervals however you want as long as they range [0,1]?
ie. $$[0,\tfrac{1}{4}] \,\cup\, [\tfrac{1}{4},\tfrac{1}{2}] \,\cup\,[\tfrac{1}{2},1] \text{ or } [0,\tfrac{1}{3}] \,\cup\, [\tfrac{1}{3},\tfrac{2}{3}] \,\cup\,[\tfrac{2}{3},1] $$
So to calculate $U(f,P)$ for the first set of subintervals:
$$U(f,P) = \sum_{i=1}^n M_i (x_i - x_{i-1})$$
$$ = f(\frac{1}{4})(\frac{1}{4} - 0)\;+ f(\frac{1}{2})(\frac{1}{2} - \frac{1}{4})\;+  f(1)(1 - \frac{1}{2})$$
$$ = \frac{1}{8} + \frac{1}{4} + 1= \frac{11}{8}$$
Calculate $L(f,P)$:
$$L(f,P) = \sum_{i=1}^n m_i (x_i - x_{i-1})$$
$$ = f(0)(\frac{1}{4} - 0)\;+ f(\frac{1}{4})(\frac{1}{2} - \frac{1}{4})\;+  f(\frac{1}{2})(1 - \frac{1}{2})$$
$$ = 0 + \frac{1}{8} + \frac{1}{2}= \frac{5}{8}$$

First off, can someone confirm that my calculations for upper and lower sums are correct?
Secondly, back to the main question, what is the $inf${U($f$,$P$)} and $sup${L($f$,$P$)} in this? as my $U$($f$,$P$) = $\frac{11}{8}$ and $L$($f$,$P$) = $\frac{5}{8}$.
As I already know that $f$ is integrable, $U$($f$,$P$) = $L$($f$,$P$) only if $f$ is constant, but what is the set in which I'm supposed to take the $inf$ and $sup$ of? As per the Darboux Integral definition, $sup${$L(f,P)$} = $inf${$U(f,P)$} for this function.
.
If someone could clear this up for me it would be greatly appreciated
Comment: I think that $U(f,P)$ and  $L(f,P)$ are viewed as sequences on the partition $P$ and the $inf$ and $sup$ conditions are there because they imply convergance as the partition gets more precise. Your calculations seem correct indeed.
Comment: Darboux sums over a partition are piecewise constant - a lower sum is at most the value of the integral (assuming it exists), and an upper sum is at least the value of the integral. As for $\sup$/$\inf$, those are fundamental concepts in analysis you should understand well.
Comment: @Math1000 , how are lower sums "at most" the value and upper sums "at least" value of the integral in the subinterval? Isn't the lower sum, by definition, the lower bound of the integral (thus the "at least" value) and upper sums are the upper bound of the integral of the subinterval?
Comment: Consider $f(x) = 1 - (1-x)^2$ on $[0,2]$ and the partition $\mathcal P=\{0,1/2,1,3/2,2\}$. The lower sum is
\begin{align}
L_f(\mathcal P) &= f(0)\cdot(1/2-0) + f(1/2)\cdot(1-1/2)+f(3/2)\cdot(3/2-1)+f(2)(2-3/2)\\
&= \frac12\left(0 + 3/4 + 3/4 + 0 \right) = 3/4,
\end{align}
Comment: while the upper sum is
\begin{align}
U_f(\mathcal P) = \frac12\left(f(1/2)+f(1) + f(1)+f(3/2)\right) = \frac12\left( 3/4 + 1 + 1 + 3/4 \right) = 7/4.
\end{align}
The actual value of the integral is
$$
\int_0^2 (1-(1-x)^2)\ \mathsf dx = 4/3.
$$
Answer: Your calculations are fine and that's a good start. The idea of inf/sup of these upper and lower sums is easy to grasp in theory (but not in practice). Thus the value $\inf U(f, P) $ requires you to evaluate all the upper sums for each partition $P$ and then take infimum of all these sums. You can see that it is practically not possible to evaluate these sums for all partitions $P$ (because there are infinitely many partitions of a given interval). The practical method of finding the infimum here is based on the following deep and difficult theorem:

Theorem: Let $f:[a, b] \to\mathbb{R} $ be a bounded function and let $$A= \{U(f, P) \mid P\text{ is a partition of }[a, b] \}, I=\inf\, A$$ then $$I=\lim_{|P|\to 0}U(f,P)$$ where $|P|$ denotes the length of largest subinterval created by $P$.

Now one can take a uniform partition with $n$ subintervals of equal length and evaluate the upper sum over this partition and then take limit as $n\to\infty$ to get the desired infimum.
In your case let $P=\{x_0,x_1,\dots,x_n\}$ where $x_i=i/n$ and then we have $$U(f, P) =\sum_{i=1}^{n}M_i(x_i-x_{i-1})=\sum_{i=1}^{n}\frac{2i}{n}\cdot\frac{1}{n}=\frac{n(n+1)}{n^2}$$ and thus when we take limit as $n\to\infty$ we get the desired infimum as $1$.
Similarly $$L(f, P) =\sum_{i=1}^{n}\frac{2(i-1)}{n}\cdot\frac{1}{n}=\frac{n(n-1)}{n^2}$$ and hence on taking limit the supremum of lower sums is also $1$ and therefore the function $f(x) =2x$ is Riemann integrable on $[0,1]$ with integral $1$.
Comment: Wait, why can you just "take" a partition with subintervals of equal length? Aren't you supposed to take an arbitrary partition $P$ and then apply $||P||\to 0$? Because $\lim\limits_{||P||\to 0} U(f,P)$ doesn't mean just norm of partitions having equal length subintervals must approach $0$ but rather "all partitions with norm in neighbourhood of $0$". No? What am I missing?
Comment: @William : the deep and difficult theorem in my post says that the upper sums will tend to the infimum whenever the norm of partition tends to $0$. This holds for any arbitrary set of partitions. The case of partitions with subintervals of equal length is just a special case of the theorem.
Comment: @William: just to clarify using your own words the set of all partitions with norm in neighborhood of $0$ includes the set of partitions with equal length subintervals and having norm in neighborhood of $0$. So the thing works for uniform partitions as well.
Comment: I'm not sure I follow. But let me explain my thought process, may be you can point out where am I going wrong. $\lim\limits_{x \to 0} f(x)$ is not the same as $\lim\limits_{x \to 0, x \in S} f(x)$ where $S = \{ \frac{1}{n} : n \in \mathbb{N} \}$. Former implies the latter but latter doesn't imply former. So if $\lim\limits_{n \to \infty} U(f,P_n)= L_1$ through a sequence of partitions $(P_n)$, it still isn't limit through *every partition* so there could be a case where $\lim\limits_{n \to \infty} U(f,Q_n)=L_2 ≠L_1$ through a different sequence of partition $(Q_n)$, no?
Comment: @William : your thought process is correct (with example of limit of $f(x) $ as $x\to 0$). The limit $\lim_{|P|\to 0}U(f,P)$ is like $\lim_{x\to 0}f(x)$ (so that it deals with every possible sequence of partitions) and it implies that all things like $U(f, P_n) $ will tend to same limit whenever norm of $P_n$ tends to $0$.
Comment: Okay I may sound really dumb but **if** you **know** $\lim\limits_{x \to a} f(x) = L$ **then** you can comment $\lim\limits_{x \to a, x \in S} f(x) = L$ but it seems to me here, you're using $\lim\limits_{x \to a, x \in S}f(x)$ to calculate $\lim\limits_{x \to a} f(x) $ but in general, $\lim\limits_{x \to a, x \in S} f(x)=L \nRightarrow \lim\limits_{x \to a}f(x)=L$ or that it even exists. How so?
Comment: No @William: we are doing in exactly the reverse of what you propose in your last comment. Check definition for limit as norm of partition tends to $0$. The definition includes all partitions with norms less than $\delta$ and this also includes those partitions with special property that subintervals are of equal length. So the uniform partitions correspond to $x\in S$. To elaborate more we know that the limit via arbitrary partitions exists and equals the  infimum of all upper sums. And hence the limit via uniform partitions also exists and equals the same infimum. Continued...
Comment: @William: the existence of infimum of upper sums is a consequence of the fact that the function being integrated is bounded on interval of integration. The fact that limit of upper sums as norms of arbitrary partitions tend to $0$ equals the infimum of upper sums is formally stated in the deep and difficult theorem. And then we restrict ourselves to uniform partitions and reach the same limit.
Answer: Take infimum (greatest common lower bound) /supremum (lowest common upper bound)  of all the arising values while $P$ ranges over all partitions.
Your calculations are correct and they show
$$\frac58\ \le\ \int_0^12x\, dx=1\ \le\ \frac{11}8$$
Comment: It's supremum of the set $\{L(f,P):P\text{ a partition of }[0,1]\}$, it contains real numbers, and every such set has a unique (possibly infinite) supremum. In your example, $\frac58$ is element of this set, and its supremum is $1$. For any $\varepsilon>0$, one can find a partition $P$ such that $L(f,P)>1-\varepsilon$.
Comment: How do I take the infimum and supremum "of all the arising values while P ranges over all partitions"?
Comment: Find a sequence of partitions for which the lower and upper sums converge to a finite limit (which is the value of the integral).
Comment: Ok thanks again for you guys' help. I have been struggling with this topic for quite some time now. Let me just see if I understand it now... so $P$={0, $\frac{1}{4}$, $\frac{1}{2}$, 1}, $U(f,P)$ = $\frac{11}{8}$ and $L(f,P)$ = $\frac{5}{8}$. $L(f,P)$ $\in$ $P$ $\therefore$ $\frac{1}{2}$ < $L(f,P)$ < 1; $\therefore$ the supremum of that subset of $P$ is 1. Now, $U(f,P)$ = $\frac{11}{8}$, $U(f,P)$ $\in$ $P$ as $P$ $\subseteq$ $\mathbb{R}$, $U(f,P)$ is an supremum of $P$ (as subset of $\mathbb{R}$ has infinte supremums), thus in $P$ 1 < $U(f,P)$ \therefore infimum of $U(f,P)$ is 1.
Comment: Since $sup${$L(f,P)$} = $inf${$U(f,P)$} = 1 $\rightarrow$ $f$ is integrable. Is this correct procedure?
Comment: Your last comment is valid. To actually get close to the supremum, one usually needs infinitely many, finer and finer partitions. That's crucial. You only took one partition. You should calculate for *all*, and then take their supremum.
Comment: Well, for the example, draw the graph of $2x$, the area below it (until the $x$ axis) over $0\le x\le1$ is the area of a right triangle, $1$. A lower or upper sum can also be depicted as area of horizontal-vertical bars below or above the graph of $2x$.


Chrome bug with pointer-events and mouse-scroll?

Question: Fiddle to reproduce:
Resize this until vertical scrollbar appears: http://jsfiddle.net/yxf1v60x/2/embedded/result/
Expected behavior: mousewheel scrolls when used over the yellow area.
Observed behavior: doesn't work in Chrome, works fine in Firefox.

HTML code:

<input />

<input />

CSS code:
html,body{

  overflow:hidden;
  height: 100%;
  width: 100%;
}
.parent {
  pointer-events:none;
  position: absolute;
  z-index:10;
  top:0px;
  left:0;
  right:0;
  bottom:0px;
  background-color:#ff0000;
  height: auto;
  overflow-y:auto;
}
.child {
    pointer-events:auto;
    position: absolute;
    z-index:11;
    top:50px;
    left:0;
    right:0;
    bottom: 0;
    max-height: 100%;
    background-color:#0000FF;
}
.subChild{
    height: 500px;
    background-color:yellow;
    width: 100%;
  }
}

So I'm not sure what's going on here: pointer-events clearly work on the yellow area, since the related input element is clickable. Scrolling via keyboard also works (try with page up/page down with focus on yellow area).
a) Is this a Chrome bug?
b) Can I avoid it while keeping both parent and child absolute positioned? I do not wish to have pointer-events on the parent element.
Comment: Confirmed this on a different use case, and filed a bug: https://bugs.chromium.org/p/chromium/issues/detail?id=818444
Comment: @Labu This seems fixed on version  84.0.4147.89 of Chrome. Sometime between March 2020 and now. You should let them know that they fixed it (without knowing it :-) )
Comment: Hey @Labu, I'm here for our two-year check up. Let's see....yes I see the bug is regressed again. That'll be 50$. See you on our next two-year check up?
Comment: Bug Monopoly? _Go straight to jail!_
Comment: Meant to come back after updating the Chrome ticket, which has now been closed. Thanks for the heads up @pkExec :)
Answer: What is going on: The overflow-y attribute, and with it the scrolling-capability, is on the pointer-events: none parent.
Firefox seems to handle pointer-events in this way:

If one of the element's children has pointer-events explicitly set to allow that child to be the target of mouse events, then any events targeting that child will pass through the parent as the event
  travels along the parent chain, and trigger event listeners on the
  parent as appropriate.
https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

While Chrome does not trigger the event on a parent with pointer-events: none. This might actually be a bug and you could/should try to report it. Good catch!
Moving the overflow-y attribute to a container could be the solution, as long as scrolling on the parent is okay, since the parent's pointer-events: none would prevent all actions on itself, while passing the mouse event to the scrollable container.

html,
body {
  overflow: hidden;
  width: 100%;
  height: 100%;
}

.container {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow-y: auto;
}

.parent {
  position: absolute;
  z-index: 10;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  pointer-events: none;
  background-color: #f00;
}

.child {
  position: absolute;
  z-index: 11;
  top: 50px;
  right: 0;
  bottom: 0;
  left: 0;
  max-height: 100%;
  pointer-events: auto;
  background-color: #00f;
}

.subChild {
  width: 100%;
  height: 500px;
  background-color: yellow;
}

    <input />

        <input />


Uncaught exception thrown after moving my website to localhost

Question: My website works right on server, I took a backup from database and public_html in order to have a copy of my webstie in localhost.
I imported the database but it reported an error, some thing was wrong with content of  cache_views table, so I emptied this table and database successfully imported. I replaced public_html with the old one and configured settings.php. but it doesn't work, it reports this error :
Additional uncaught exception thrown while handling exception.
Original
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT s.lid, t.translation, s.version FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid AND t.language = :language WHERE s.source = :source AND s.context = :context AND s.textgroup = 'default'; Array ( [:language] => fa [:source] => Makes the view results available as a context for use in Panels and other applications. [:context] => ) in locale() (line 684 of C:\xampp\htdocs\test\modules\locale\locale.module).

Additional:
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] => 0 [:db_insert_placeholder_1] => php [:db_insert_placeholder_2] => %type: !message in %function (line %line of %file). [:db_insert_placeholder_3] => a:6:{s:5:"%type";s:12:"PDOException";s:8:"!message";s:455:"SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT s.lid, t.translation, s.version FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid AND t.language = :language WHERE s.source = :source AND s.context = :context AND s.textgroup = &#039;default&#039;; Array ( [:language] =&gt; fa [:source] =&gt; Makes the view results available as a context for use in Panels and other applications. [:context] =&gt; ) ";s:9:"%function";s:8:"locale()";s:5:"%file";s:52:"C:\xampp\htdocs\test\modules\locale\locale.module";s:5:"%line";i:684;s:14:"severity_level";i:3;} [:db_insert_placeholder_4] => 3 [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => h t t p://localhost:81/test/ [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => 127.0.0.1 [:db_insert_placeholder_9] => 1389935326 ) in dblog_watchdog() (line 154 of C:\xampp\htdocs\test\modules\dblog\dblog.module).

Comment: Try restarting mysql on your local machine and double check if you have the right connection details in settings.php
Comment: @SumeetPareek I do have right connection details in settings.php, this is the same settings that was working on older version of website. I also restarted mysql and it didn't work
Answer: I solved the problem this way: set max_allowed_packet = 4M to the file php.ini
Comment: Thanks sooooooo much it worked :) . in fact it is in `my.ini` not `php.ini` . thanks again
Comment: my.cnf for me :)


What is the meaning of an 8 followed by a dotted line?

Question:
There is a 8 and a bunch of dots going over the notes. it doesn't look like octave lines, though.
Comment: That's what octave lines look like. Why do you say different?
Answer: It's an ottava-line. Or shorter: an 8va line. It means you should play those notes one octave higher than notated.
There's also an 8vb-line (ottava bassa) to play the notes an octave lower, which is drawn underneath the staff.
And then there's the same for 2 octaves too: 15ma and 15mb
Which stands for 'quindicessima' and 'quindicessima bassa' or a 15th up or down respectively.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/123229/discussion-on-answer-by-creynders-what-is-the-meaning-of-an-8-followed-by-a-dott).


Reject 1 tailed test but not reject 2 tailed test

Question: I'm going through a statistics course and don't understand this point.
Since a 2 tailed test has alpha/2, the reject rate moves further down the tails. Would there be a case where you reject a one tailed test (because p< 0.05), but will not reject a 2 tailed test because you have effectively taken the reject rate further down (p < 0.025)  when you divide alpha by 2.
Sorry I'm not getting this point but according to the course if you fail the one tailed test you would also fail the two tailed test.
Comment: Yes; this is one reason why in some application areas there's an unusual level of suspicion of one-tailed tests (even when they do make sense) ... because they can be used as a form of significance-hunting, sometimes people suspect it almost automatically.
Answer: I think it might help to think about it visually. Picture a normal distribution bell curve, then imagine shading in one of the tails (right or left) that contains 5% of the total area under the curve. In a one-tailed test, you will reject your null hypothesis if your result falls within the shaded area. Make sense?
But if you drew the shaded region to the right side of the curve, then you are never going to reject the null hypothesis if your result falls on the left side of the curve--no matter how far to the left it is.
Now, for the two-tailed version you still need to shade regions that contain 5% of the total area under the curve, but you are splitting it up on both sides of the bell--so each side only gets 2.5% of the total area. Thus, for your result to be significant under a 2-tailed test, it will have to fall a bit farther from the middle of the curve--but, unlike a 1-tailed test, your result can be significant in either direction, left or right.
So, a hypothetical result could be significant in a 1-tailed test, but not in a 2-tailed test, because it was far enough from the center to fall in the 5% region of the curve, but not far enough out to fall into the 2.5% region. But, it could also go the other way--because the 2-tailed test will allow you to reject the null hypothesis based on results that fall on both ends of the bell curve.
As for weather you should use a 1-tailed or 2-tailed, that should be informed by your hypotheses or question. If you predict that "X will change Y" then use a 2-tailed, if you predict "X will increase Y" use a 1-tail (that's way oversimplified, but the general idea).
Comment: This was exactly my point, you could reject a hypothesis on a one tailed test but fail to reject it on a two tailed test.
Really appreciate the answer, it was explained really well.


Drush command to switch to a multi-site child directory?

Question: Is there a Drush command that would cd into the directory of a particular multi-site instance, I mean to go to a directory like this one:
/srv/www/drupal/sites/alpha
where the parent Drupal resides in:
/srv/www/drupal
Thanks.
Answer: drush status produces a Site Path in its output which is what you're looking for. With some additional shell commands, you can parse this out.
MYPATH=/srv/www/drupal
MYDOMAIN=example.com

SITE_PATH=$(drush status --root=$MYPATH --uri=$MYDOMAIN | grep 'Site path' | cut -d':' -f2 | xargs)
cd "$MYPATH/$SITE_PATH"

Comment: Sure. If you don't need to dynamically find the path.
Comment: Interesting.. But the same can be achieved using a bash alias e.g. `alias alpha = cd /srv/www/drupal/sites/alpha`, isn't it?
Comment: Thank you for providing this valuable information.. I have learned new things from you code ..


Add paragraph value to referenced node

Question: I have a paragraph with two field:

Paragraph title [text field]
Node [entity reference field]

The node is displaying its title and an image. By default the Node title is a H2 heading. But I want it to change based on the existence of the Paragraph title.
When the Paragraph title is set. The Paragraph title should be a H2 and the Node title should be a H3. But when the Paragraph title field is empty the Node title should be surrounded by a H2.
How can this be done?
Comment: There are **really many** questions and answers on this site about "get child paragraph from node" or "getting parent node of paragraph".
Answer: You probably can use the hook function template_preprocess_paragraph(&$variables).
In the hook function you can test if you are on a the proper paragraph and if you are on a Node object like this :
$paragraph_type = $variables['paragraph']->getType();
$node = \Drupal::routeMatch()->getParameter('node');

And then from here you can test if your Node has the value you want (the title) and if the paragraph_type is the correct type and return the good title in $variables['my_new_title'].
In twig template of the paragraph, you can then call {{ my_new_title }}.

Add paragraph value to referenced node


Use htaccess to rewrite subdomain files to a folder

Question: I need to rewrite a files on subdomain to files stored in the folder with name of the subdomain. Only files that start with sitemap should be rewritten. So, if the requests look like this:
http://demo.domain.com/sitemap.xml
http://demo.domain.com/sitemap_more.xml
http://test.domain.com/sitemap.xml
http://test.domain.com/sitemap_alpha.xml
These should rewrite to files:
/content/sitemaps/demo/sitemap.xml
/content/sitemaps/demo/sitemap_more.xml
/content/sitemaps/test/sitemap.xml
/content/sitemaps/test/sitemap_alpha.xml
So, subdomain name is used as a folder in the rewrite-to-path. This should be rewriting NOT redirecting. Also, it would be good to have rules that will work with any domain without need to change domain name everytime.
Answer: You can match the subdomain with a condition, then rewrite it with the rule :
RewriteCond %{HTTP_HOST} ^([^.]+)\.domain\.com
RewriteRule ^(.*)$ http://domain.com/content/sitemaps/%1/$1 [L]

Maybe you want to add a filter on .xml
Add :
RewriteCond %{REQUEST_FILENAME} \.xml

Edit
For file beginning with sitemap :
RewriteCond %{REQUEST_FILENAME} sitemap.*\..+$

This will match any string that finish with sitemap. and end. => this is a filename not an inner match of directory.
Comment: This is not taking into account that files to be rewritten must start with `sitemap`. Extension can be different than XML.
Comment: No, its not working. With RewriteRule as you suggested, server generates 500 internal error that .domain.com is not found. If I leave only path without `http://domain.com` part, nothing happens, it's not working. I think for rewrite to work, it can't include domain, rewrite should point to same domain, or subdomain in this case.
Comment: I shall see that. Let me think. But you can change domain, for sure.
Comment: Maybe, but in any case is not working. Point is to have it stay on same domain to get files, no need to go cross domain or to main domain.
Comment: Have you any log in the /var/log/apache2? You can also activate mod_rewrite logs with the RewriteLog "/var/log/apache2/rewrite.log" and RewriteLogLevel 3 (or 4).


How to perform a datamigration when moving from one-to-one to one-to-many

Question: I'm using south to manage migrations and I've hit a corner. Basically I have the following setup:
App1:
class A(models.Model):
  # bunch of attributes

App2:
class B(models.Models):
  instance_a = models.OneToOneField(A, null=True, blank=True,
                                    editable=False)

Now, I want to go from this to this:
App1:
class A(models.Model):
  instance_b = models.ForeignKey(B, null=True, blank=True)

App2:
class B(models.Models):
  # other attributes

My main issue is that I can't loose data. So basically at the end of the migration(s) all objects A that mapped previously to objects B should keep that mapping. As an example, if object A with id 7 was mapped to object B with id 8, by the end of this procedure this mapping should be retained.
I tried several things from schema migrations mixed with temporary place holders and data migrations. However I end up always in the same place, which is by the time the data migration is performed I no longer have the previous relations in order to access the correct attributes. So for example, B.instance_a is no longer available.
I would like your opinion on two things:

First, is this viable at all using just south migrations.
Second, how shall I proceed.

Thanks
Answer: Finally after some time I got a procedure with django-south that might help others. The key was in south's depends_on feature (http://south.aeracode.org/wiki/Dependencies). I did it in 4 steps:
First:

Create a placeholder for the values of the foreign key in model A.

So model A becomes:
class A(models.Model):
    instance_b_placeholder = models.ForeignKey(A, null=True, blank=True)

Now just run manage.py schemamigration app1 --auto.
Second

Create a datamigration so we can copy the values. The goal is to have the data duplicated in the db and later on rename the attributes and delete the old ones. Issue manage.py datamigration app1 update_fields. I chose to keep the datamigration in app1. If you don't do this just make sure it runs after the previous migration.

Here's the datamigration coded:
# Forwards:

for b in orm['app2.B'].objects.filter(instance_b__isnull=False):
        b.instance_a.instance_b_placeholder = b
        b.instance_a.save()

# Backwards:

for r in orm['app1.A'].objects.filter(instance_b_placeholder__isnull=False):
        r.instance_b_placeholder.instance_a = r
        r.instance_b_placeholder.save()

Third:

Delete the field instance_b from model B and be sure to make the migration run after the one created in the previous step.

Model B becomes:
class B(models.Model):
     # etc...

Issue manage.py schemamigration app2 --auto and edit the migration adding the previous migration to depends_on:
depends_on = (
    ("app1", "<migration_number>_update_fields"),
)

Forth step:

Rename the place holder. This is achieved by changing the name in the code and editing the migration. Editing is necessary because south tends to delete and add a new column, but we only want it to rename the column.
This migration should run in last place, so I made it dependent on the previous one.

Here's the code:
depends_on = (
    ("app2", "<previous_migration_here>"),
)

# Forwards:

    db.rename_column('app1_a', 'instance_b_placeholder_id', 'instance_b_id')

# Backwards:

    db.rename_column('app1_a', 'instance_b_id', 'instance_b_placeholder_id')

So that's it. I don't know if there are so many other ways to do it, but at least this helped me.


Como faço para o Django enxergar as pastas do meu computador?

Question: Preciso fazer com que meu sistema enxergue pastas que estejam fora da sua pasta, para renderizar os .pdfs que estão dentro dessas pastas. Estou utilizando uma função no javascript (Vue.js) muito simples, semelhante a esta:
<code>get_doc(doc_name) {
  return '/static/pdf_docs/' + doc_name;
}
</code>
Só que, além de ser deselegante, me obriga a deixar todos os arquivos .pdf na pasta static. Tentei alguns procedimentos mais não consegui. Agradeço a ajuda desde já.
Comment: desculpe pela demora, então, eu nunca fiz isso em django mas acredito que seja muito fácil, tem um [tutorial](https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html) que mostra um exemple simples de como fazer isso.
Comment: vc configurou o [media](https://docs.djangoproject.com/pt-br/2.2/howto/static-files/)?, geralmente se usa um [servidor dedicado](https://docs.djangoproject.com/pt-br/2.2/howto/static-files/deployment/#serving-static-files-from-a-dedicated-server) para servir esses tipos de arquivos
Comment: @DaviWesley, como sou iniciante em django, não sabia que era necessário fazer essa configuração. Poderia fornecer um exemplo de como posso fazer?
Answer: Geralmente não é aconselhado a usar o Django pra servir arquivos em produção, usa-se um servidor dedicado como nginx.

A maioria dos grandes sites Django usa um servidor Web separado – isto é, um que não está servindo também o Django – para servir arquivos estáticos. Este servidor roda um tipo diferente de servidor web – mais rápido mas sem tantas funcionalidades

porém, caso queira fazer isso em Django ele oferece essa funcionalidade, no SO em inglês tem um exemplo de como fazer isso passo a passo :)


Why does AIC select the wrong logistic regression model?

Question: I've noticed a phenomenon with logistic regression: when the probability of success is small and number of trials large the AIC consistently selects the wrong models. In fact the more wrong the model the lower the AIC.
Here's some example code to show what I mean. About $96\%$ of the time the model with the random probe gets chosen. $100\%$ of the time the model with $3$ random probes gets chosen. The models with probes have AIC between $300$ and $2000$ units lower.
If I replace the $\lambda$ in the Poisson distribution with something smaller, like $1000$, this doesn't happen anymore - the model with the random probe gets selected about $9\%$ of the time, the model with 3 probes $6\%$ of the time.
This seems very odd to me. As the number of trials goes up the number of successes does too, so why does the metric break down?
nreps <- 1000
registerDoMC(16)

N <- 40000
lambda = 1e7

result <- foreach(rep = 1:nreps) %dopar% {

  # Number of trials
  n_trials <- rpois(N, lambda = lambda)

  # Probability of success is very small and depends on x
  x <- rnorm(N)

  rate <- rep(1e4, N)
  rate[x > 0] <- 2e4

  p <- rexp(N, rate)

  # Convert probability of success into number of successes in n_trials
  success <- floor(n_trials * p)
  failure <- n_trials - success

  # Set up target
  y <- data.frame(success = success, failure = failure)
  y <- as.matrix(y)

  # Random numbers
  probe0 <- rnorm(N)
  probe1 <- rnorm(N)
  probe2 <- rnorm(N)

  # Fit models
  fit  <- glm(y ~ x, family = 'binomial')
  fit0 <- glm(y ~ x + probe0, family = 'binomial')
  fit1 <- glm(y ~ x + probe0 + probe1, family = 'binomial')
  fit2 <- glm(y ~ x + probe0 + probe1 + probe2, family = 'binomial')

  res <- data.frame(fit = AIC(fit), fit0 = AIC(fit0), fit1 = AIC(fit1), fit2 = AIC(fit2))

  return(res)

}

result <- Reduce(rbind, result)

mean(result$fit > result$fit0)
mean(result$fit > result$fit2)
```

Comment: Without looking into the details, could it be that AIC selects the best forecasting model (maximimizing the expected likelihood of a new, unseen observation) instead of the true model? That would be exactly as expected.
Comment: That doesn't explain why AIC gets uniformly better the more random variables are involved or why a smaller number of trials makes the problem go away.
Answer: Your outcome variable $y$ is very overdispersed relative to a binomial, so the binomial model is misspecified. From one example of fit2, modified to quasibinomial:
> summary(glm(formula = y ~ x + probe0 + probe1 + probe2, family = "quasibinomial"))

Call:
glm(formula = y ~ x + probe0 + probe1 + probe2, family = "quasibinomial")

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-61.135  -22.809   -9.250    9.047  189.121

Coefficients:
             Estimate Std. Error   t value Pr(>|t|)
(Intercept) -9.539830   0.005434 -1755.604   <2e-16 ***
x           -0.263607   0.005261   -50.109   <2e-16 ***
probe0       0.007280   0.005243     1.389    0.165
probe1      -0.001967   0.005278    -0.373    0.709
probe2      -0.004626   0.005269    -0.878    0.380
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for quasibinomial family taken to be 823.1188)

    Null deviance: 28757637  on 39999  degrees of freedom
Residual deviance: 26686790  on 39995  degrees of freedom
AIC: NA

Number of Fisher Scoring iterations: 5

If you don't have any allowance for the overdispersion, larger models will always fit better.  Basically, you are accepting a new model if it improves the binomial deviance by 2, and a random predictor will improve the binomial deviance by an average of over 800.
You can't just use AIC with quasilikelihood, you'd need something like Takeuchi's criterion, or you'd need to fit something like a beta-binomial model.


Android ant build changing global variable

Question: I have an ant build setup for my Android project, and I've been reading guides and tutorials all over stackoverflow and online, but cannot seem to understand how to make this work. Basically in my code I have a variable, "isDebugVersion" (which will print out logs, and a few other things). When I build with ant, I want that variable in my code to be set to "false". I'm looking around and I cannot find the custom_rules.xml examples even though it's listed in the build.xml file.
So the variable is in com.example.application.Globals, and it's listed as isDebugVersion. Can someone please give me an example for how to manipulate this variable using an ant build script?
Comment: While this isn't a direct answer to your question have you looked into using the debuggable flag in the Android manifest?  [Here](http://stackoverflow.com/questions/4276857/getting-debuggable-value-of-androidmanifest-from-code) is a link to access the value in code.
Comment: I have, but part of the reason that I'm looking for this is because I'm also going to need to control variables like the "mapKey" used for the MapAPI
Answer: You can a file named custom_rules.xml to the root folder of your project.
Inside define any property you want.
Note that what you are trying to achieve could be simpler using BuildConfig.DEBUG. This file is in the gen folder of your project, close to R.java. It is generated during the build and the constant DEBUG will be set to false during debug builds and to true in release.
So if you type ant release, you will get false. With eclipse or ant debug, you will get true.
You could also learn how to use RoboGuice, it has an interesting logging solution.
You can use this constant for all purposes like changing the google map api key from debug to release key. For an example, follow this thread.
Comment: That's the debug flag in the AndroidManifest file though isn't it? I also need to be able to change variables like my mapKey for the Google Maps API
Comment: Can you update your answer with an example of how I would go about doing this?


If f is a surjective, but not injective morphism of groups G->G', can there be a cyclic group of G' whose preimage is not cyclic?

Question: If $f$ is a surjective, but not injective morphism of groups $G\to G'$, can there be a cyclic group of G' whose preimage is not cyclic?
Edit: I am almost sure the answer is yes, but I would like to see an example.
Answer: The group homomorphism $F(2) \rightarrow \Bbb Z$ sending both generators of the free group on 2 elements $F(2)$ to 1 is surjective, not injective and the preimage of $\Bbb Z$ is $F(2)$, hence not cyclic.
Answer: Yes. Consider $f : S_{42} \rightarrow \lbrace e \rbrace$, where $S_{42}$ denotes the symetric group over $42$ elements, and $\lbrace e \rbrace$ denotes the trivial group, defined by
$$f(\sigma)=e$$
The preimage of the cyclic group $\lbrace e \rbrace$ is isomorphic to $S_{42}$ which is not cyclic.


Teaching hard passages to a child

Question: First off I'm no teacher neither have I studied music. I have played the oboe for 15 years now and  play in multiple amateur orchestras.
Now I have encountered situations where I'm asked to lead a practice session of the oboes of a youth orchestra which to me is a lot of fun. I really enjoy helping out and teaching them a thing or two. Also there usually is just one or maybe two oboes in those orchestras so I can really focus on them individually.
Now when practicing hard passages with a student I'm sometimes at a loss. I try to tell them how I would approach it and play along with them so they can hear how it should sound and if they are off somehow. I try to let them play the passage very slowly, even note after note if the fingerings are hard. Then I let them play it faster until we reach the right tempo but at that point I have often already lost them.
Since I only have so much time and there are a couple of other pieces that I should go through with them I eventually move on and tell them to practice that part on their own later, but I feel as if they didn't get any further during the session.
It isn't my job to have them play it all perfectly after we're done and I know that but it feels frustrating when you see that they don't make any progress. I don't want to tell them to leave out a harder passage even though I can see that they probably won't be able to play it right by the time of the concert because only by practicing they will get better.
So in the end I'm looking for different approaches for children to learn hard pieces since my methods won't necessarily work. I thought of introducing some kind of reward system if they play it right a couple of times. Or should I maybe not even focus too hard on certain passages but rather try to help them developp a better sound?
Comment: I often tell students and parents that progress doesn't happen during lessons, it happens in between lessons. That said, I'm interested to see if anyone has ideas for making lessons more effective.
Comment: @ToddWilcox - I subscribe to progress doesn't happen in lessons! I think at that time, we're just opening doors for the students, or at least showing them which key fits best...
Comment: What @ToddWilcox said. If anybody *could* teach a hard passage to a student in a few minutes, they would be able to teach a complete beginner to be a virtuoso performer in a few weeks. You can learn *how* to do something at an intellectual level quickly, but it takes many repetitions to learn to *carry out* any physical activity.
Answer: After 15 years playing the instrument, it's a reasonable assumption that you have moved beyond "learning to play hard passages" and have now "learned to play your instrument" - i.e. your general purpose oboe technique is good enough to play anything reasonably successfully, without any special practising.
Relative beginners don't have that ability yet, and it's a fact of life that some of them will never acquire it even though they appear to be making progress, especially if they are taught mainly to "play specific pieces" to pass examinations.
A student can quickly learn how to play a passage at the intellectual level, but developing the physical skill and control required to actually do it is a different matter - and those skills are what you have, but your student's don't.
Answer: The guy that commented that progress takes place between lessons is absolutely right.  I would suggest introducing them to slow practice techniques.  If you learn to play a piece correctly at a slower tempo, it is easier to speed it up and play it at the correct speed.
http://www.essential-music-practice.com/slow-practice.html

Teaching hard passages to a child


Reparameterization of Poisson Distribution

Question: In deep learning, especially generative models, sometimes we need to add some random noise to the input of model. To make the sampling of random noise learnable (or differentiable), we need to reparameterize the sampling, just like diffusion models do.
For example, given x ~ N (μ, σ2), if we sampled x directly, the mean and variance would not be differentiable. In practice we need to reparameterize it with x = μ + σ*ε, where ε ~ N (0, 1). So we sample ε instead of x, making μ and σ differentiable and learnable.
But if given x ~ Poisson (λ), how to reparameterize it to make λ learnable?
Answer: You can re-parameterize $x$ by using the quantile function of the Poisson distribution.
$$x = Q(\epsilon;\lambda) \qquad \text{where $\epsilon \sim U(0,1)$}$$
If you also want the function to be differentiable then you might want to consider a gamma distribution (with a continuous support) instead of a Poisson distribution (with a discrete support).
Compare below the Poisson distribution and the gamma distribution (with fixed scale=1) for equal values of the mean. The variance as function of the mean is in both cases $\text{Var}(X) = \text{Mean}(X)$.
Comment: @Lorin60 the Poisson has $\text{Var}(X) = \text{Mean}(X)$ whereas the Gamma has $\text{Var}(X) \propto \text{Mean}(X)^2$ if the shape parameter is fixed. But if you keep the scale of the gamma distribution fixed and equal to one, then the Gamma distribution has the same behaviour $\text{Var}(X) = \text{Mean}(X)$. (In a glm framework they would be the same)
Comment: I may not use Gamma distribution because its probability density function differs from Poisson. If there are no precise methods, perhaps approximating the Poisson distribution by a Gaussian is better when lambda is big.
Comment: An alternative is to use the conjugate prior for the shape parameter, which has the same form as the Poisson distribution, except that the discrete factorial is replaced by a gamma function. But that distribution may not be so easy to work with.
Comment: Thanks. I see. Gamma is a good approximation of Poisson when the scale of Gamma equals to 1.
Comment: @Lorin60 and with different scales you can consider it as an over/under-dispersed Poisson distribution.
Comment: btw. I wonder why you would actually need a Poisson distribution as choice for the additional random noise.
Comment: I'm simulating the process of a detector receiving photons, which is a Poisson process. So it would generate noticeable Poisson noise in resulting images when the number of photons is relatively small.
Comment: @Lorin60 and you are coupling this to some deep learning model? In that case you may not have to make the model output directly the number of photons and instead you might have as model output the expected rate $\lambda$. Like in a classification model where we may have the model output probabilities instead of a single class.
Comment: That's it! I'm trying to do that. You have a deep understanding of it.  :-)
Comment: @Lorin60 here is a link to a post that I had in my mind when speaking about classification and using the probabities instead of the final classification https://stats.stackexchange.com/a/312787/164061
Comment: It's quite right. I'm a biomedical engineer practitioner, so I can relate to the question and answers.


Installing android app from PC to device via USB without USB debugging

Question: I want to install the app directly from android studio of my PC to any android device without generating apk file and without enabling USB debugging of my device. Is it possible ?
Comment: Use this to install app on your device using browser without cable https://play.google.com/store/apps/details?id=com.sand.airdroid
Answer: 1) Using Android Studio
You'll have to build your app from the menu: Build > Generate Signed APK
Then from the directory that your .apk was built you can transfer the .apk to your phone and install it (when prompted check "Unknown Sources").
2) (Advanced) Using Skipsoft Toolkit, if your device supports it.
Comment: I'm also not allowed to generate the apk file.
I have also edited my question, pls hv a look at it also and help.
Thanks in advance


Groovy XmlSlurper vs XmlParser

Question: I searched for a while on this topic and found some results too, which I am mentioning at the end of post. Can someone help me precisely answer these three questions for the cases listed below them?

For which use-cases using XmlSluper makes more sense than XmlParser and vice-versa (from point of view ease of use of API/Syntax)?
Which one is more memory efficient? (looks like Slurper)
which one processes the xml faster?

Case a. when I have to read almost all nodes in the xml?
Case b. when I have to read just few nodes (like using gpath expression)?
Case c. when I have to update/transform the xml?
provided the xml document is not trivial one (with level of depths and size of the xml).
Resources :
http://www.tutkiun.com/2009/10/xmlparser-and-xmlslurper.html states :

Difference between XMLParser and XMLSlurper:
There are similarities between XMLParser and XMLSlurper when used for
  simple reading but when we use them for advanced reading and when
  processing XML documents in other formats there are differences
  between two.
XMLParser stores intermediate results after parsing documents. But on
  the other hand,
XMLSlurper does not stores internal results after processing XML
  documents.
The real, fundamental differences become apparent when processing the
  parsed information. That is when processing with direct in-place data
  manipulation and processing in a streaming scenario.

http://groovy.dzone.com/news/john-wilson-groovy-and-xml
The groovy doc (XmlParser, XmlSlurper) and the groovy's site explains them well (here and here)but does not do a great job in explaining the aforementioned question.
Answer: The big difference between XmlSlurper and XmlParser is that the Parser will create something similar to a DOM, while Slurper tries to create structures only if really needed and thus uses paths, that are lazily evaluated. For the user both can look extremely equal. The difference is more that the parser structure is evaluated only once, the slurper paths may be evaluated on demand. On demand can be read as "more memory efficient but slower" here. Ultimately it depends how many paths/requests you do. If you for example want only to know the value of an attribute in a certain part of the XML and then be done with it, XmlParser would still process all and execute your query on the quasi DOM. In that a lot of objects will be created, memory and CPU spend. XmlSlurper will not create the objects, thus save memory and CPU. If you need all parts of the document anyway, the slurper loses the advantage, since it will create at least as many objects as the parser would.
Both can do transforms on the document, but the slurper assumes it being a constant and thus you would have to first write the changes out and create a new slurper to read the new xml in. The parser supports seeing the changes right away.
So the answer to question (1), the use case, would be, that you use the parser if you have to process the whole XML, the slurper if only parts of it. API and syntax don't really play much a role in that. The Groovy people try to make those two very similar in user experience. Also you would prefer the parser over the slurper if you want to make incremental changes to the XML.
That intro above also explains then what is more memory efficient, question (2). The slurper is, unless you read in all anyway, then the parser may, but I don't have actual numbers about how big the difference is then.
Also question (3) can be answered by the intro. If you have multiple lazy evaluated paths, you have to eval again, then this can be slower than if you just navigate an existing graph like in the parser. So the parser can be faster, depending on your usage.
So I would say (3a) reading almost all nodes itself makes not much of a difference, since then the requests are the more determining factor. But in case (3b) I would say that the slurper is faster if you just have to read a few nodes, since it will not have to create a complete structure in memory, which in itself already costs time and memory.
As for (3c)...these days both can update/transform the XML. Which is faster is actually more linked to how many parts of the xml you have to change. If many parts I would say the parser, if not, then maybe the slurper. But if you want to for example change an attribute value from "Fred" to "John" with the slurper, just to later query for this "John" using the same slurper, it won't work.
Comment: Awesome explanation of updating in regards to slurper, thanks. This solved my problem when trying to delete nodes recursively when "empty" in a slurper, which of course will not work.
Answer: I will give you crisp answers:

XML Parser is faster than XML Slurper.
XML Slurper consumes less memory than XML Parser.
XML Parser can parse and update the XML simultaneously.
For XML Slurper you need to MarkupBuild the XMLs after each update you make.
When you want to use path expressions XML Slurper would be better than parser.
For reading almost all nodes XML Parser would be fine.

Hope it helps

Groovy XmlSlurper vs XmlParser


Concatenate string to dictionary path when using print in Python

Question: I want to create a variable such as 'path' and use it to get the same result when getting data from the dictionary. Is this concatenation possible by doing some type of conversions?
print(dict['detect'][1]['ssh'][0]['Server']) #Result

path = "['ssh'][0]['Server']"
print(dict['detect'][1]{path}) #...should give same result

Answer: To answer your immediate question, you can use eval() to treat the string data as code:
print(eval(f"dict['detect'][1]{path}")

That being said, be very careful when using eval(), as it introduces major security risks. I don't see a way to use ast.literal_eval() here, so if at all possible I would suggest avoiding this appoach entirely.


How to query for records that have a certain count within a timespan

Question: I have a table in which I store a log of every request to a web site. Every time a page is requested, a record is inserted. I now want to analyze the data in the log to detect possible automated (non-human) requests. The criteria I need to use is x number of requests within y seconds by an individual user.
So, the data looks like this:
| Page          | UserId | Date                           |
| /Page1.htm | 001      | 2014-06-02 11:03 AM |
| /Page2.htm | 001      | 2014-06-02 11:03 AM || /Page1.htm | 002      | 2014-06-02 11:04 AM || /Page3.htm | 001      | 2014-06-02 11:04 AM || /Page2.htm | 002      | 2014-06-02 11:05 AM || /Page4.htm | 001      | 2014-06-02 11:05 AM || /Page5.htm | 001      | 2014-06-02 11:07 AM || /Page3.htm | 002      | 2014-06-02 11:15 AM |
So, I wanted to get all UserIDs that made 5 or more requests within any 5 second timespan. How can I get that? Is this even possible with SQL alone?
I don't have access to the web server logs or anything else other than the SQL Server database.
Comment: What is the version of your SQL Server?
Answer: Here is the query which you are looking for:
SELECT
    T1.Page,
    T1.UserId,
    T1.Date,
    MIN(T2.Date) AS Date2,
    DATEDIFF(minute, T1.Date, MIN(T2.Date)) AS DaysDiff,
    COUNT(*) RequestCount
FROM
    [STO24541450] T1 LEFT JOIN [STO24541450] T2
    ON T1.UserId = T2.UserId AND T2.Date > T1.Date
GROUP BY
    T1.Page, T1.UserId, T1.Date
HAVING
    DATEDIFF(minute, T1.Date, MIN(T2.Date)) >= 5 AND COUNT(*) >= 5;

Comment: You have a typo: should be `DATEDIFF(minute, T1.Date, MIN(T2.Date)) <= 5` (**less** or equal)
Answer: I would probably group by the time range and UserId and grab any with a count greater than 5.
select count(*),
       UserId,
       dateadd(SECOND, DATEDIFF(SECOND, '01-jan-1970', [date])/5*5, '01-jan-1970')
from   [LogTable]
group by UserId, DATEDIFF(SECOND, '01-jan-1970', [date])/5
having count(1) > 5

The above will return the same UserId for each period in which the user has made more than 5 requests. If you're only interested in the userId's and not when or how many times they breached the conditions you could simplify the above to
select distinct(UserId)
from   [LogTable]
group by UserId, DATEDIFF(SECOND, '01-jan-1970', [date])/5
having count(1) > 5

Comment: *within any 5 second timespan*
Comment: @PM 77 - good point, I missed the word _any_. My solution will work in 5 second timespans from 0 seconds to 55 seconds each minute but it won't capture cases where for example 2 hits are at 03 seconds and another 3 hits are at 06 seconds as they'd fall into different groups.
Answer: This is untested but should hopefully give you an idea on how to proceed.
SELECT UserId, COUNT(UserId) as AccessCount
     (SELECT UserId FROM AccessLogTable WHERE Date BETWEEN startDate AND endDate) a
GROUP BY UserId HAVING COUNT(UserId) > x

What we're doing here is using a subquery to first select the subset of records (your y criteria) that are of interest. This will then be encapsulated in an external query where you would do a group by UserId having count(userid) > x.
Comment: `startDate` and `endDate` are not known


How parse json array of object inside autcomplete c# mvc

Question: I have an auto complete method.
$("#txtSearch").autocomplete({

                  source: function (request, response) {
                      $.ajax({
                          url: "/Home/Getsrchresult",
                          type: "POST",
                          dataType: "json",
                          data: { term: request.term, location: $('#location').val() },
                          success: function (data) {
                              response($.map(data, function (item) {
                                  return {

                                   label: item.srchresult, value: item.srchresult
                                    };
                              }))

                          }
                      })
                  }
              });

my controller passes multidimension array.How to place all data inside autocmplete textbox
controller
                var fd2 = (from r in db.Restaurants
                       where r.restname.ToLower().Contains(term.ToLower())
                       orderby r.state == location descending
                       select new { searchresult = r.restname ,place=r.place

                       }).Take(10);
  return Json(fd2, JsonRequestBehavior.AllowGet);

Response is like this
[{"srchresult":"foodtakeaway","place":"karnataka"},{"srchresult":"ssdf","place":"dfsaf"}]

Comment: It is an array of objects, not multidimension array.
Answer: This should work
$("#txtSearch").autocomplete({
     source: function (request, response) {
               $.ajax({
                    url: "/Home/Getsrchresult",
                    type: "POST",
                    dataType: "json",
                    data: { term: request.term,location:$('#location').val() },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.place, value: item.place };
                        }))
                    }
                })
            }
});

Assuming you are returning JSON like this
[
    {
        "srchresult": "foodtakeaway",
        "place": "karnataka"
    },
    {
        "srchresult": "ssdf",
        "place": "dfsaf"
    }
]

I have used item.place for label and value property, you may replace it with item.srchresult as needed.
Suggestion : Use MVC Helper methods(Url.Action) to generate the url to your action methods, instead of hardcoding
Comment: i have 2 items place and srchresult
Comment: This will work as long as you return n number of items with the JSON structure you mentioned.
Comment: can i retrieve both srchresult and place in  txtsearch.simultaneously
Comment: but i am getting location from javascript.so i cant send javascript variabled in url.Action
Comment: this is not the answer i required.pls understand my situation
Comment: @user3300195 You want to show a string with srchresult and place name ? Yes, just do a string concatenation inside the `$.map` part.