React Drag & Drop Event propagation problem

Question: I have a simple Drag & Drop setup. What's special is that there can be dropzones inside dropzones. My problem is, that whenever I drop something in my child component, the parent event gets fired as well but only under certain circumstances.
For example (this works, no event propagation):
export default class Folder extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dragActive: false
        };
    }

    onDragOver = (e) => {
        e.preventDefault();
        this.setState({ dragActive: true });
    }

    onDragLeave = () => {
        this.setState({ dragActive: false });
    }

    onDrop = (e) => {
        e.stopPropagation();
        alert("test");
    }

    render() {
        return (

        );
    }
}

The important part is this line here:
onDrop={this.onDrop}

If my drop event is inside the same component everything works as expected.
As soon as I change the line to this:
onDrop={() => this.props.onDropFunction(event, this.props.folder.id)}

The event propagation stops working. This is the onDrop function I am calling inside the parent:
onDrop = (e, folderId) => {
    e.stopPropagation();
    e.preventDefault();
    var files = this.fileListToArray(e.dataTransfer.files);
    this.setState({
        dragActive: false,
        uploadFiles: files
    }, () => {
        this.uploadFiles(folderId);
    });
}

Answer: Found the answer in this SO-Post (just didn't scroll down enough).
So apparently the solution is to basically use the first approach and replace the alert("test") part with this.props.onDropFunction(event, this.props.folder.id);
Answer: onDrop={(event) => this.props.onDropFunction(event, this.props.folder.id)}

pass event like this and try


How can I programmatically add data to an address field?

Question: I'm trying to import user data from a json file. So far I managed to import most of the information, but now I'm stuck on the address field (created with Address module for Drupal 8).
In the json file (exported from a Drupal 7 website), there is city, country code and country name.
How can I import this data into the new field (the machine name is field_address)?
So far I tried using Drupal::entityTypeManager.
$values = array(
            'name' => $user["name"],
            'pass' => '',
            'status' => $user["status"],
            'mail' => $user["e_mail"],
            'field_first_name' => $user["first_name"],
            'field_last_name' => $user["last_name"],
            'field_address' => $city,
        );

        $userStorage = \Drupal::entityTypeManager()->getStorage('user');
        $userEntity = $userStorage->create($values);

It doesn't work: The address field stays empty.
Should I use the sub fields?
Answer: If you have a field with multiple properties then use an extra array:
$values = [
  'name' => $user["name"],
  'pass' => '',
  'status' => $user["status"],
  'mail' => $user["e_mail"],

  'field_address' => [
    'first_name' => $user["first_name"],
    'last_name' => $user["last_name"],
    'city' => $city,
  ],
];

Answer: Thanks to 4k4 answer I was able to import the data. Here is the code:
$adressCountryCode = "NL";
$addressCity = "Amsterdam";

$values = [
  'name' => $user["name"],
  'pass' => '',
  'status' => $user["status"],
  'mail' => $user["e_mail"],
  'field_address' => [
     'country_code' => $adressCountryCode,
     'locality' => $addressCity,
  ],
];


Executar um vídeo em html5 em tela cheia

Question: Estou utilizando esta solução para carregar um html que possui um js que carrega uma url de um video criptografada.
Tudo anda muito bem porém, necessito que ao dar o primeiro play no vídeo (clicar no webview) o vídeo seja executado em fullscreen imediatamente. É possível?
Answer: Tente isso:
<video controls id="myvideo">
  <source src="somevideo.webm"></source>
  <source src="somevideo.mp4"></source>
</video>

Em javascript:
var elem = document.getElementById("myvideo");
if (elem.requestFullscreen) {
  elem.requestFullscreen();
} else if (elem.mozRequestFullScreen) {
  elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
  elem.webkitRequestFullscreen();
}

Comment: tentei já esta solução conforme pesquisa nos fóruns e não funciona. Me retorna um aviso onde somente poderá ficar em fullscreen se tiver ações do usuário e não pelo programa/ comandos.
O estranho que no iOS ao darum play em um vídeo o  webview permite estar em tela cheia logo de ínicio e no android não. Uma tentativa que gostaria de realizar e não sei como era chamar o onShowCustomView ao dar o play no vídeo já que ele controla o frame de fullscreen.


How to detect a self referencing list in python

Question: I have been trying to find a self-referencing loop in a list. I have referenced the list like this:
a = [1, 2, None]
a[2] = a

What is the right way to detect this loop in python?
Answer: I'm not sure if there's a "right" way, but the is operator is your friend. To check if the list contains itself:
any(x is a for x in a)

To find the index of the list:
next(i for i, x in enumerate(a) if x is a)

This version is like a.index in that it raises an error if the list is not found in itself. To simulate a.find instead, add a default value to next:
next(..., -1)

You can't use a.find or a.index directly because those will search by equality, which will be infinitely recursive on a positive match in this case.
Checking for identity should be relatively foolproof in this case.


Implementing Multinomial Logistic Classification

Question: I have a dataset that has probability labels instead of one-hot-encoded labels AND I'd like to keep it that way. The probabilities of each sample is information that I'd like to influence the loss function during backprop.
E.g. of dataset

Sample (Movie)
Horror
Comedy
Drama
SciFy/Fantasy

Aliens
0.3
0.2
0.0
0.5

Dumb & Dumber
0.0
0.8
0.2
0.0

The Hobbit
0.1
0.2
0.2
0.5

Above you can see each movie is labeled corresponding to a category with a probability in each category. One-hot-encoding would hard classify Aliens as 100% SciFy/Fantasy, but there's value in knowing that this also belongs to horror and comedy too and in those exact proportions.
My usecase is a little more complicated than this as well. I'm not able to simply slap on scikit-learn's logistic regression model and call it a day. I'll need to use a timeseries neural network. I'm able to get decent results with my current model that converts everything to a one-hot-encoded classification, but I believe that it would perform significantly better if y_target utilized more loose class labels reflecting the probabilities in each of those labels.
I'm assuming that using those y_target probabilities will work just like any one-hot classification problem and that the loss function will reflect these softer labels, but I am unsure...
What I'm thinking is:
<code>linear model output --> y_pred --> softmax << cross-entropy >> y_target
</code>
Essentially, use a linear output from the model. Then squash it down using softmax. Then calculate the loss with cross-entropy against y_target. y_pred and y_target will both have probability distributions and both will not be one-hot encoded.
Can this be done? and is it doing what I think it's doing? Has anyone seen any good examples of something similar?
Comment: Interesting question and a +1 from me, but I am concerned that you might be mixing up two ideas. It seems like your data are saying that *Aliens* is $30\%$ horror, $20\%$ comedy, and $50\%$ sci-fi/fantasy. What does that have to do with weights in backprop for a softmax neural network regression? // In a standard multinomial logistic regression, the output contains the probabilities of each class. This can be used to make a hard classification, but it does not have to be (and there are advantages to using the probability values instead of hard classifications).
Comment: This is obviously not something I've seen anywhere... I've dreamed up this approach. The reason why I think it'll impact cross-entropy loss is due to its formula.

H(P, Q) = – sum x in X P(x) * log(Q(x))

The probability distribution P(x) is multiplied by Q(x) for each class/label. So, in a typical 1-hot function, only one of these labels is ultimately calculated. My proposed approach would actually use the sum of the difference between prob distributions...
Comment: Focal Loss looks very promising. It's essentially cross-entropy with a weighting criteria. https://arxiv.org/pdf/1708.02002.pdf Perhaps I can use hard 1-hot encoded y_targets, but use those percentages/probabilities as the weighting...
Answer: Answering my own question. Yes, you can use cross entropy loss for comparing two vectors of continuous values. It's stated in the wiki with supporting proofs:

The situation for continuous distributions is analogous.


How to set Form API link href to # hashtag

Question: In Form API when creating a link, the output a-anchor will have a prefix of "en/" in front of whatever I set as the href value and if href is set to "#" it will be output with the language prefix and # is escaped and becomes a code something like "en/%23"
this is the code:
<code>$element['add_address'] = array(
            '#type' => 'link',
            '#title' => t('Add new address'),
            '#href' => '#',
        );
</code>
I need that link to not have a href destination value, as it's supposed to react to javascript only. I know I could do a preventDefault() or any of the same resulting bypasses with JS, but I'm curious how to make a empty anchor with the form API.
Thanks,
Alari
Comment: Does this answer your question? [How to create an EMPTY anchor-only link with l()?](https://drupal.stackexchange.com/questions/51596/how-to-create-an-empty-anchor-only-link-with-l)
Comment: No, but Clive's comment under one of the answers did in May 2017, unfortunately it was never posted as an answer.
Comment: Could you then maybe post it as an answer and accept it to help future readers to find the right solution for sure?
Answer: Not sure if this will work, give this a try
<code>'#href' => '&num',  OR  '#href' =>'&#x00023', OR '#href' => '&#35',
</code>
Comment: I think this is the canonical post @AlariTruuts: http://drupal.stackexchange.com/questions/51596/how-to-create-an-empty-anchor-only-link-with-l
Comment: Errrrr...try `'#href' => '', '#options' => array('fragment' => ' ', 'external' => TRUE)` in the render array
Comment: @Clive: You're a very smart person :)! the solution works, mind if you mark it as an answer, so I can accept? it puts the href out as "# " with the following space, curious as to why that is, but works perfectly! Thanks!
Comment: 'twill not, the `#` representing numbers and `&` will also be escaped. Drupal doesn't have a method for adding an empty fragment believe it or not. There are a couple of hacks, I'll see if I can dig one up
Comment: @Clive I had a similar problem with Twig [Twig: How to print special symbols, such as Copyright, Trademark, etc](http://stackoverflow.com/questions/36880446/twig-how-to-print-special-symbols-such-as-copyright-trademark-etc#comment-61326988#answer-36880514) thought the character code solution there may work here. I guess after thinking it over, you're right.
Comment: Yes, unfortunetely these don't work either and if they did, they wouldn't escape the prefix, which I don't seem to be able to control at all. @Clive: Would be very interested in seeing a solution :) So far google hasn't been of much help to my queries..
Comment: @Clive: Thanks, I actually found that one on my search as well, but don't see how I could use it in the scenario described. I tried setting the #href to "javascript:void(0)" but that came out as: "/en/javascript%3Avoid%280%29" any ideas how to escape the prefix?
Answer: I would try this to create a link:
<code>
  l(t('My Anchor Link'), '', array(
     'fragment' => ' ',        // use a space here
     'external' => TRUE,      // this will solve your problem
     'attributes' => array(
        'title' => 'Title description'
   )
</code>
Comment: It would be helpful to use the same render array, which should be possible by including that array as the #options element.
Answer: As per Clive (https://drupal.stackexchange.com/users/2800/clive) answer in the comments:
<code>'#href' => '', '#options' => array('fragment' => ' ', 'external' => TRUE)
</code>
in the render array solves the issue and removes the pre-processing with the language prefixes.


Select rows with minimum difference

Question: I'm pretty strong with SQL, but I can't think of good solution to this "look-alike" data analysis problem:
Given a table with a set of integers, I need to match each integer with the integer in a second table that is most similar (smallest absolute difference). Normally I'd do a Cartesian join and order by the difference in numbers, but I need to only get one pairing for each row from each table so no value from either table can be used twice.
Any idea how to accomplish this?
EDIT: Example:
TABLE_A
34
57
108
219
380
5000

TABLE_B
4000
200
400
99
40
33
34
4600

The pairing would be one row from table_a and the closest row from table_b:
RESULT
34,34
57,40
108,99
219,200
380,400
5000,4600

So no row from either table appears twice.
EDIT: more clarification: I'm trying to solve this problem where given 1 row from table_a, we find the 1 row from table_b that's closest. That becomes a pair and is removed. Then take the next row from table_a and repeat. So we're trying to find the best match for each row and optimize that pairing, not trying to optimize total differences.
Comment: "...one pariting for each row from each table..." is confusing. Is it "take every value in the first table and find the closest for it in the second table"? Or is there some requirements that every value in the second table must appear in the list, or otherwise must appear in the final set? Perhaps a small example would help
Comment: Can you add sample data please to help us visualise the inputs and outputs? Can we assume integers are unique in each table? What about 5 and 7 in one table, 6 in the other? 6 should appear twice because it is equally close to 5 and 7
Comment: If you're looking for the solution with a smallest total difference between sets, then if you have 5 and 8 in one table and 7 and 15 in the second table, then your sets would actually be (5,7), (8,15). This is true even though the smallest difference is between 7 and 8. Because ((7-5) + (15-8)) == 9 but ((8-7)+(15-5) == 11. So the solution that finds the closest number for that row isn't necessarily the optimal solution for the data set. We really need to know how you want to prioritize the solution and resolve conflicts/duplicates as gbn mentioned.
Answer: Assuming

where given 1 row from table_a, we find the 1 row from table_b that's closest

select
   *
from
   TABLE_A a
   cross apply
   (select top 1 Number from TABLE_B b order by abs(b.Number - a.Number)) b2

This also assume rows in b can be repeated: try it and see if it does what you want. However, this should fit your sample data so it would answer your question...
Answer: select v.*
from

   (select a.value as avalue, b.value as bvalue,
   (abs(a.value - b.value)) as difference
   from
   TABLE_A a,
   TABLE_B b) v,

   (select a.value as avalue, b.value as bvalue,
   min((abs(a.value - b.value))) as difference
   from
   TABLE_A a,
   TABLE_B b
   group by a.value, b.value) m

where m.avalue = v.avalue and m.bvalue = v.value and m.difference = v.difference

Answer: You will probably need to use a cursor to handle this. Copy the data from each table to their own temp table and apply your logic one row at a time.
What makes this difficult, if not impossible without a cursor, is the fact that the order in which you handle each number from the first table will affect the end result.
If your first table looks like this
9
10

And your second table looks like this
5
6

Then your result will look like this if you process the 9 first
9,6
10,5

And the result would look like this if you processed the 10 first
10,6
9,5

Select rows with minimum difference


How to fill the svg path based on percentage?

Question:
I am using Linear gradient to indicate the percentage of the task completed. As u can see above its not calculated correctly. Currently I am just adding another path over an existing one.
Is there any way I can display the correct percentage? or Is there any other method to display the percentage.?
-

Here is the link to my code.
Comment: Instead of using `linearGradient` for this task I would use strokes: `stroke-dasharray`and  `stroke-dashoffset` for example like this: [Create a circle progressbar in svg or css](https://stackoverflow.com/questions/53892517/create-a-circle-progressbar-in-svg-or-css/53893211#53893211)
Comment: https://stackoverflow.com/a/9031405/5385381
Comment: Please show me what you have. I would like to help.
Comment: Thanks. Please use this link for the code. https://codepen.io/sashnk/pen/ebPPwB
Comment: Please put a [mcve] in the question. Links can break. You seem to have had some of that in there in the past but you've removed it.
Comment: You can delete this question.
Answer: You should be able to recycle your computeTextRotation function to add gradientTransform='rotate()' with the computed angle.
grad.attr('gradientTransform' , function(d) {
  var angle = computeTextRotation(d);
  return `rotate(${angle + 90})`
})

Codepen
Comment: Thanks.. I got the angles right but not able to show/calculate the percentage.
https://codepen.io/sashnk/pen/WLLJRo
Comment: I'm not sure what you mean?
Comment: I need to fill the Path with exact percentage. Pls see the link i jus mentioned.
Comment: Yes I have seen the link but it's not clear what you are asking.
Comment: Hmm..for instance in my example arc "Sub A2" should be filled exactly 30%. But its filled above 60%. So how can I calculate the value of endAngle based on percentage?
Comment: What do you mean by `filled exactly 30%`?
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/186648/discussion-between-ksav-and-devsa).


Impedir Insert ou Update Caso data esteja em um intervalo Cadastrado

Question: estou com a seguinte dúvida:
Tenho a tabela:
 Escala
 Data_Atuacao_Inicial, Data_Atuacao_Final, tipo

O tipo poder ser 1 ou 2
Quero criar uma trigger para impedir o insert ou update dessa tabela, se eu inserir uma escala ou editar uma existente e colocar uma data que esteja entre os limites de outra existente no banco impeça e retorne uma mensagem.
Exemplo:
Escala
Data_Atuacao_Inicial = 09-10-2019
Data_Atuacao_Final   = 10-10-2019
tipo                 = 1

Quando eu tentar inserir ou editar um outra escala e colocar as datas entre 09-10-2019 e 10-10-2019 e ser do tipo 1 deve impedir(instead off) e dar uma menssagen (Já existe escala do tipo 1 atuando nessa data)
Podem me ajudar?
Comment: acho que a pergunta não tem relação com a tag c#
Answer: Na sua trigger faça esta verificação:
IF EXISTS(SELECT * FROM inserted WHERE inserted.DATA1 < DATA2)
   rollback tran

Ai para o seu problema, trate da maneira que for necessário a seguinte parte DATA1 < DATA2
Answer: Tenta algo como
create trigger bloqueia_registro
on TABELA
for insert
as
declare
@codigo int,
@data date,
@tipo int
select @codigo = codigo, @data = data, @tipo = tipo from inserted
IF (@data between '09-10-2019' and ' 09-10-2019' and @tipo = 1 )
BEGIN
delete from TABELA where codigo = @codigo and tipo = @tipo and data between '09-10-2019' and ' 09-10-2019'
raiserror('Já existe escala do tipo 1 atuando nessa data !',16,1)
END
Para fazer a mesma coisa só que com UPDATE é só mudar de insert para Update na declaração do tipo da Trigger " for update "


H2: can't initialize DB schema from an sql file inside a jar

Question: I am trying to use the H2 database (v1.3.170) for JUnit testing in my project and experiencing a weird behavior.
I have one jar containing all sqls for DB schema initialization:
db_data.jar
  |--schema
        |--aliases.sql
        |--tables.sql
        |-- ...

I have this jar in my classpath. But when I am executing the below code - it throws an exception [see below]:
CallableStatement initCall = conn.prepareCall("RUNSCRIPT FROM 'classpath:schema/aliases.sql'");
initCall.execute();

The exception thown:
Caused by: org.h2.jdbc.JdbcSQLException: IO Exception: "java.io.FileNotFoundException: resource /schema/aliases.sql"; "classpath:schema/aliases.sql"; SQL statement:
RUNSCRIPT FROM 'classpath:schema/aliases.sql' [90031-170]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:329)
    at org.h2.message.DbException.get(DbException.java:158)
    at org.h2.message.DbException.convertIOException(DbException.java:315)
    at org.h2.command.dml.ScriptBase.openInput(ScriptBase.java:162)
    at org.h2.command.dml.RunScriptCommand.update(RunScriptCommand.java:43)
    at org.h2.command.CommandContainer.update(CommandContainer.java:75)
    at org.h2.command.Command.executeUpdate(Command.java:230)
    at org.h2.server.TcpServerThread.process(TcpServerThread.java:333)
    at org.h2.server.TcpServerThread.run(TcpServerThread.java:149)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.io.FileNotFoundException: resource /schema/aliases.sql
    at org.h2.store.fs.FilePathDisk.newInputStream(FilePathDisk.java:285)
    at org.h2.store.fs.FileUtils.newInputStream(FileUtils.java:209)
    at org.h2.command.dml.ScriptBase.openInput(ScriptBase.java:160)
    ... 6 more

I saw that in org.h2.store.fs.FilePathDisk#newInputStream() you are explicitly adding the / to the path of the SQL file:
public InputStream newInputStream() throws IOException {
    //...
    if (!fileName.startsWith("/")) {
        fileName = "/" + fileName;
    }
    //...
    return in;
}

Can you please explain the purpose of the above? And how to deal with the exception?
Thanks in advance!
Comment: Try `'classpath:/schema/aliases.sql'` (slash in front). If it doesn't work, what is your database URL? (The jar file needs to be on the server side when using the server mode.)
Comment: you are right Thomas. The issue was that the aliases.sql was in the client classpath and was not in the TCP server classpath.
Thanks!
Comment: Thanks! I have added the solution as an answer now.
Answer: The resource (jar file) needs to be on the server side when using the server mode.
Answer: Try changing the file reference to:
classpath*:schema/aliases.sql

Comment: That doesn't work:
Caused by: org.h2.jdbc.JdbcSQLException: IO Exception: "java.net.MalformedURLException: no protocol: classpath*:schema/aliases.sql"; "classpath*:schema/aliases.sql"; SQL statement:
RUNSCRIPT FROM 'classpath*:schema/aliases.sql' [90031-170]


Are sampling distributions legitimate for inference?

Question: Some Bayesians attack frequentist inference stating that "there is no unique sampling distribution" because it depends on the intentions of the researcher (Kruschke, Aguinis, & Joo, 2012, p. 733).
For instance, say a researcher starts data collection, but his funding was unexpectedly cut after 40 participants. How would the sampling distributions (and subsequent CIs and p-values) even be defined here? Would we just assume each constituent sample has N = 40? Or would it consist of samples with different N, with each size determined by other random times his funding may have been cut?
The t, F, chi-square (etc.), null distributions found in textbooks all assume that the N is fixed and constant for all the constituent samples, but this may not be true in practice. With every different stopping procedure (e.g., after a certain time interval or until my assistant gets tired) there seems to be a different sampling distribution, and using these 'tried and true' fixed-N distributions is inappropriate.
How damaging is this criticism to the legitimacy of frequentist CIs and p-values? Are there theoretical rebuttals? It seems that by attacking the concept of the sampling distribution, the entire edifice of frequentist inference is tenuous.
Any scholarly references are greatly appreciated.
Comment: The citation is for:

Kruschke, J. K., Aguinis, H., & Joo, H. (2012). The time has come: Bayesian methods for data analysis in the organizational sciences.

But Kruschke has used it before in: (2010) Bayesian data analysis and (2010) What to believe: Bayesian methods for data analysis.
Answer: Typically you'd carry out inference conditional on the actual sample size $n$, because it's ancillary to the parameters of interest; i.e. it contains no information about their true values, only affecting the precision with which you can measure them. Cox (1958), "Some Problems Connected with Statistical Inference", Ann. Math. Statist. 29, 2 is usually cited as first explicating what's sometimes known as the Conditionality Principle, though it was implicit in much earlier work, harking back to Fisher's idea of "relevant subsets".
If your researcher's funding was cut off because results so far were disappointing, then of course $n$ isn't ancillary. Perhaps the simplest illustration of the problem is estimation of a Bernoulli probability from either a binomial (fixed no. of trials) or negative binomial (fixed no. successes) sampling scheme. The sufficient statistic is the same under either, but its distribution differs. How would you analyze an experiment where you didn't know which was followed? Berger & Wolpert (1988), The Likelihood Principle discuss the implications of this & other stopping rules for inference.
You might want to think about what happens if you don't take any sampling distribution into account. Armitage (1961), "Comment on 'Consistency in Statistical Inference and Decision' by Smith", JRSS B, 23,1 pointed out that if you sample $x$ from a normal distribution until $\sqrt{n} \bar{x} \leq k$, the likelihood ratio for testing that the mean $\mu=0$ vs $\mu\neq0$ is $\frac{L(0)}{L(\bar{x})}\leq \mathrm{e}^{-k^2/2}$, so the researcher can set a bound on this in advance by an appropriate choice of $k$. Only a frequentist analysis can take the distribution of the likelihood ratio under this rather unfair-seeming sampling scheme into account. See the responses of Kerridge (1963), "Bounds for the frequency of misleading Bayes inferences", Ann. Math. Stat., 34, Cornfield (1966), "Sequential trials, sequential analysis, and the likelihood principle", The American Statistician, 20, 2, & Kadane (1996), "Reasoning to a foregone conclusion", JASA, 91, 435
Pointing out the dependence of frequentist inference on a researcher's intentions is a handy dig at people (if there still are any) who get on their high horse about the "subjectivity" of Bayesian inference. Personally, I can live with it; the performance of a procedure over a long series of repetitions is always going to be something more or less notional, which doesn't detract from its being a useful thing to consider ("a calibration of the likelihood" was how Cox described p-values). From the dates of the references you might have noticed that these issues aren't very new; attempts to settle them by a priori argumentation have largely died down (except on the Internet, always behind the times except in trivial matters) & been replaced by acknowledgement that neither Bayesian nor frequentist statistics are going to collapse under the weight of their internal contradictions, & that there's more than one useful way to apply probability theory to inference from noisy data.
PS: Thinking to add a counter-balance to Berger & Wolpert I happened upon Cox & Mayo (2010), "Objectivity and Conditionality in Frequentist Inference" in Error and Inference. There's quite likely an element of wishful thinking in my assertion that the debate has died down, but it's striking how little new there is to be said on the matter after half a century or so. (All the same, this is a concise & eloquent defence of frequentist ideas.)
Comment: +1 (long time ago). I am wondering if Armitage's reasoning can be adapted to the well-known example of binomial vs neg-binomial sampling; e.g. [observing TTTTTH sequence of coin tosses](http://stats.stackexchange.com/a/40897) yields either p=0.03 or p=0.1 depending on the stopping rule. So, if we now consider yet another stopping rule, e.g. "Keep tossing until binomial p<0.05 and there was at least one H and at least one T", then it becomes rather intuitive that one should rather *not* ignore this stopping rule for inference (despite violating the Likelihood Principle). Does this make sense?
Answer: The short answer to your question is: it depends who you ask ;-) Die-hard Bayesians will declare victory over, or at least parity with, frequentist methodology. Die-hard frequentists will default to "This can't be answered". The other 99% of statisticians will use whatever methods have been shown to be reliable under inerrupted experiments.
I know that the sensitivity of the sampling distribution to the intentions of the researcher can be troubling, and there is really no good solution to that problem. Bayesians and frequentists alike must use some subjectivity and judgement in deciding how to form an inference. However, I think you are taking an example from an area that is generally controversial and laying the problems solely at the feet of frequentist inference. The sequential and/or stopped experiments are classic examples of the subjective nature of inference ... and to which there is no absolutely objective and agreed upon answer.
What about regular inference, where you actually collect the sample you intended to get? Here, I think the frequentists have the upper hand, as CI's and p-values are well calibrated wrt their repeated sampling properties, whereas Bayesian inference retains its personal and subjective nature.
If you want a more theoretical exposition of the Bayesian response, I would read about "conditional inference" with key researchers being Nancy Reid and Lehmann.


Traveling rules in basketball

Question: I have a few related questions about traveling in basketball. I get the general idea, but I am not sure about some specific cases. They all involve the pivot foot leaving the ground. The first three cases are:

You catch the ball standing on one leg. Then you jump off that
leg and land on both feet at the same time. (I understand this is
not a travel, but I am asking to make sure).
You catch the ball standing on one leg. Then you jump off that
leg and land on the non-pivot foot (i.e., the other leg).
You catch the ball standing on one leg. Then you jump off that
leg and land on the pivot foot (i.e., the same leg).

My next series of questions basically asks if it matters is you touch your non-pivot   foot to the ground before doing the jump.

You catch the ball standing on one leg. You touch your other foot
to the ground and raise it again. Then you jump off that leg and
land on both feet at the same time.
You catch the ball standing on one leg. You touch your other foot
to the ground and raise it again. Then you jump off that leg and
land on the non-pivot foot (i.e., the other leg).
(This one is definitely a travel) You catch the ball standing on
one leg. You touch your other foot to the ground and raise it again.
Then you jump off that leg and land on the pivot foot (i.e., the
same leg).

Which if any of these are travels? Also, does it matter if you were instead to catch the ball in the air and then land on one leg, instead of just catching the ball on one leg.
Comment: A player who receives the ball while he is progressing or upon completion of a dribble, may take two steps in coming to a stop, passing or shooting the ball. - NBA Regulations
Answer: The answer to all questions regards the "jump stop". Here is a summary of the traveling rule, which includes this concept:

A player who catches the ball with both feet on the floor may pivot, using either foot. When one foot is lifted, the other is the
  pivot foot.
A player who catches the ball while moving or dribbling may stop and establish a pivot foot as follows:
a. If both feet are off the floor and the player lands;
  (1) Simultaneously on both feet, either foot may be the pivot.
  (2) On one foot followed by the other, the first foot to touch is the pivot.
  (3) On one foot, the player may jump off that foot and simultaneously land
  on both. Neither foot can be a pivot in this case.
b. If one foot is on the floor;
  (1) It is the pivot when the other foot touches in a step.

  (2) The player may jump off that foot and simultaneously land on both. Neither foot can be a pivot in this case.
After coming to a stop and establishing a pivot foot:
a. The pivot foot may be lifted, but not returned to the floor,
  before the ball is released on a pass or try for goal;
  b. If the player jumps, neither foot may be returned to the floor before > the ball is released on a pass or try for goal;
  c. The pivot foot may not be lifted, before the ball is released, to start a dribble.
After coming to a stop when neither foot can be a pivot:
a. One or both feet may be lifted, but may not be returned to the
  floor, before the ball is released on a pass or try for goal;
  b. Neither foot may be lifted, before the ball is released, to start a
  dribble.

So regarding your questions:
Question #1: Sounds like 2.b.2 - If one foot is on the floor: The player may jump off that foot and simultaneously land on both. Neither foot can be a pivot in this case.
Question #2 and Question #3 are covered by Section 3.b: After coming to a stop and establishing a pivot foot: If the player jumps, neither foot may be returned to the floor before the ball is released on a pass or try for goal;
So #1 is not a travel as long as you do not move either foot after landing. #2 or #3 would both be a travel as soon as either foot touches the ground.
For the second batch of questions...
Question #1 sounds like 2.b.1 once your other foot touches the ground, which then becomes 3.b and therefore a travel.
Question #2 and Question #3 are also 2.b.1 to start and then become 3.b (jumping once you have a pivot foot) and thus are also a travel.
Answer: So to answer your specific scenarios:
A

That is not a travel, but neither foot can be the pivot foot, therefore you
may not move either foot from the court before passing or shooting.
This counts as a travel because you switched feet.
This is also a travel, because both feet did not touch after the jump.

B

This does not count as a travel
I'm not sure on this one, could not find any specific references.
Definitely a travel, as you said

C
The first foot to touch automatically becomes the pivot foot, regardless of when the other one touches.
Hope this covers everything!

Traveling rules in basketball


How to draw a string array into a Java Applet?

Question: I'm amateur when it comes to java, I am trying to create an applet that randomizes the sequence "Black Screen British Guy" into a different sequence. e.x. "Screen Black Guy British"
I have got the sequence to print to console, However I am trying to print the strings into a java applet, I'm having trouble with this, and I could use some help. Thanks.
 package bsbg_gen;
import java.lang.String;
import java.io.*;
import java.util.Arrays;
import java.util.Random;
import java.applet.*;
import java.awt.Graphics;

public class main extends Applet {

        public void init(){
             String[] bsbg;
             String[] bsbg2;
             String[] bsbg3;
             String[] bsbg4;

             String [][] name = {{"Black"}, {"Screen"}, {"British"}, {"Guy"}};
             String [][] name2 = {{"Black"}, {"Screen"}, {"British"}, {"Guy"}};
             String [][] name3 = {{"Black"}, {"Screen"}, {"British"}, {"Guy"}};
             String [][] name4 = {{"Black"}, {"Screen"}, {"British"}, {"Guy"}};

             Random rand = new Random();

             bsbg = name [rand.nextInt(name.length)];
             bsbg2 = name2 [rand.nextInt(name2.length)];
             bsbg3 = name3 [rand.nextInt(name3.length)];
             bsbg4 = name4 [rand.nextInt(name4.length)];

             System.out.print(Arrays.toString(bsbg));
             System.out.print(Arrays.toString(bsbg2));
             System.out.print(Arrays.toString(bsbg3));
             System.out.print(Arrays.toString(bsbg4));
        }

        public void stop(){
        }

        public void paint(Graphics g){

            g.drawString((Arrays.toString(bsbg)), 150, 50);

            g.drawString((Arrays.toString(bsbg2)), 150, 50);

            g.drawString((Arrays.toString(bsbg3)), 175, 50);

            g.drawString((Arrays.toString(bsbg4)), 200, 50);
        }

}

Comment: _" I'm having trouble with this"_ - You never explained what the trouble is, or even asked a question.
Comment: 1) Why code an applet?  If it is due to spec. by teacher, please refer them to [Why CS teachers should stop teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 2) Why AWT rather than Swing?  See my answer on [Swing extras over AWT](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon using AWT components.
Comment: @AndrewThompson It's in applet form so it can be embedded into a website.
Comment: *"It's in applet form so it can be embedded into a website."*  Use JavaScript.  It will work a lot better for things like this.
Comment: @peeskillet yes i did.. I asked how I could use something similar to this, however use a java applet and have the strings printed.
Answer: You need to declare these as class members. They're currently not within the scope of the paint method. They're localized in the init method. Take them out.
String[] bsbg;
String[] bsbg2;
String[] bsbg3;
String[] bsbg4;

Declare them outside
String[] bsbg;
String[] bsbg2;
String[] bsbg3;
String[] bsbg4;

public void init(){


Ramsey number for two graphs

Question: Given R(G, H) = n, we have the minimum number such that $K_n$ will always contain G in one color OR H in the other. Is this definition correct? I ask because I'm very confused about the particular wording. For example, if my definition is correct then there should exist a$K_{n-1}$ such that G is not present in one color AND H is not present in the other color.
Am I right so far?
Thanks in advance!
Answer: That's correct, though for greater clarity I would make the quantification over colorings explicit:
If $R(G,H)=n$ then every coloring of the edges of $K_n$ with two colors, call them blue and red, will either contain a blue copy of $G$ or a red copy of $H$. Also, since $n$ in minimum, there exists a blue-red coloring of the edges of $K_{n-1}$ containing no blue $G$ and no red $H.$
A trivial example: $R(K_2,K_3)=3.$ Thus, if each edge of the triangle $K_3$ is colored blue or red, there must be either a blue edge or a red triangle. (Swapping the roles of the colors, there must be a red edge or a blue triangle. So we could also say: either there is a blue triangle, or there is a red triangle, or there are edges of both colors.) On the other hand, we can color $K_2$ so that there is neither a blue triangle nor a red edge. To accomplish that, we color the single edge blue.
Less trivial examples: $R(K_3,K_3)=6$ and $R(K_3,K_4)=9$ and $R(P_5,K_{1,3})=5.$

Ramsey number for two graphs


How to integrate the following geometric brownian motion in Black-Scholes framework

Question: As my previous questions make it obvious, I am very new to this field of mathematics and wondering if I am doing things right in the following question.

Let $T \in (0, \infty)$ and consider a Black-Scholes market for a stock $(S_t)_{t \in [0,T]}$(A geometric Brownian motion with drift $r$ and volatility $\sigma$). Consider the all or nothing option contract with the payoff at time $T$ defined by
$$
\begin{array}{cc}
  g(x)=\{ &
    \begin{array}{cc}
      P & \text{ if }x \geq K \\
      0 & \text{ if } x< K
    \end{array}
\end{array}
$$
where $P>0,K>0$ are given real constants. Compute the price $\Pi(0;g(S_T))$ of the contract $g(S_T)$. Namely, find the expression of $\Pi(0;g(S_T))|_{S_0}=e^{-rT}\mathbb{E}[g(S_T)]$

My attempt was simply find $e^{-rT}\mathbb{E}[g(S_T)]$. So, for the $\mathbb{E}$ bit, I need to calculate
$$\mathbb{E}[g(S_T)]=\int_K^\infty S_T \cdot P\cdot dS_T$$
(I am not sure if this $dS_T$ i.e. integrate wrp to $S_T$ is correct or not) which is due to the general definition of a continuous random variable expected value $\mathbb{E}[x]=\int_{-\infty}^{\infty}xf(x)dx$. But I am not sure how to proceed, i.e. how to integrate this geometric brownian motion...wrp to a geoertic brownian motion(which yes, sounds wrong actually...).
It would be great if someone can guide me here, I hope my basic attempt overall shouldn't be entirely wrong. I think I am not very sure about the details.
Would someone please help me? It would be great if I can get some explanations in the details along rather than just a brief answer, sorry for asking a lot. Thank you very much in advance
Update
I have made some progress hopefully, so please tell me if it looks okay or not.
I have seen that, given some random variable $X$, with pdf $f(x)$, the expected value of a new variable $Y=g(x)$ for some function $g$ is $\mathbb{E}[Y]=\int_{-\infty}^{\infty}g(x)f(x)dx$. I have based my calculations on this.\
So in my case,
\begin{align*}
\mathbb{E}[g(S_T)] &=\int_{-\infty}^{\infty}g(S_T:=x)f(S_T:=x)dx\\
&=\int_{0}^{K}0f(x)dx+\int_{K}^{\infty}Pf(x)dx$\\
\end{align*}
Now since my $S_T$, a geometric brownian motion is lognormally distributed with mean $S_0e^{rt}$ and variance $S_0^2e^{2rt}(e^{\sigma^2t}-1)$, I will substitute these in to the PDF of a lognormal function as my $f(x)$. So,
$$\mathbb{E}[g(S_T)] = \frac{1}{S_0e^{rt} \sqrt{2 \pi(e^{\sigma^2 t}-1)}} \int_{K}^{\infty} \frac{1}{x}e^{- \frac{(lnx-S_0e^{rt})^2}{2S_0^2e^{2rt}(e^{\sigma^2t}-1)}} dx$$
It looks ugly, so I did an interchange of variables introducing $z=lnx-S_0e^{rt}$. Thus I have $x$ from $K \rightarrow \infty|$ then $z$ from $lnK-S_0e^{rt} \rightarrow \infty$ and $dx = e^{z+S_0e^{rt}}dz$. So substituting these, I get something better,
$$\mathbb{E}[g(S_T)] = \frac{1}{S_0e^{rt} \sqrt{2 \pi(e^{\sigma^2 t}-1)}} \int_{lnK-S_0e^{rt}}^{\infty} e^{- \frac{z^2}{c}}dz$$
where $c=2S_0^2e^{2rt}(e^{\sigma ^2t}-1)$
My question is, the integral now involves (Gauss') error function which is well, complicated. I can fortunately compute the error function's value for the one up to $\infty$ which is $\frac{\sqrt{\pi}}{2}$ I think but not for the one up to $lnK-S_0e^{rt}$. All I can think of is expressing it as a Taylor expansion of the error function.
But is this correct? This is the best I can do so far...
Please please help! Thank you again.
Comment: What happened to the probability density function under the integral?  Replace $S_T$ with the lognormal PDF.  The, the integral can be written in terms of the Cumulative Normal Function (related to the error function).  It is the $N(d_2)$ term in the Black-Scholes-Merton formula.  Note that the value is the discounted probability of expiring in the money.
Comment: Hello, thanks for helping; yes I noticed after I posted that it's odd to miss a $f(x)$ in the integral. So the integral is $\int_K^\infty P \cdot \frac{1}{x \sigma \sqrt{2 \pi}}  e^ {      - \frac {(lnx- \mu)^2}  {2 \sigma^2}     } dx$? is this with respect to $dx$?
Comment: That isn't quite correct unless your $mu$ becomes $$\mu =\left(r-\delta-\frac12 \sigma^2\right)(T-t)$$and the $\sigma$ that currently appears in your expression in the comment is replaced with $\sigma\sqrt{T-t}$, where $r$ is the risk-free rate, $\delta$ a continuous yield, $T-t$ is the time remaining from $t$ to expiry at $T$
Comment: I am not entirely sure if I got what you've told me there...but I've made my update based on what I understood from you. If you do have the time, it would be great if you would kindly look into it...thank you so much
Comment: It does not look correct.  If you use the density function that you wrote, corrected as per my previous note, then you should be fine.
Comment: alright, so the density function is correct, BUT i must replace the mean $\mu$ and $\sigma$ in the original function with $\mu=(r-\delta-\frac{1}{2}\sigma^2)(T-t)$ (what is $\delta$ though? It does not appear in my given variables/parameters) and $\sigma$ with $\sigma \sqrt{T-t}$ and proceed with the integration?
Comment: *ohps, I didn't see the "continuous yield for $\delta$ in your previous comment; I'm not sure what that is though...Is it equivalent to the continuous interest rate?
Comment: The yield can account for a continuous dividend yield, the risk-free rate when the underlying is a futures/forward price, or a foreign interest rate when the underlying is the spot exchange rate of currency.
Comment: Okay, so for a final check; is this what you are saying then? $\mathbb{E}[g(S_T)]= \int_K^{\infty} P \frac{1}{x \sigma \sqrt{2 \pi(T-t)}}e^ { -  \frac{(lnx -(r-\delta -\frac{1}{2}\sigma^2)(T-t))^2}{2\sigma^2(T-t)}     }  dx$ this is what I must calculate? I replaced the $\mu$ and $\sigma$ with those in your second comment...
Comment: That looks correct now! Note $P$ is constant and pulls out of the integral.
Comment: Right, thank you so much. As in my edited version, if I proceed with the integration, I end up having to integrate $\frac{P}{\sigma \sqrt{2 \pi (T-t)}}\int_{lnK-(r-\delta-\frac{\sigma^2}{2})(T-t)}^{\infty}e^{-\frac{z^2}{2 \sigma^2(T-t)}}dz$  where I've used $z=e^{z+(r-\delta-\frac{\sigma^2}{2})(T-t)}$. The integration of $e^{-\frac{z^2}{c}}$ is a problem unless I can integrate from $-\infty,\infty$ or $0,\pm\infty$...is there something you would suggest? Because I have to integrate from $lnK-(r-\delta-\frac{\sigma^2}{2})(T-t), \infty$...
Comment: The answer can be expressed in terms of the Cumulative Normal Function (or the Error Function if one prefers).
Comment: I'm sorry this is getting so long; if so, my answer becomes $$\frac{P\sqrt{\pi 2 \sigma^2(T-t)}}{2 \sigma \sqrt{2 \pi(T-t)}} (1 - erf[\frac{lnK-(r-\delta-\frac{\sigma^2}{2})(T-t)}{\sqrt{2 \sigma^2(T-t)}}])$$ which looks quite complicated, but if I may leave my answer in terms of the error function, I think this is the simplest form I can leave it in...If my previous integral with $z$ is correct, I believe this is where I end up...
Answer: You have the right start in that you want to compute
$$
e^{-rT}E_Q(g(S_T))
$$
where $Q$ is the risk-neutral probability measure and, under $Q$,
$$
S_T = S_0e^{\left(r - \frac{\sigma^2}{2}\right)T + \sigma W_T}.
$$
So we have
$$
e^{-rT}E_Q(g(S_T)) = e^{-rT}E_Q(P\cdot \mathbb{I}_{S_T \geq K}) = Pe^{-rT}Q(S_T \geq K),
$$
where the last equality is because
$$
E_Q(\mathbb{I}_{S_T \geq K}) = Q(S_T \geq K).
$$
A simplifying step often done in texts is to use only the normal distribution, instead of the more cumbersome lognormal, as follows.  Note
\begin{align}
S_T \geq K & \iff S_0e^{\left(r - \frac{\sigma^2}{2}\right)T + \sigma W_T} \geq K \\
& \iff \left(r - \frac{\sigma^2}{2}\right)T + \sigma W_T \geq \log \frac{K}{S_0} \\
& \iff W_T \geq \frac{1}{\sigma}\left(\log\frac{K}{S_0} - \left(r - \frac{\sigma^2}{2}\right)T\right) \\
& \iff \frac{W_T}{\sqrt{T}} =: Z  \geq \frac{1}{\sigma\sqrt{T}}\left(\log\frac{K}{S_0} - \left(r - \frac{\sigma^2}{2}\right)T\right) =: -d_2.
\end{align}
Note I'm suggestively calling the RHS $-d_2$, and $Z \sim \mathcal{N}(0,1)$.  Hence, letting $\phi$ be the standard normal pdf and $\Phi$ the standard normal cdf,
\begin{align}
Pe^{-rT}Q(S_T \geq K) & = Pe^{-rT}Q(Z \geq -d_2) \\
& = Pe^{-rT}\int_{-d_2}^\infty \phi(x)\, dx \\
& = Pe^{-rT}\int_{-\infty}^{d_2}\phi(x)\, dx \\
& = Pe^{-rT}\Phi(d_2).
\end{align}


Running bridged-networking vmware player on a Linux machine with 2 interfaces

Question: I have got a laptop running Arch Linux with 2 interfaces: wireless (wlan0) and ethernet (eth0). I use wlan0 to access internet (static IP, networking is configured using netcfg), and I connect a second PC to the eth0.
Now, whenever I start vmware player (v. 4.0.4), it chooses wlan0 to connect its bridged virtual NIC to, but I need it to connect to eth0 (I want my guest machine to be able to talk to the second physical PC on eth0). So, I disable the wlan0 interface (netcfg -d wireless) and restart vmware. Now, it connects to eth0, and everything works fine; I can ping the host PC from the virtual one, and I can ping the virtual PC from the second physical PC connected to eth0. Then, if I try to reenable the wlan0 interface (netcfg -u wireless), all of the connectivity between the host and the guest (and between the second physical PC and the guest) gets lost, until I disable wlan0 again. Can someone please give me a hint on what's going on?
Comment: http://support.tranzeo.com/knowledgebase/users/kb.php?id=10053 might help you out..
Comment: They recommend basically what I am already doing.. Whenever I reenable the wireless interface, all of the communications between the guest and the host on the wired interface fail.
Answer: Don't use VM player. The networking capabilities are limited. The full version will let you choose the desired physical interface so you don't have to "disable interface" to trick vmware.
Or if you are looking for a free one, use virtualbox.
Comment: Unfortunately, I'm stuck with VMWare Player for now.


Fields created by a Feature generated module remains after disabling the module

Question: In my-site-com I created a new feature to show the component: fields , then I added some fields, I download the feature as a module called my-feature-module, then I saved and enabled this module in other drupal installation my-site-2.com.
I get all the fields properly. So far so good.
Now I disabled the module my-feature-module in my-site-2.com and the problem is that the fields are not removed, they remain there. Is this normal? I mean, expected the fields to disappeared if I disable the module.
I make sure I cleared all caches and updated database, just in case it was a cache problem, but problem still persist.
Answer: Yes, this is normal. Some configuration items such as views can be implemented purely as code and some such as fields require database updates. Items in the former category will be removed when you disable a feature, those in the latter category will not. This is not necessarily a good thing but once you understand it, at least you know how to deal with it (manual removal of items).
Comment: ok, I understand. Then, it is like an importation of fields instead of a module which you can enable/disable.


Let's Encrypt certbot cannot complete verification due to Nginx server config

Question: For an application I need the following line in my location block:
rewrite ".*" /server.php break;

This causes certbot fail to verify the domain. To install the SSL cert I commented that line and certbot worked fine. Now, the issue is renewal is automated and will fail if I uncomment the line.
Is there a way to have a dedicated location just for Let's Encript's verification? If so, what?
Here is the full block with the problem line commented:
location / {
    try_files $uri $uri/ =404;
    fastcgi_pass unix:/run/php/php7.1-fpm.sock;
    include fastcgi_params;
    fastcgi_param USE_INSTANCE 'd1';
    fastcgi_param SCRIPT_FILENAME $request_filename;
    #rewrite ".*" /server.php break;
}

If you wonder why I am not limiting the match pattern to ~ \.php$, it is because the config belongs to my api.host.com endpoint which will only receive requests that need to be routed to a PHP script.
Answer: I created a separate location block for certbot.
location /.well-known/acme-challenge/ {
    root /var/www;
    try_files $uri =404;
}

(Note that I use the same document root for every virtual host, which is outside the normal document root, so certbot is never writing anything to the web sites' actual directories.)
Comment: After posting the question I tried `sudo certbot renew --dry-run` (with the line uncommented) and it worked. It may be because on renewal, there is no verification, or because with `--dry-run` the process is just *faked*. So, maybe there is no need for a change, but I'm not sure.

Let’s Encrypt certbot cannot complete verification due to Nginx server config


Do something if :update actually writes anything

Question: I have a function in vim that is calling update and I'd like to call execute to run something in case the buffer was actually modified and written to the disk.
So I'm wondering if there's some sort of return value from update to indicate that, or some other way to know (BufWritePost seems to trigger only when :w is called).
Answer: BufWritePost and BufWriteCmd are triggered just fine when I issued
:update

on my gVim 7.3 (WinXP). The autocommand fired when the buffer was actually modified, and didn't if it wasn't modified.
Tested with
:au!
:au BufWriteCmd *.cpp echo "bufwriteCmd called"

and
:au!
:au BufWritePost *.cpp echo "bufwritePost called"

Comment: This is strange. If I call `update` explicitly it works, but I have a `au CursorMoved *.tex silent update` that fails to trigger the BufWritePost.


It is possible to create and add it new element using javascript or jquery?

Question: I have one code,and i want to create and add new element after specific element but by id or its name using javascript or jquery.It is possible?
here is code:

                            Data Insert Form

                            <?php $data=mysql_fetch_array(mysql_query("select * from admin_seo_meta_tag_data"));?>
                            <form  id="Data-insert" >

                                    Page Title

                                    <input type="text" class="form-control" id="PageTitle" name="PageTitle" value="<?php echo $data['PageTitle'];?>" onFocus="clear_Pagetitle()">
                                    <input type="hidden" id="uid" value="<?php echo $_GET['id'];?>">

                                    Meta description

                                    <input type="text" class="form-control" value="<?php echo $data['MetaDescription'];?>" id="MetaDescription" name="MetaDescription" onFocus="clear_Metadescription()">

                                    Meta Keywords

                                    <input type="text" class="form-control" id="MetaKeywords" name="MetaKeywords" value="<?php echo $data['MetaKeywords'];?>" onFocus="clear_Metakeyword()">

                                    Location

                                    <input type="text" class="form-control" id="Location" name="Location" value="<?php echo $data['Location'];?>" onFocus="clear_Loc()">

                                    <button type="button" onclick="UpdateSeoData()" class="btn btn-primary">Submit</button>
                                    <button type="text" class="btn btn-default">Cancel</button>

                            </form>

Now i am insert data using ajax  getting success,now i want to create new div in which will show success message,i need to create it dynamically because i am creating dynamic inser,update form which do not know about user created div name
thank you all for your help
finally work done
$('.content-header').append('

');
                                                        $('.success_msg').html("
<?php echo $message["success"];?>
");

Comment: Yes it is possible.
Comment: Welcome to Stackoverflow. Please take a moment to take the tour to understand how to use the platform http://stackoverflow.com/tour
Comment: Your question is incomplete, it should contain code sample, what you have done
Comment: Yes it is possible. But can you show us your code? So will be able to assist you more properly
Comment: Yes, you should use: `document.createElement` method, here is a good reference from MDN: [document.createElement](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement)
Comment: ok let me explain fully, ihave one form which get data insert or update using ajax,i am getting ajax success message now i need to display success message using creating new div and display and then disappear but main problem is that i want to show that message at one spacific place or after fix div which i can't do
Comment: i know how to create but how to append it to after specific div which i want?
Comment: @MJ8042 It sounds like you need this: [jQuery.insertAfter](http://api.jquery.com/insertafter/)
Comment: yup i need it too much
Comment: I've added an answer with code example and a reference for the function you are looking for, hope it helps. Now I ask from you (as @AhmadAlfy already said) to find some time and to learn how this system works. If you do that, it will be easier for you to get help next time & also make your posts more useful for the future readers.
Answer: To question:

I want to create and add new element after specific element but by id or its name using javascript or jquery. It is possible?

The answer is: Yes it is possible
There are a lot of completely different ways to do it, but If I understand your explanation in comments, then what you need is to use the method: jQuery.insertAfter
Here is a code example, of how it can be done:

$(function(){
  //Assume yourDiv - is an element that you want to add after element by id="one"
  var yourDiv="
Added after #one
";
  $(yourDiv).insertAfter("#one");
});
<!DOCTYPE HTML>

 <meta charset="UTF-8">
 <title></title>

content of ONE

content of TWO

Side note: jQuery is a Javascript library, so even that I understand what you meant by: "javascript or jquery", but in practical terms it's just Javascript.
Edit Added after OP added code sample:
After seen your code sample, I couldn't ignore a few things:
First - Methods mysql_query,mysql_fetch, etc shouldn't be used anymore, as stated in PHP official reference

...was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used...

I recommend to use: PDO
Second - Using $_GET directly (or any other data that came from client) is UNSAFE. Take a look at: Data validation

...Data from the client should never be trusted...

I recommend to use: filter_input and to check (don't want to sound paranoid but still) every possible bad scenario case.
Answer:     <!DOCTYPE html>

Comment: Bro i have given the execued code which he should use in his ans thats it not to do his entire cod
Comment: @might be obvious to you but not to other people. If you're trying to provide entire *Document preview* code than make sure to use the proper `` and include the necessary. Also, first make sure and answer does not already exists here on StackOverflow that already covers that question. Also, explaining shortly what are your changes and improvements would help.
Comment: Now i included what you expected sir..but i am also trying to give answer day by day i will learn from you guys how to answer


Rails Puma concurrency issue

Question: I am trying to achieve concurrency in a rails puma server on development but am running into trouble.
My endpoint looks like:
<code>    def show
      (1..10).each do |i|
        Rails.logger.info "I!! #{i}"
        sleep(1)
      end
      render json: {health: "hihi"}
    end
</code>
I run hit this endpoint twice, one after the other, and they run in sequence. Can I get them to be more concurrent?
Log:
<code>    puma -t 2:16 -p 3000
    [20186] Puma starting in cluster mode...
    [20186] * Version 3.4.0 (ruby 2.2.2-p95), codename: Owl Bowl Brawl
    [20186] * Min threads: 2, max threads: 16
    [20186] * Environment: development
    [20186] * Process workers: 2
    [20186] * Preloading application
    [20186] * Listening on tcp://0.0.0.0:3000
    [20186] Use Ctrl-C to stop
    [20186] - Worker 0 (pid: 20217) booted, phase: 0
    [20186] - Worker 1 (pid: 20218) booted, phase: 0

    Started GET "/v1/address-service/addresses/1" for 127.0.0.1 at 2016-05-07 19:00:38 -0700
      ActiveRecord::SchemaMigration Load (0.5ms)  SELECT `schema_migrations`.* FROM `schema_migrations`
    Processing by Api::V1::AddressService::AddressesController#show as JSON
      Parameters: {"id"=>"1"}
    I!! 1
    I!! 2
    I!! 3
    I!! 4
    I!! 5
    I!! 6
    I!! 7
    I!! 8
    I!! 9
    I!! 10
    Completed 200 OK in 10143ms (Views: 0.9ms | ActiveRecord: 0.0ms | Elasticsearch: 0.0ms)

    Started GET "/v1/address-service/addresses/1" for 127.0.0.1 at 2016-05-07 19:00:49 -0700
    Processing by Api::V1::AddressService::AddressesController#show as JSON
      Parameters: {"id"=>"1"}
    I!! 1
    I!! 2
    I!! 3
    I!! 4
    I!! 5
    I!! 6
    I!! 7
    I!! 8
    I!! 9
    I!! 10
    Completed 200 OK in 10031ms (Views: 0.3ms | ActiveRecord: 0.0ms | Elasticsearch: 0.0ms)
</code>
development.rb:
<code>  config.cache_classes=false
  config.allow_concurency = true
</code>
Comment: My rails version is: Rails 184.108.40.206
Answer: I realize I was using chrome to test and it only sends one request at a time for what ever reason. I used curl and it works as expected.

Rails Puma concurrency issue


How to get reference field value in term object?

Question: I have term object with referance field .How to get values for referance ids.Please check attached srceenshot of my term object.
I tried this but it return nothing
<code> $ids = array_column($term_object->field_aktivitaetsbild->getValue(), 'target_id');
kint($ids);
</code>
Answer: You can get the IDs like this:
<code>$target_ids = [];

foreach ($term_object->field_aktivitaetsbild as $item) {
  if ($item->entity) {
    $target_ids[] = $item->entity->id();
  }
}
</code>
Source: Programmatically get all names of an entity reference field.
Comment: Actually, if you just want the id, then you can just use $item->target_id. But usually getting the id is just the first step for getting the label or something else from the entity.


In homogeneous ODE

Question: If the solution to an ode is an exponential of x multiplied by $\sin x$ , what "guess" do i use for $y_p$ in order to solve the equation?
I have tried using the guess $e^x(A\sin x + B\cos x)$ but i think it comes out wrong
Comment: Can you post the actual ODE?
Answer: If you have $e^{px}(\cos{(kx)})$, you usually want something of the form
$y_p=c_1e^{(m+ik)x}$, with m or k possibly changing signs. Complex exponentials should simplify the math.

In homogeneous ODE


Using AutoMySQLBackup on Rackspace Cloud

Question: Since Rackspace Cloud only allows FTP access it makes using AutoMySQLBackup a little trickier, and while it is at least creating DB dumps I get errors in the backup log:
<code>###### WARNING ######
Errors reported during AutoMySQLBackup execution.. Backup failed
Error log below..
.../backups/automysqlbackup: line 1791: /usr/bin/find: Permission denied
.../backups/automysqlbackup: line 1855: /usr/bin/find: Permission denied
.../backups/automysqlbackup: line 803: /usr/bin/find: Permission denied
.../backups/automysqlbackup: line 1972: /usr/bin/du: Permission denied
</code>
Since files are being created I'm assuming the find command failing has to do with actually rotating out and deleting the old backups?
Line 803:
<code>find "${CONFIG_backup_dir}/${subfolder}${subsubfolder}" -mtime
+"${rotation}" -type f -exec rm {} \;
</code>
Any ideas for alternatives?
Answer: Well as noted elsewhere, Rackspace Cloud doesn't allow access to the find command. Perhaps some kind of security concern? In any case I ended up building on someone else's bash script which versions daily/weekly/monthly backups without the find command:
<code>#!/bin/bash
####################################
#
# Purpose:  Create daily, weekly and monthly rotating backups
#           (Originally for WordPress web content and MySQL DB
#           on Rackspace Cloud Sites)
#
#####################################

##### SETTINGS #####
BACKUP_NAME="SOMEWEBSITE Web & DB Backup"                               # What is the name of this backup?
BACKUP_SITEROOT=""                                                      # Root directory of website
BACKUP_TARGET=$BACKUP_SITEROOT"/backups"                                # Where to store the backups
BACKUP_FILES=$BACKUP_SITEROOT"/web/content"                             # What directories to backup

# Database info
DB_USER=""
DB_PASS=""
DB_HOST=""
DB_NAME=""

# How many weekly backups and monthly backups to save
WEEKS_TO_SAVE=4     # default: 4
MONTHS_TO_SAVE=6    # default: 6

# Which day of the week and month to version backups on
BACKUP_DAYOFWEEK="Saturday"  # default: "Saturday"
BACKUP_DAYOFMONTH=1          # default: 1

# Archive file names
ARCHIVE_DB="db_backup_"`date +%Y-%m-%d`
ARCHIVE_WEB="web_backup_"`date +%Y-%m-%d`.tar.bz2

/bin/echo "======================================================================"
/bin/echo "Starting Backup Task:" $BACKUP_NAME
/bin/echo "======================================================================"

# CREATE DAILY BACKUP
/bin/echo "Creating daily backup archives..."

# Check to make sure the folders exist, if not create them.
/bin/mkdir -p $BACKUP_TARGET/daily.{0..6}

# Delete the oldest backup folder.
/bin/rm -rf $BACKUP_TARGET/daily.7

# Shift all the backup folders up a day.
for i in $(eval echo {7..1})
 do
    /bin/mv $BACKUP_TARGET/daily.$[${i}-1] $BACKUP_TARGET/daily.${i}
 done

# Create tar'ed and bzip2 archive of web content
tar cfj $BACKUP_TARGET/daily.1/$ARCHIVE_WEB $BACKUP_FILES

# Dump MySQL DB and create bzip2 archive
mysqldump --opt -h $DB_HOST -u $DB_USER -p$DB_PASS $DB_NAME > $BACKUP_TARGET/daily.1/$ARCHIVE_DB.sql
bzip2 $BACKUP_TARGET/daily.1/$ARCHIVE_DB.sql

# CREATE WEEKLY BACKUP
DAYOFWEEK=$(date +%A)
if [ $DAYOFWEEK == $BACKUP_DAYOFWEEK ]
then
    /bin/echo "It's" $DAYOFWEEK"! Copying latest Daily backups to Weekly..."

    # Check to make sure the folders exist, if not create them.
    eval "/bin/mkdir -p $BACKUP_TARGET/weekly.{0..$WEEKS_TO_SAVE}"

    # Delete the oldest backup folder.
    /bin/rm -rf $BACKUP_TARGET/weekly.$WEEKS_TO_SAVE

    # Shift all the backup folders up a day.
    for i in $(eval echo {$WEEKS_TO_SAVE..1})
     do
        /bin/mv $BACKUP_TARGET/weekly.$[${i}-1] $BACKUP_TARGET/weekly.${i}
     done

    # Copy archives to weekly
    /bin/cp $BACKUP_TARGET/daily.1/* $BACKUP_TARGET/weekly.1/
else
    /bin/echo "Skipping Weekly archive creation until" $BACKUP_DAYOFWEEK
fi

# CREATE MONTHLY BACKUP
DAYOFMONTH=$(date +%d)
if [ $DAYOFMONTH -eq $BACKUP_DAYOFMONTH ]
then
    /bin/echo "It's the" $DAYOFMONTH"st! Copying latest Daily backups to Monthly..."

    eval "/bin/mkdir -p $BACKUP_TARGET/monthly.{0..$MONTHS_TO_SAVE}"

    # Delete the oldest backup folder.
    /bin/rm -rf $BACKUP_TARGET/monthly.$MONTHS_TO_SAVE

    # Shift all the backup folders up a day.
    for i in $(eval echo {$MONTHS_TO_SAVE..1})
     do
        /bin/mv $BACKUP_TARGET/monthly.$[${i}-1] $BACKUP_TARGET/monthly.${i}
     done

    # Copy archives to monthly
    /bin/cp $BACKUP_TARGET/daily.1/* $BACKUP_TARGET/monthly.1/
else
    /bin/echo "Skipping Monthly archive creation until the" $BACKUP_DAYOFMONTH"st"
fi

/bin/echo "======================================================================"
/bin/echo "Completed Backup Task:" $BACKUP_NAME
/bin/echo "======================================================================"
</code>


Getting Rails to work on Heroku with Mongo db

Question: I have downloaded an open-source code ribbot. I am new to Ruby and Rails but I have set up my environment and was able to get this code to run on my local machine.
I wanted to use Heroku as my server base solution. I pushed this app to Heroku. Heroku seems to tell me that the app is running fine however I keep getting redirected to an error page via the open-source code; it doesn't do so on my local machine. I suspect that it has something to do with Mongo. I have downloaded the add on MongoHQ for Heroku and am still experiencing this problem. I do know that this code uses mongoid:
2012-04-16T19:06:47+00:00 app[web.1]: localhost:11211 failed (count: 2)
2012-04-16T19:06:47+00:00 app[web.1]:
2012-04-16T19:06:47+00:00 app[web.1]:
2012-04-16T19:06:47+00:00 app[web.1]: Started GET "/" for 18.104.22.168 at 2012-04-16 19:06:47 +0000
2012-04-16T19:06:47+00:00 app[web.1]: allow_dynamic_fields is not a valid option for Mongo::Connection
2012-04-16T19:06:47+00:00 app[web.1]: autocreate_indexes is not a valid option for Mongo::Connection
2012-04-16T19:06:47+00:00 app[web.1]: identity_map_enabled is not a valid option for Mongo::Connection
2012-04-16T19:06:47+00:00 app[web.1]: include_root_in_json is not a valid option for Mongo::Connection
2012-04-16T19:06:47+00:00 app[web.1]: include_type_for_serialization is not a valid option for Mongo::Connection
2012-04-16T19:06:47+00:00 app[web.1]: max_retries_on_connection_failure is not a valid option for Mongo::Connection
2012-04-16T19:06:47+00:00 app[web.1]: parameterize_keys is not a valid option for Mongo::Connection
2012-04-16T19:06:47+00:00 app[web.1]: scope_overwrite_exception is not a valid option for Mongo::Connection
2012-04-16T19:06:47+00:00 app[web.1]: persist_in_safe_mode is not a valid option for Mongo::Connection
2012-04-16T19:06:47+00:00 app[web.1]: preload_models is not a valid option for Mongo::Connection
2012-04-16T19:06:47+00:00 app[web.1]: raise_not_found_error is not a valid option for Mongo::Connection
2012-04-16T19:06:47+00:00 app[web.1]: skip_version_check is not a valid option for Mongo::Connection
2012-04-16T19:06:47+00:00 app[web.1]: time_zone is not a valid option for Mongo::Connection
2012-04-16T19:06:47+00:00 app[web.1]: use_utc is not a valid option for Mongo::Connection
2012-04-16T19:06:47+00:00 app[web.1]: timestamped_migrations is not a valid option for Mongo::Connection
2012-04-16T19:06:50+00:00 app[web.1]:
2012-04-16T19:06:50+00:00 app[web.1]: Mongo::ConnectionFailure (Failed to connect to a master node at localhost:27017):
2012-04-16T19:06:50+00:00 app[web.1]:   app/controllers/application_controller.rb:19:in `current_forum'
2012-04-16T19:06:50+00:00 app[web.1]:   app/controllers/application_controller.rb:40:in `require_current_forum!'
2012-04-16T19:06:50+00:00 app[web.1]:
2012-04-16T19:06:50+00:00 app[web.1]:
2012-04-16T19:06:50+00:00 app[web.1]: cache: [GET /] miss
2012-04-16T19:06:50+00:00 app[web.1]:   Processing by PostsController#index as HTML
2012-04-16T19:06:50+00:00 app[web.1]: Completed 500 Internal Server Error in 2997ms
2012-04-16T19:06:50+00:00 app[web.1]: Rendered vendor/bundle/ruby/1.9.1/gems/exception_notification_rails3-1.2.0/lib/exception_notifier/views/exception_notifier/_request.text.erb (0.2ms)
2012-04-16T19:06:50+00:00 app[web.1]: Rendered vendor/bundle/ruby/1.9.1/gems/exception_notification_rails3-1.2.0/lib/exception_notifier/views/exception_notifier/_title.text.erb (0.0ms)
2012-04-16T19:06:50+00:00 app[web.1]: Rendered vendor/bundle/ruby/1.9.1/gems/exception_notification_rails3-1.2.0/lib/exception_notifier/views/exception_notifier/_session.text.erb (0.2ms)
2012-04-16T19:06:50+00:00 app[web.1]: Rendered vendor/bundle/ruby/1.9.1/gems/exception_notification_rails3-1.2.0/lib/exception_notifier/views/exception_notifier/_title.text.erb (0.0ms)
2012-04-16T19:06:50+00:00 app[web.1]: Rendered vendor/bundle/ruby/1.9.1/gems/exception_notification_rails3-1.2.0/lib/exception_notifier/views/exception_notifier/_environment.text.erb (23.9ms)
2012-04-16T19:06:50+00:00 app[web.1]: Rendered vendor/bundle/ruby/1.9.1/gems/exception_notification_rails3-1.2.0/lib/exception_notifier/views/exception_notifier/_title.text.erb (0.0ms)
2012-04-16T19:06:50+00:00 app[web.1]: Rendered vendor/bundle/ruby/1.9.1/gems/exception_notification_rails3-1.2.0/lib/exception_notifier/views/exception_notifier/_backtrace.text.erb (0.1ms)
2012-04-16T19:06:50+00:00 app[web.1]: Rendered vendor/bundle/ruby/1.9.1/gems/exception_notification_rails3-1.2.0/lib/exception_notifier/views/exception_notifier/_title.text.erb (0.0ms)
2012-04-16T19:06:50+00:00 app[web.1]: Rendered vendor/bundle/ruby/1.9.1/gems/exception_notification_rails3-1.2.0/lib/exception_notifier/views/exception_notifier/exception_notification.text.erb (26.8ms)
2012-04-16T19:06:50+00:00 app[web.1]:
2012-04-16T19:06:50+00:00 app[web.1]: Sent mail to email@example.com (274ms)
2012-04-16T19:06:50+00:00 heroku[router]: GET impact-project.herokuapp.com/ dyno=web.1 queue=0 wait=0ms service=3832ms status=500 bytes=728
2012-04-16T19:06:51+00:00 app[web.1]: localhost:11211 failed (count: 3)
2012-04-16T19:06:51+00:00 app[web.1]: cache: [GET /favicon.ico] miss, store
2012-04-16T19:06:51+00:00 app[web.1]: [2012-04-16 19:06:51] ERROR NoMethodError: undefined method `each' for nil:NilClass
2012-04-16T19:06:51+00:00 app[web.1]:   /app/vendor/bundle/ruby/1.9.1/gems/rack-1.3.5/lib/rack/handler/webrick.rb:71:in `service'
2012-04-16T19:06:51+00:00 app[web.1]:   /usr/local/lib/ruby/1.9.1/webrick/httpserver.rb:111:in `service'
2012-04-16T19:06:51+00:00 app[web.1]:   /usr/local/lib/ruby/1.9.1/webrick/httpserver.rb:70:in `run'
2012-04-16T19:06:51+00:00 app[web.1]:   /usr/local/lib/ruby/1.9.1/webrick/server.rb:183:in `block in start_thread'
2012-04-16T19:06:51+00:00 heroku[router]: GET impact-project.herokuapp.com/favicon.ico dyno=web.1 queue=0 wait=0ms service=517ms status=500 bytes=337

Comment: Can we see your `config/mongoid.yml`?
Comment: Also, have you installed any of the Mongo add-ons on Heroku?
Comment: Hi sorry for the late reply. Yes I have added the mongo add-ons
Comment: development:
  host: localhost
  database: ribbot_development

test:
  host: localhost
  database: ribbot_test

production:
  uri: <%= ENV['MONGOLAB_URI'] %>
Comment: Does this mean I should use mongolab instead of mongoHQ?
Answer: If you've installed the MongoHQ add-on in Heroku, it creates a MONGOHQ_URL environment variable which your Rails app can use to connect to the database. Looks like your config/mongoid.yml isn't configured properly. Here's a working example for Heroku & MongoHQ:
development:
    host: localhost
    database: yourapp_dev

test:
   host: localhost
   database: yourapp_test

# set these environment variables on your prod server
production:
    uri: <%= ENV['MONGOHQ_URL'] %>

Hope this helps!
Comment: Thank you for your response. Just saw that my mongoid.yml is very simillar to urs but mine specified MONGOLAB_IRL. Does this mean I should install the mongolab add on?
Comment: It just depends on what your Heroku app is using and what your preferences are. Check to see if you have either addon installed on your app by using the command ```heroku addons``` in your CLI. If neither are there, just pick and use whichever you like. The environment variable should work the same either way in your Rails config.


XPath Text or Child Node

Question: I have a Div element on a page which is used to display error messages. This div is invisible unless it is populated.
Unfortunately, the content type is inconsistent. In some cases it can have a direct child text node, which I could pick up with:

contains(text(),'*'))

or it can contain a  which contains its own child text node, which I could pick up with:

//div/span[contains(text(),'*')]

As much as I would like to, I cannot change this behaviour.
Example 1:

Error Message

Example 2:

    Error Message 1
Error Message 2

Fortunately, I really don't need to know the contents, I just need to know if the div is non-empty.
Can anyone help me out?
Comment: You could try [boolean](https://developer.mozilla.org/en-US/docs/Web/XPath/Functions/boolean) xpath function. If node exist it returns true e.g. `boolean(//div[@id="TopErrorMessageDiv"]//text())`
Answer: Try this one
//div[@id="TopErrorMessageDiv" and .//text()]

to match div that contains any text content
Answer: This should work for you as well
//div[@id="TopErrorMessageDiv" and string-length(text()) > 0]

XPath Text or Child Node


F# script change argument in function

Question: I've just studied F# scripting, and I have a strange situation with changing variable in it:
let ParseActual (arg:string) = let mutable value = false
                               if arg.[1] = '-' then value <- false
                               else value <- true
                               if arg.[1] = '-' || arg.[1] = '+' then ref arg := arg.Remove(0,2)
                               else (
                                        Console.WriteLine(arg)
                                        ref arg := arg.Remove(0,1)
                                        Console.WriteLine(arg)
                                    )
                               AddActual(arg, value)

But it doesn't change the string. First output \r and second is the same \r. What's wrong removing some characters from string and assigning it a new value?
Answer: The arg string is immutable. What you can do is to use the string to create and return a new string with changed literal but you won't be able to mutate the existing string.
It's the case with all variables (not the most fortunate word, I know) in F#, once they are created and bound to a value they cannot be changed (unless you explicitly use the mutable keyword, as you did for the bool value).
Comment: yeah I know the keyword mutable, i've used it already. If I write `let mutable arg1 = arg` and change arg1 will it work? Or I should create a new string and assign it to mutable variable
Comment: I would go for creating a new string entirely. It's more idiomatic for F# and for functional programming.

F# script change argument in function


When/should I add breath marks to my woodwind/brass score?

Question: I have two questions concerning how a composer writes breath marks in their score for brass/woodwinds:
First: Is it required that the composer notate breath marks where players can/should breathe, or would the composer leave that out and let players decide, in their own parts, when and where to breathe?
Second: When several players of a particular instrument section (such as four French horn players) are playing a long passage, do some players pause to breathe whilst others keep playing, thus producing a continuous tone, or do all players stop and resume simultaneously? If it's the former, is there a way to notate that in a score (e.g., "Pl.1+2 breathe here" or something)?
Answer: No, breathing marks are not required. However, if it's important that breathing occurs at a specific place, then notate it. Especially if the location isn't intuitive.
If you don't write breathing marks, players will generally aim for the end of a phrase. At least, decent players will. If you're writing for a younger or inexperienced player, more notation can help. Your aim should be to communicate exactly the required level of detail. If it's obvious where I should breathe, don't notate it. The trick is figuring out what is obvious.
The easiest way to notate a continuous tone is to write "stagger breathing" or similar above the passage. This asks the players to coordinate their breathing such that the tone doesn't stop. You can also explicitly notate breathing to achieve the same effect.
Comment: Thanks for the info. "Stagger breathing" in particular is exactly what I was looking for.
Comment: The first instance means the composer really wants a small break there, perhaps the (non-obvious) end of a phrase.     Agree entirely with the "figur[e] out what is obvious" part.


Determining confidence interval with one observation (for Poisson distribution)

Question: When you make only one measurement, how do you determine 95% confidence interval for the Poisson distribution?
Let's say that I make one measurement of a quantity $x$ and obtain $x=10$. Also it is known that the population $x$ is Poisson-distributed. If I want to calculate 95% confidence interval for the population mean, then how can I find the corresponding z-score?
One says the margin of error for 95% is $1.96\lambda$. I wonder how to obtain the $1.96$. Please note that in the example above the sample size is one.
Comment: Related https://stats.stackexchange.com/questions/15371/how-to-calculate-a-confidence-level-for-a-poisson-distribution
Answer: If $X \sim \mathsf{Pois}(\lambda).$ then $E(X) = \lambda$ and $SD(X) = \sqrt{\lambda}.$ For sufficiently large $\lambda,$ the random variable $X$ is approximately normally distributed. Then one says that $Z = \frac{X -\lambda}{\sqrt{\lambda}}$ is
approximately standard normal, so that
$$P\left(-1.96 < \frac{X -\lambda}{\sqrt{\lambda}} < 1.96\right) \approx 0.95.$$
This gives rise to $P(X - 1.96\sqrt{\lambda} < \lambda < X + 1.96\sqrt{\lambda})\approx0.95.$
Again, for sufficiently large $\lambda,$ one says that $1.96\sqrt{\lambda} \approx 1.96\sqrt{X}.$ So finally, an approximate 95% confidence interval
for $\lambda$ is of the form $$(X - 1.96\sqrt{X},\;X + 1.96\sqrt{X}).$$
This type of interval was proposed by Wald as asymptotically accurate for
$\lambda \rightarrow \infty.$ It works reasonably well for $\lambda > 50.$
For smaller $\lambda,$ a confidence interval with somewhat closer to 95% coverage is $$(X+2 - 1.96\sqrt{X+1},\; X+2 + 1.96\sqrt{X+1}).$$

Rationale: This adjusted 95% interval for smaller $\lambda$ is based on 'inverting' a
standard test for $H_0: \lambda = \lambda_0$ vs. $H_a: \lambda \ne \lambda_0,$ with test
statistic $Z = \frac{X - \lambda_0}{\sqrt{\lambda_0}},$ which rejects
at the 5% level for $|Z| \ge 1.96.$
Specifically for given $X,$ the adjusted interval
is found by solving a quadratic inequality for values $\lambda_0$
with $|Z| < 1.96$ and conflating $1.96$ with $2$ to obtain the terms with $X + 2$ and $X+ 1.$ In effect, the adjusted CI consists of non-rejectable hypothetical values of $\lambda_0.$ (One still assumes that $Z$ is approximately standard normal, but the additional assumption
that $1.96\sqrt{\lambda} \approx 1.96\sqrt{X}$ is no longer required.)

For both styles of CIs, an approximate 90% confidence interval is shorter, using $\pm 1.645$ instead of $\pm 1.96.$
Because a Poisson distribution is discrete, actual coverage probabilities can vary by a surprising amount with a small change in the value of $\lambda.$ Here is a graph that shows actual coverage probabilities of the second (small $\lambda)$ type of "95%" confidence interval given above, for many values of $\lambda$ between $0.5$ and $30.$ For $\lambda > 5,$ coverage probabilities are not far from 95%.

The figure was made using the following R code:
<code>lam = seq(.5, 30, by=.0001); m = length(lam) # values of lambda
t = 0:200 # realistic values of T
LL = t+2 - 1.96*sqrt(t+1); UL = t+2 + 1.96*sqrt(t+1) # corresp. CIs
cov.pr = numeric(m)
for(i in 1:m) {
lam.i = lam[i] # pick a lambda
cov = (lam.i >= LL & lam.i <= UL) # TRUE if CI covers
cov.pr[i] = sum(dpois(t[cov], lam.i)) } # sum probs for covering T's
plot(lam, cov.pr, type="l", ylim=c(.8,1), lwd=2, xaxs="i")
 abline(h=.95, col="green3")
</code>
Addendum: By contrast, making obvious minor changes in the program above, we have the following graph showing the true coverage probabilities of a "95%" Wald confidence interval for $\lambda.$


Como faze site ser acessado com e sem "www"

Question: meu site está acessando apenas sem o "www"
dentro do diretório do meu site, tem um .htaccess com essa regra:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^subdominio\.meusite\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.subdominio\meusite\.com$
RewriteRule ^(.*)$ "http\:\/\/subdominio\meusite\.com\.br/$1" [R=301,L]

Eu uso o CentoS e Apache.
Será que tenho que ver alguma parada de módulo Rewrite se está ativo ou inativo no meu servidor?
Como eu faço isso?
E um outro problema, é que as minhas páginas só estão sendo acessadas com a extensão no final: .php, .html etc.. Como posso corrigir isso também?
Answer: Para o problema das extensões verifique no arquivo de conf do seu apache o parâmetro dir_module, se não tiver adicione as seguintes linha:
<IfModule dir_module>
    DirectoryIndex index.html index.php
</IfModule>

Reinicie o apache e teste, isso permite que os arquivos index.html ou index.php na pasta raiz do site dentro do apache serem aberto automaticamente para o usuário Ex: o que antes era acessado com www.meusite.com.br/index.php agora poderá ser acessado com www.meusite.com.br, os nomes index.html e index.php são comumente utilizados como padrão (se não for padrão para o seu caso adicione o nome do arquivo do diretório raiz do servidor apache que queira abrir).
Sobre o acesso do seu site precisar conter o www no inicio você vai precisar criar uma entrada DNS, se você utiliza o Bind como servidor DNS você deve ter a zona referente ao seu site criada, é bem provável que você tenha algo parecido com isso em seu servidor DNS.
zone "meusite.com.br" {
        type master;
        file "/etc/namedb/remote/meusite.com.br.zone";
};

vá até o arquivo meusite.com.br.zone e crie a entrada www para o seu site:
www            IN      A       XXX.XX.XX.XX (IP publico do seu servidor web)

Se este IP já tem algum nome cadastrado o que geralmente acontece crie uma entrada CNAME, Incremente o serial do arquivo de conf do DNS e reinicie o serviço do DNS para que sua entrada DNS possa se propagar ao redor do mundo.


How to tell if two QPushButtons have been pressed (Python)

Question: I need to call a member function when both of my QPushButtons have been pressed.  I cannot find a way to keep track of if they have been pressed.
I call a function when either of the buttons are clicked using ...clicked.connect(func) and within that function I have tried to: 1) return a value, 2) update a member variable. Below I have shown how I tried to create and update member variable and use a conditional to see if both variables were true so that I could call my next function.
def __init__(self, parent=None):
    super(MorphingApp, self).__init__(parent)
    self.setupUi(self)

    self.startIm = None
    self.endIm = None

    self.initialState()

def initialState(self):

    self.btn_loadStart.clicked.connect(self.loadImageS)
    self.btn_loadEnd.clicked.connect(self.loadImageE)

    if(self.startIm is True and self.endIm is True):
        self.loadedState()

def initialState(self):
    self.startIm = True

def loadImageE(self):
    self.endIm = True

My functions of course do things, but I removed parts that were irrelevant.   When I run the GUI I am able to load the images but the function that is supposed to be called after both buttons have been pushed is not called.  I know this because the state of the GUI is not changing as I intend.
This is my first time posting a question so let me know how to improve :)
Answer: def __init__(self, parent=None):
    super(MorphingApp, self).__init__(parent)
    self.setupUi(self)

    self.startIm = False
    self.endIm = False

    self.btn_loadStart.clicked.connect(self.loadImageS)
    self.btn_loadEnd.clicked.connect(self.loadImageE)

def loadImageS(self):
    self.startIm = True

    if self.startIm and self.endIm:
        self.loadedState()

def loadImageE(self):
    self.endIm = True

    if self.startIm and self.endIm:
       self.loadedState()

Answer: Use a simple True/False flag to check if the button has been pressed at least once. Both buttons start with the flag set to False, so we can set that up in the init method.
Then place the code that checks to see if both buttons have been pressed inside the functions connected to them. Finally, simply call the respective "final" function if the check passes.
This is an example using two generic buttons:
def __init__(self, parent=None):
    super(MorphingApp, self).__init__(parent)
    self.btn_01_pressed = False
    self.btn_02_pressed = False
    self.set_buttons()

def set_buttons(self):
    self.btn_01.clicked.connect(self.check01)
    self.btn_02.clicked.connect(self.check02)

def check01(self):
    self.btn_01_pressed = True
    if self.btn_01_pressed is True and self.btn_02_pressed is True:
        self.call_final_function()

def check02(self):
    self.btn_02_pressed = True
    if self.btn_01_pressed is True and self.btn_02_pressed is True:
        self.call_final_function()

def call_final_function(self):
    # do something great here

Like in your post I've ommited some parts necessary for the actual code (like creating the QPushButton widgets), but hopefully you get the idea.


Hearing both piano hands (MIDI), but only the right one is visible on Bitwig piano roll

Question: I have created a piano track, exported it as a MIDI file and loaded it on Bitiwg. When I hit play, I can hear both hands, but on the Piano Roll, only the notes of the right hand are visible.
How can I fix this? The left hand is audible, so the notes must be somewhere, but I cannot find where they are, or why I cannot see them.
Comment: What was the process to create the track initially? are you sure it didn't create two different tracks for the two registers (treble/bass)?
Comment: Again, it depends on the way the MIDI rendition was originally created. If it's a performance that was MIDI recorded both hands simultaneously, it's odd that two different tracks were created. But if the two parts were recorded or edited separately, there can be a number of reasons why that is: different clips in the same track that the DAW exports as different tracks by default,  default behaviour to create different tracks for notes entered in different staffs, etc.
Comment: @joseem yes. Now that I look at it there are 2 separate parts. Why is that?
Answer: Would it help to describe the way MIDI segregates Left and Right on my Yamaha Clavinova piano? There are a few options for single, dual, split and split+dual voices.
In its startup configuration, the keyboard creates a single MIDI track containing the notes played by both hands.  I can assign that stream of MIDI events to a MIDI channel I choose.  This is how I use MIDI presently to communicate with a software program I am writing.
The piano control panel has a Dual/Split button and a piano setting to set a keyboard split allowing two voices: one for keys below the split and another for keys above the split. The Piano's MIDI output configuration settings allow the user to map each voice to a distinct MIDI channel. (I have not checked whether the piano allows both voices to be assigned to the same MIDI channel - it would not make a lot of sense to do this if it was not possible to segregate the MIDI events into two voices - but you never know until you try!) I think the piano adjusts the Key number in the MIDI event so that both splits report notes either side of a middle C (note 60 in MIDI) as though you were playing two distinct keyboards.
The piano also has a feature allowing two voices to be generated at the same time for the same keys.  In these configurations the keyboard generates duplicate MIDI events that can be assigned to two distinct MIDI channels.
Finally, there is a Split+Dual mode in which the Right hand split has a dual voice.  This should allow a keystroke above the split to generate duplicate MIDI events - overall this would create events assignable to 3 MIDI channels (Yamaha use L+R1/R2 in their MIDI manual when describing this).
The Piano settings has a section devoted to configuring MIDI.  The MIDI settings in the piano allow me to set the MIDI channels for each output (and each input if also sending MIDI events to the piano synthesiser or sequencer).


Making a  inherit the height of parent () using only css?

Question: http://jsfiddle.net/ZAvDd/
As my table row grows in height, I'd like my div inside to automatically match it as well.
For the code above, my div's height is always 0.
I understand that the height:inherit only works when you explicitly state the height of the parent () but I don't want to do that because I have no idea what content height will be displayed there.
Is there any css trick to do this or do I have to resort to some JS?
Answer: You cannot using a height rule, but you can still achieve the effect you're after by positioning the div absolutely. Since this changes the layout of the div, you will then have to apply the width to the td instead:
td.fooed {position:relative; width:30px;}
td.fooed .foo {
    position:absolute; top:0px; left:0px; right:0px; bottom:0px;
    background:gray;
}

Here's your fiddle: http://jsfiddle.net/ZAvDd/2/
Comment: Well, you could try to use css flexbox, but I wouldn't recommend it. The flexbox spec has changed and it's "final" state isn't well supported, as well as no support under IE10. http://caniuse.com/#search=flexbox
Comment: Thanks. I'm a novice at css but is absolute positioning the only way? I'm gonna be frank here: it's 2013 and we still have to resort to these little hacks?
Comment: Thanks for the hack. You can also shorten the code by simply saying `inset: 0;` on the div.
Answer: What is the purpose of your div?
Your div has currently a height of 0 (zero) because it's empty. What you can do is apply the style directly to your parent td by adding a class to it:

And style it accordingly:
.bar { background: gray;}

It really depends on the purpose of your div.
Comment: jsFiddle above is merely an example. Just take it as a div that fills the parent height.


primitive polynomials and their factorisation

Question: A polynomial with integer coefficients is called
primitive if its coefficients are relatively prime. For
example, $$3{x^2} + 7x + 9$$ is primitive while $$10{x^2} + 5x + 15$$
is not.
(a) Prove that the product of two primitive polynomials is primitive.
(b) Use this to prove Gauss's Lemma: If a polynomial with integer coefficients can be factored
into polynomials with rational coefficients, it
can also be factored into primitive polynomials
with integer coefficients
Comment: What did you try so far?
Answer: For the first part let $f$ and $g$ be primitive polynomials in $\mathbb{Z}$ and assume their product isn't, i.e. there exists prime number $p$ that divides all coefficients of $f\cdot g$. Now define the following mapping:
$$\phi = \begin{cases} \mathbb{Z}[x] \to \mathbb{Z}_p[x] \\ a_nx^n + a_{n-1}x^{n-1} + ... a_0 \to [a_n]x^n + [a_{n-1}]x^{n-1} + ... + [a_0] \end{cases}$$
Prove that it's epimorphism and as $\mathbb{Z}_p[x]$ is an integral domain we have that $\phi(f)\phi(g) = \phi(f \cdot g) =  0$ implies that one of the polynomials isn't primitive.

For the second part let $f,g \in \mathbb{Q}[x]$. Let $b$ be the LCM of the denominators and $a$ be the GCD of the nominators of $f$ and similarly define $c,d$ for $g$. Now $f = \frac{a}{b} \cdot F$ and $g = \frac{c}{d} \cdot G$, where $F,G \in \mathbb{Z}[x]$ and they are primitive.
Then we have $h = \frac{a}{b} \cdot F \cdot \frac{c}{d} \cdot G \implies bd \cdot h = ac \cdot F \cdot G$. But $F\cdot G$ is primitive, as well as $h$, so we must have $ac = bd$. So: $$h = f \cdot g = F \cdot G$$

Here's a more elementary solution to the first part. Let $f(x) = a_nx^n + a_{n-1}x^{n-1} + ... + a_0$ and $g(x) = b_tx^t + b_{t-1}x^{t-1} + ... + b_0$. Now assume that $p \mid f \cdot g$ for some prime number $p$. As both are primitive there exist coefficients $a_i$ and $b_j$ that aren't divisible by $p$. Let $a_i$ and $b_j$ be the coefficients such that $p \not \mid a_i, b_j$, but $p \mid a_s, b_u$ for $s>i$ and $u>j$. Now let's consider the coefficient in front of $x^{i+j}$ in $f \cdot g$. We have:
$$ c_{i+j} = a_0b_{i+j} + a_1b_{i+j-1} + ... + a_ib_j + ... + a_{i+j-1}b_1 + a_ib_0$$
Using the previously mentioned things we have that $0 \equiv c_{i+j} \equiv a_ib_j \pmod p$, an ovcious contradiction. Hence the claim is proven by contradiction.
Comment: Note that the problem is tagged "elementary number theory" but not "abstract algebra", so the OP may not be familiar with ring theory.
Comment: I added a proof avoiding ring theory.
Comment: @BillDubuque I will try to find some easier and more understandable proof for the first part. The second one, except for the notation doesn't use any abstract algebra
Answer: Since you tagged it elementary number theory and not abstract algebra, here is an approach that does not require any knowledge of ring theory.
Write the polynomials as $\,A,B.\,$ Suppose $\,p\nmid A,B.\,$ So when reduced mod $\,p,\,$ both are $\not\equiv 0$ hence they have leading coef's $\,a,b\not\equiv 0\pmod p.\,$ By $\,p\,$ prime:  $\,p\nmid a,b\,\Rightarrow\, \color{#c00}{p\nmid ab},\,$ so
$$ \begin{eqnarray} A &\equiv&\ \  a\ x^j + \:\cdots,\quad\ \ a\not\equiv 0\pmod p\\   B &\equiv&\ \   b\ x^k + \:\cdots,\quad\ \ b\not\equiv 0\pmod p\\ \Rightarrow\ AB &\equiv& \color{#c00}{ab}\ x^{j+k}\! + \:\cdots,\ \color{#c00}{ab\not\equiv 0}\pmod p\end{eqnarray}$$
So $\,p\nmid AB.\,$ Said contrapositively, $\ p\mid AB\,\Rightarrow\,p\mid A\,$ or $\,p\mid B,\, $ i.e. a prime $\,p\in \Bbb Z\,$ remains prime in $\,\Bbb Z[x] = $ polynomials with integer coefficients. This preservation of the prime divisor property in the leading coef's will become clearer when one studies ring theory, where it follows from general structural results [$\,p$ prime $\Rightarrow \Bbb Z_p$ domain $\Rightarrow$ $\,\Bbb Z_p[x]$ domain].
For part 2, factor out fractional contents, then clear denominators and apply the first part.
Remark  $ $ Note that when reduced mod $p$ the polynomial may have different leading coef, e.g. $\, A = 10x^2+ax\equiv  ax\pmod{5}.\,$ But $\,p\nmid A\,\Rightarrow\,A\not\equiv 0\,$ so its reduction has lead coef $\,a\not\equiv 0$
Comment: @Stefan4024 Yes, you can do it that way too  - which doesn't require knowledge of polynomial arithmetic $\!\pmod p$. But it greatly  obfuscates the essence of the matter, viz, that the proof boils down  to the prime divisor property persisting in the leading coef's $\!\pmod p$
Comment: How can we get that $a, b \not \equiv 0 \pmod p$? Maybe they are divisible by $p$, but some later coefficient isn't.
Comment: @Stefan4024 If not then all coefs $\equiv 0\pmod p\,$ so $\,p\mid A,\,$ contra hypothesis. Here $\,a\,$ is the highest coef not divisible by $\,p\,$ i.e. $\,a\,$ is the the *leading* coef when it is reduced mod $\,p,\,$ e.g. $\, A = 10x^2+ax+1\equiv  ax+1\pmod{5}\ $ has lead coef $\equiv a\pmod 5\ $
Comment: I mean in $f(x) = 3x^2 + 5x + 10$, $3$ divides the first coefficients, but not the last one or the second one.
Comment: Maybe you can check the update of my proof and see what I meant


Hide some of the fields of user profile of profile2 module

Question: I am using Drupal 7 profile2 module for creating user profile and Organic group module for group managemnet.
I have user status field in user profile, and there are two options(radio button) for visibility of profile field like 1. Visible in Group 2. Invisible.
Visible in Group is selected then any group member can see the user status
Invisible then no one can see the user status field
Now I want to know that is there any way to unset the profile field during viewing. Is any hook calling during user view event ?
I have also the code that checks whether user being viewed and logged in user are member of same group or not
Answer: hook_entity_view can be used all core and most contrib entities and the more specific hook_user_view can be used when the user account is used - this is, however, not the same as the user profile itself.
You should note that this wont effect fields and entities displayed by views.
Comment: @googletrop: I want to unset some of the profile fields: i mean I want solution like **unset($profile['fieldname'])** is it possible to achieve it
Comment: @mohit_rocks Yes
Comment: thanks for your reply, but this way it is not working. I mean field is still displayed
Comment: @mohit_rocks Did you inspect the variables to see where the field markup is located - you are aware that it's not the field itself but the field content you need to disable. You can also use manage display if you always want to hide the field
Comment: @googletrop: I don't want to hide the field all the time, actually it depends on the value of radio buttons.