should i normalize dependent variable for linear regression?

Question: If we want to perform a multiple linear regression on the dependent variable $Y$ by independent variables $X_1$,$X_2$, etc., should I normalize the $X_i$ variables only? Or should I also normalize the dependent variable $Y$?
If I normalize $Y$ , how will I interpret the predicted values? Won't the predicted values be in the normalized form? How should I denormalize them to get the exact values?
Also, which is the best normalization method, if my $X_i$ variables are a mixture of both continuous and categorical variables?
Comment: just to add that dont forget to standardize your feature, unles its a feature coming from one hot encoding. this will prevent you dealing with different scale probleme as Ben as in the comment
Comment: Standardization of explanatory variables is usually unnecessary in most applications of ordinary least squares regression.
Answer: Without seeing your data (especially the residuals of the final regression model) and further context, it is hard to provide you with a definitive answer.
However, when talking about regression in general, your dependent variable does not have to be normally distributed. The model's residuals on the other hand, do have to be normally distributed. Look at it this way: one of the assumptions of linear regression is that your independent variables explain the variation in the dependent variable in such a way, that the error around the model's estimated values (== the residuals) of the dependent variable is normally distributed.
Comment: How is it when $ X_1 , X_2 $ have totally different ranges like distance and temperature?


Field Widget Ajax

Question: I'm trying to add an ajax callback in a FieldWidget.
I definied my element:
<code>$element['value']['#ajax'] = [
  'callback' => [$this, 'ajaxRefreshField'],
];
</code>
Next in my callback, how do I access the form_state value filled out in the field and the element defined on the form?
<code>    public function ajaxRefreshField(array $form, FormStateInterface $form_state, Request $request) {
      // What I want to do is something like this:
      $response = new AjaxResponse();
      $element = $form->get-my-element-in-some-sort-of-way
      $element['add-a-change'] = [...];
      $response->addCommand(new ReplaceCommand('my-selector', $element));

      return $response;
    }
</code>
Comment: Do you mean `$form_state->getValue('foo');`?
Comment: Yeah, but the form_state is a tree and it is possible my field is configured for example on a Paragraph... so I then I have to fetch the element from the paragraph definied on the form... I want to find a dynamic way to do this
Comment: Or if other contrib modules have ajax calls in their FieldWidget, I would be glad to check them, but I don't know of any...
Answer: Grab the triggering element from the <code>$form_state</code> in your AJAX callback method:
<code>$triggeringElement = $form_state->getTriggeringElement();
$value = $triggeringElement['#value'];
</code>

Field Widget Ajax


How to hide some property in Right click using JS

Question: I my web application I want to Hide/ Remove some for the menus like View Source, Properties using JavaScript coding. This should available in entire webpage.
Comment: I don't want to hide complete right click menu, I just want to hide some of the property
Answer: Do not do it.
You only make your users angry but you can not stop them any way.
See also How do I disable right click on my web page?
If I can't stop you from doing it. You can only disable the whole menu:

Answer: var message="Sorry, right-click has been disabled";

function clickIE() {if (document.all) {(message);return false;}}
function clickNS(e) {
   if(document.layers||(document.getElementById&&!document.all)) {
       if (e.which==2||e.which==3) {(message);return false;}}}
       if (document.layers){
          document.captureEvents(Event.MOUSEDOWN);
          document.onmousedown=clickNS;
       }
       else{
          document.onmouseup=clickNS;
          document.oncontextmenu=clickIE;
       }
document.oncontextmenu=new Function("return false")

This is code disable the right click.


strsplit by variable separator

Question: I have some strings of data separated by " " that needs to be split into columns. Is there an easy way to split the data by every nth separator. For example, the first value in x tells you that the first 4 values in y correspond to the first trial. The second value in x tells you that the next 3 values in y correspond to the second trial, and so on.
x <- c("4 3 3", "3 3 3 2 3")
y <- c("110 88 77 66 55 44 33 22 33 44 11 22 11", "44 55 66 33 22 11 22 33 44 55 66 77 88 66 77 88")

The goal is something like this:
structure(list(session = 1:2, trial.1 = structure(1:2, .Label = c("110 88 77",
"44 55 66"), class = "factor"), trial.2 = structure(c(2L, 1L), .Label = c("33 22 11",
"66 55 44"), class = "factor"), trial.3 = structure(1:2, .Label = c("22 33 44",
"23 33 44"), class = "factor"), trial.4 = structure(c(NA, 1L), .Label = "55 66", class = "factor"),
    trial.5 = structure(c(NA, 1L), .Label = "77 88 66", class = "factor")), .Names = c("session",
"trial.1", "trial.2", "trial.3", "trial.4", "trial.5"), class = "data.frame", row.names = c(NA,
-2L))

Ideally, any extra values from y need to be dropped from the resulting data frame, and the uneven row lengths should be filled with NA's.
Comment: `strsplit(y, " ")` then use x as a selector of elements in the resultant structure, then add your own spaces back in.
Comment: Do you mean do it manually? I should have mentioned this is a simplified version of my real data.
Comment: Your structure statement seems odd to me, do you have a particular R routine that you want to run after this cleaning, if you don't I'd suggest a vastly different structure than you are suggesting.
Comment: @Seth I'm planning on reshaping the data using the reshape package after and THEN splitting individual cases by " ". Any suggestions or approaches are welcome.
Answer: This maybe useful
dumx<-strsplit(x,' ')
dumy<-strsplit(y,' ')
dumx<-lapply(dumx,function(x)(cumsum(as.numeric(x))))
dumx<-lapply(dumx,function(x){mapply(seq,c(1,x+1)[-(length(x)+1)],x,SIMPLIFY=FALSE)})
ans<-mapply(function(x,y){lapply(x,function(w,z){z[w]},z=y)},dumx,dumy)

I will leave you to convert the resulting list to dataframe :)
Comment: Any reason why this code wouldn't work when the every value in dumx is the same?
Comment: aah, I see. I should familiarize myself with mapply better

strsplit by variable separator


How to improve right hand picking/strumming technique for electric and acoustic guitar?

Question: How can I raise my picking (and strumming) to 16th notes at 160 beats per minute or higher?  I have been trying to incorporate more forearm rotational movement into my picking (imagine turning a circular door knob), rather than forearm lever or wrist, and I can perform this motion at very high speeds, but fail to do it with any sort of control when picking/strumming. The goal here is to have a relaxed picking technique that allows for great speed and control.  I can pick using my forearm at 220 BPM 16ths and above, but lack the control to then switch strings or really anything else other than just one single note.
Let's talk about what I'm doing right now.  I recently picked up the Guitar Grimoire Progressions and Chords book  (I am finding to be great--I already know theory, so it's just a good reference book so I don't have to think so much about what to practice).

There is a section of the book with simply many pages of exercise progressions to try, so right now I am trying to play through them all with a metronome with quarter notes, eighth notes, triplets, and 16th notes.
Eventually, once I have the first few pages down well, I will record myself playing these exercises so I can discover and practice applicable scales over the progressions.

I have been working on my right hand technique to play more quickly for about a few years now, probably 5-15 minutes a day, and still am quite far off (I'm at around 125BPM 16ths on a good day), so any advice is appreciated.  I am left handed, so maybe this has something to do with it, although I would like to think I can overcome this.
Comment: Left-handed,playing a LH or RH guitar? Some would say (me included) that playing a RH guitar left-handed can be better - for fretting - , but it sounds like your problem is in the strumming hand. But which one?
Answer: One of my favourite guitar players - Tuck Andress, outlines all methods of picking a excellently on his site. Be sure to read through it and try it all out. He outlines each method of holding the pick, finding the angle of picking, rotation vs up-down motion, as well as thumb-only  (ala Wes Montgomery) and pure old school classical fingerstyle technique and discusses thier pros and cons. =
https://www.tuckandpatti.com/pick-finger_tech.html
Once you settle on a proper technique that works for you, you can get speed easily. 5 - 15 minutes a day is great, but do not stay on the same exercise for too long. Keep moving on and try to start thinking about picking geometrically, optimising picking and motion while crossing strings etc.. no book is going to figure that out for you. Just got to do it yourself.

NOTE: The thing my teachers have always told me is to play at the
  speed of my thought. This means I am never in "muscular mode", where i
  am just playing without expression or musical impetus. So try to see
  speed musically, rather than mechanically, it really helps. Sometimes
  when you do this, the mechanics work themselves out magically, and
  then you can analyse them backwards and set them in stone for solid
  technique.
Comment: I actually have read the above link posted, quite a few times, and it is a good read for sure.  However, I have a lot of trouble with the Benson picking described there as it causes a lot of tension throughout my arm when I try to do it.  The forearm rotational picking as described by PebberBrown seems to help much more.  Let me see if I can find the video...
Comment: As you can see in the video it is possible to combine a very slight finger movement along with the rotation of the forearm to pick.  I like this method because it allows to keep the picking at a consistent angle.


Binary Search and Add in Java

Question: I am to make a search method more efficient and I decided to use binary search. I want to use this search to add each item line number in a word list found to and display the number of times each item is found. But my code does not seem to work...
private static void searchAndAdd(List<Word> wl, String w, int ln) {
    boolean found = false;
    Iterator<Word> wit = wl.listIterator();
    int min = 0;
    int max = wl.size()-1;

     int bsearch = binarySearch(wl, w, min, max);
    while (found && wit.hasNext()) {
        Word wd = wit.next();
        if (bsearch == -1 )
        {
            wd.addLineNumber(ln);
        }
    }
    if (!found)
        wl.add(0, new Word(w, ln));
}
 private static int binarySearch(List<Word> arr, String w, int min, int max) {
     if (min < max) {
             return NOT_FOUND;
     }
     int mid = (min + max) /2;
     Word w2 = arr.get(mid);
     if (w.compareTo(w2.toString())  > 0) {
             return binarySearch(arr, w, mid + 1, min);
     } else if (w.compareTo(w2.toString()) < 0) {
             return binarySearch(arr, w, min, mid - 1);
     } else {
             return mid;
     }

I always get this error:
in thread "main" java.lang.NullPointerException
at Concordance.binarySearch(Concordance.java:131)
at Concordance.searchAndAdd(Concordance.java:114)
at Concordance.main(Concordance.java:51)

Comment: it keeps given me this errorException in thread "main" java.lang.NullPointerException
 at Concordance.binarySearch(Concordance.java:131)
 at Concordance.searchAndAdd(Concordance.java:114)
 at Concordance.main(Concordance.java:51)
Comment: does not seem to add the line.
Comment: it will perform better if it isn't recursive.
Comment: We don't have your line numbers. Please edit your post to show where the NPE is happening.
Comment: You also really need to paste the code that you're actually using into this, not editing it along the way.  Reasons I think this isn't your real code: the "found" variable is never not false, so you don't get into that loop.  Also, the whole min < max thing means that you'd never get far enough into the binarySearch method to get a NPE.
Answer: Not sure this is your only problem, but I suspect that your binary search doesn't ever search for anything because of the lines:
if (min < max) {
         return NOT_FOUND;
 }

Which is always the case for a non-empty list.
Comment: You might want to consider writing some unit tests on your binary search.  You also have a bug in this line:return binarySearch(arr, w, mid + 1, min);
Comment: Use a debugger, put a breakpoint at that line (the one that compares min and max), and look at the values.

Binary Search and Add in Java


TypeScript JSDoc annotations for a function that adds an object property

Question: I'm working in a project with ample JSDoc comments and I want to start taking advantage of tsc and JSDoc style annotations.
Given a function that adds a property to an Object like so:
/**
 * @param {object} obj
 * @param {string} n
 * @return void
 */
function addName(obj, n) {
    obj.name = n;
}

let thing = {size: "medium"};
addName(thing, "product");
console.log(thing.name);

Is there a way to declare that the object will be mutated with an additional property?
Comment: I don't think that that is posible. Because is not posible in typescript. Or It is?
Answer: Going down another track, given the current signature of addName returns void, you could make it always return boolean and turn it into a type predicate. Then anything guarded by the assignment's boolean return value would be properly typed with the extra known parameter
function addName(obj:object, n:string) : obj is typeof obj & {name:string}{
    (obj as any).name = n;
    return true
}

let thing = {size: "medium"};
if(addName(thing, "product")){
  console.log(thing.name);
}

Answer: Does this approach fulfil the need of your real case? It superficially resolves the issue you describe, but perhaps you can't change the signatures of anything to adopt this more 'immutable' pattern.
function addName<O extends object, V>(obj:O, val:V): O & {name:V} {
    return {
      ...obj,
      name:val
    }
}

let thing = {size: "medium"};
let newThing = addName(thing, "product");
console.log(newThing.name);


Attainable correlations for lognormal random variables

Question: Consider the lognormal random variables $X_1$ and $X_2$ with $\log(X_1)\sim \mathcal{N}(0,1)$, and $\log(X_2)\sim \mathcal{N}(0,\sigma^2)$.
I'm trying to calculate $\rho_{\max}$ and $\rho_{\min}$ for $\rho (X_1,X_2)$. One step in the given solution I have is:
$\rho_{\max}=\rho (\exp(Z),\exp(\sigma Z))$ and
$\rho_{\min}=\rho (\exp(Z),\exp(-\sigma Z))$,
but they've made some references to comonotonicity and countercomonotonicity. I was hoping someone help me understand how they're relevant. (I know how to get this from the general expression but want to know specifically what the comonotonicity parts were saying.)
Comment: Who are "they"?
Answer: I'll start by providing the definition of comonotonicity and countermonotonicity. Then, I'll mention why this is relevant to compute the minimum and maximum possible correlation coefficient between two random variables. And finally, I'll compute these bounds for the lognormal random variables $X_1$ and $X_2$.
Comonotonicity and countermonotonicity
The random variables $X_1, \ldots, X_d$ are said to be comonotonic if their copula is the Fréchet upper bound $M(u_1, \ldots, u_d) = \min(u_1, \ldots, u_d)$, which is the strongest type of "positive" dependence.
It can be shown that $X_1, \ldots, X_d$ are comonotonic if and only if
$$
(X_1, \ldots, X_d) \stackrel{\mathrm{d}}{=} (h_1(Z), \ldots, h_d(Z)),
$$
where $Z$ is some random variable, $h_1, \ldots, h_d$ are increasing functions, and
$\stackrel{\mathrm{d}}{=}$ denotes equality in distribution.
So, comonotonic random variables are only functions of a single random variable.
The random variables $X_1, X_2$ are said to be countermonotonic if their copula is the Fréchet lower bound $W(u_1, u_2) = \max(0, u_1 + u_2 - 1)$, which is the strongest type of "negative" dependence in the bivariate case. Countermonotonocity doesn't generalize to higher dimensions.
It can be shown that $X_1, X_2$ are countermonotonic if and only if
$$
(X_1, X_2) \stackrel{\mathrm{d}}{=} (h_1(Z), h_2(Z)),
$$
where $Z$ is some random variable, and $h_1$ and $h_2$ are respectively an increasing and a decreasing function, or vice versa.
Attainable correlation
Let $X_1$ and $X_2$ be two random variables with strictly positive and finite variances, and let $\rho_{\min}$ and $\rho_{\max}$ denote the minimum and maximum possible correlation coefficient between $X_1$ and $X_2$.
Then, it can be shown that

${\rm \rho}(X_1, X_2) = \rho_{\min}$ if and only if $X_1$ and $X_2$ are countermonotonic;
${\rm \rho}(X_1, X_2) = \rho_{\max}$ if and only if $X_1$ and $X_2$ are comonotonic.

Attainable correlation for lognormal random variables
To obtain $\rho_{\max}$ we use the fact that the maximum correlation is attained if and only if $X_1$ and $X_2$ are comonotonic. The random variables $X_1 = e^{Z}$ and $X_2 = e^{\sigma Z}$ where $Z \sim {\rm N} (0, 1)$ are comonotonic since the exponential function is a (strictly) increasing function, and thus $\rho_{\max} = {\rm corr} \left (e^Z, e^{\sigma Z} \right )$.
Using the properties of lognormal random variables, we have
${\rm E}(e^Z) = e^{1/2}$,
${\rm E}(e^{\sigma Z}) = e^{\sigma^2/2}$,
${\rm var}(e^Z) = e(e - 1)$,
${\rm var}(e^{\sigma Z}) = e^{\sigma^2}(e^{\sigma^2} - 1)$, and the covariance is
\begin{align}
{\rm cov}\left (e^Z, e^{\sigma Z}\right )
 &= {\rm E}\left (e^{(\sigma + 1) Z}\right ) - {\rm E}\left (e^{\sigma Z}\right ){\rm E}\left (e^Z\right ) \\
 &= e^{(\sigma + 1)^2/2} - e^{(\sigma^2 + 1)/2} \\
 &= e^{(\sigma^2 + 1)/2} ( e^{\sigma} -1 ).
\end{align}
Thus,
\begin{align}
\rho_{\max}
 & = \frac{ e^{(\sigma^2 + 1)/2} ( e^{\sigma} -1 ) }
          { \sqrt{ e(e - 1) e^{\sigma^2}(e^{\sigma^2} - 1) } } \\
 & = \frac{ ( e^{\sigma} -1 ) }
          { \sqrt{ (e - 1) (e^{\sigma^2} - 1) } }.
\end{align}
Similar computations with $X_2 = e^{-\sigma Z}$ yield
\begin{align}
\rho_{\min}
 & = \frac{ ( e^{-\sigma} -1 ) }
          { \sqrt{ (e - 1) (e^{\sigma^2} - 1) } }.
\end{align}
Comment
This example shows that it is possible to have a pair of random variable that are strongly dependent — comonotonicity and countermonotonicity are the strongest kind of dependence — but that have a very low correlation.
The following chart shows these bounds as a function of $\sigma$.

This is the R code I used to produce the above chart.
<code>curve((exp(x)-1)/sqrt((exp(1) - 1)*(exp(x^2) - 1)), from = 0, to = 5,
      ylim = c(-1, 1), col = 2, lwd = 2, main = "Lognormal attainable correlation",
      xlab = expression(sigma), ylab = "Correlation", cex.lab = 1.2)
curve((exp(-x)-1)/sqrt((exp(1) - 1)*(exp(x^2) - 1)), col = 4, lwd = 2, add = TRUE)
legend(x = "bottomright", col = c(2, 4), lwd = c(2, 2), inset = 0.02,
       legend = c("Correlation upper bound", "Correlation lower bound"))
abline(h = 0, lty = 2)
</code>
Comment: (+6) Nice thorough exposition and well illustrated.  It is interesting that attempts to confirm your chart through simulation will be doomed when $\sigma$ is much larger than $3$ because the *sample* correlation coefficient is extremely variable (due to the chance of getting one extremely high value of $X_2$, which will have high leverage). That places a higher value than usual on a solid theoretical analysis.
Comment: This exposition is an adaptation of Example 2.1 (pg. 23) of M. Denuit and J. Dhaene (2003), [Simple characterizations of comonotonicity and countermonotonicity by extremal correlations](http://papers.ssrn.com/sol3/papers.cfm?abstract_id=886319), *Belgian Actuarial Bulletin*, vol. 3, 22-27.
Comment: @cardinal I wasn't aware of this article, thanks. Other potential references include http://ebooks.cambridge.org/chapter.jsf?bid=CBO9780511615337&cid=CBO9780511615337A013 or McNeil, A. J., Frey, R. and Embrechts, P. (2005). Quantitative Risk Management: Concepts, Techniques and Tools. Princeton: Princeton University Press.
Comment: The example goes back to at least R. D. De Veaux (1976), [Tight upper and lower bounds for correlation of bivariate distributions arising in air pollution models](http://statistics.stanford.edu/~ckirby/techreports/SIMS/SIMS%2005.pdf), Tech. Report 5, Dept. of Statistics, Stanford University. See Section 3 starting on page 6. The underlying tools were known to Hoeffding.
Comment: @QuantIbex in your proof there's something unclear to me. You first claim that $X_1$ and $X_2$ are comonotonic if and only if their joint distribution is equal to $(h_1(Z), h_2(Z))$, for $h_1, h_2$ increasing, etc., but when you apply this result to the lognormal random variables, you say that this implies that the random variables themselves are such that $X_1=e^Z$ and $X_1=e^{\sigma Z}$, i.e., it seems you apply the claim to the random variables themselves, not just their distributions. How is it?
Comment: @RandomGuy The random variables $X_1$ and $X_2$ are defined as functions of a common random variable $Z$, which implies that they are comonotonic (not the other way around).
Comment: @QuantIbex Yes, now it makes perfect sense. The reason why I asked this question is because you write, after the statement of the theorem about comonotonicity, that "comonotonic random variables are only functions of a single random variable" which I find ambiguous since the result only holds for distribution functions, not random variables. This confused me in the construction of the two $X_1$, $X_2$.


CSS para diferentes navegadores

Question: Estou montando um label + input text personalizado.
O problema é que cada browser interpreta o código de modo diferente.
A minha intenção final é fazer com que o border-bottom aparente ser apenas uma única linha.
No Chrome e no Opera fica correto.
Já no IE e no Firefox é totalmente visível o "erro" que ocorre.
Não estou utilizando css reset, e nem mesmo a tag form.
A princípio, creio que a solução seja elaborar diferentes CSS para cada navegador, mas caso tenha outra solução para este problema, será muito bem vindo!
Segue o código CSS e HTML:

.style-select{
    margin-bottom: 15px;
}

.style-select select {
background: transparent;
-webkit-appearance: none;
width: 213px;
font: 13px;
color: #444444;
height: 28px;
padding-right:55px;
padding-left: 8px;

border: none;

}

.style-select {
width: 183px;
height: 21px;
overflow: hidden;
background:url(arrow.jpg) no-repeat right;

}

.style-select select {
    padding-right:0px;
    text-align:left;
    line-height:21px;
    height:auto;
    vertical-align:top !important;

}

.style-select {
    border-bottom: 1px solid #C9D3DD;
}

/*Formatação label*/
.label-formulario{
    font: 12px HEINEKENCore;
    color: #444444;
    padding-bottom: 6px;
    padding-right: 30px;
    padding-left: 10px;

    border-bottom: 1px solid #C9D3DD;
    border-right: 1px solid #C9D3DD;

    float: left;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="estilo.css" >

    Pilar T&D

       <select>
            <option>lorem</option>
            <option>Ipsum</option>
            <option>Dolor</option>
        </select>

    Treinamento <select>
        <option>lorem</option>
        <option>Ipsum</option>
        <option>Dolor</option>
    </select>

Comment: @MarcoAntonioQuintal A IDE não tem importância, a questão é o navegador. Para criar uma página nem é preciso utilizar IDEs, bloco de notas + um navegador e *tcharam*!
Comment: Eu sei mas cada navegador implementa alguns csss próprios e existem ferramentas nas IDEs que ajudam a achar erros e incompatibilidades no css. Ex.: o seu css tem padding-right:0px; e quando o valor é zero não devemos colocar unidade de medida. Eu testei seu codigo no firefox e chrome e funcionou.
Comment: Qual IDE você usa? Visual Studio?
Comment: Marco, em relação a IDE... Elas apontam o que está incorreto no CSS ou a compatibilidade com cada navegador?

E está funcionando sim, mas a questão é sobre o design que não fica igual nos navegadores.

E estou utilizando o Brackets, nenhuma IDE.
Answer: Não tem necessidade de criar um CSS para cada navegador
Primeiro de tudo: Defina box-sizing:border-box em um seletor universal para não ter surpresas no tamanho dos elementos. Veja neste artigo o porque para entender melhor.
Você está aplicando border-bottom em dois elementos inline. Pode ser que um fique mais acima que o outro (como no seu caso) e a linha não apareça como deveria. E então, você vai precisar trabalhar com números mágicos no padding e margin para ajustar corretamente.
Uma solução melhor é envolver esses dois elementos dentro de um elemento pai, no qual será aplicado esse border-bottom. O esquema ficaria como na imagem a seguir:

*{box-sizing:border-box;margin:0;padding:0}

.wrapper {
    border-bottom: 1px solid #ccc; /* Aqui é aplicada a borda inferior, no elemento pai */
    height: 40px;
    position: relative;
    width: 300px
}

.wrapper p,
.wrapper select {
    position: absolute;
    top: 0; bottom 0
}

.wrapper p {
    left: 0;
    line-height: 40px;
    text-align:center;
    width: 30%
}

.wrapper select {
    border: none;
    height: 100%;
    right: 0;
    width: 70%
}

Pilar T&D

    <select>
        <option>lorem</option>
        <option>Ipsum</option>
        <option>Dolor</option>
    </select>

Comment: Obrigado!
Ajudou aqui no meu trabalho.
Gostei também da utilização dos positions.
Answer: Cara acho que pode te ajudar, inserir no seu css um código para resetar os elementos dos navegadores assim que subir sua página, existem alguns modelos, dentre um deles o seguinte abaixo:
fonte reset css:http://www.nacaolivre.com.br/css/css-padrao-entre-navegadores-web/
/*
===========================================================
// Zera as configurações padrões dos elementos html.
===========================================================
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
    margin: 0px;
    padding: 0px;
    border: 0px;
    outline: 0px;
    font-weight: inherit;
    font-style: inherit;
    font-size: 100%;
    font-family: inherit;
    vertical-align: baseline;
}

:focus {
    outline: 0px;
}

/* --------------------------------------------------------------------------------------------- */
/* Configuração básica padrão para os elementos HTML entre os navegadores web. */
/* --------------------------------------------------------------------------------------------- */
h1 {
    font-size: 18px;
}

h2 {
    font-size: 16px;
}

h3 {
    font-size: 14px;
}

h1, h2, h3 {
    margin: 16px 0;
}

h1, h2, h3, h4, h5, h6, strong {
    font-weight: bold;
}

abbr, acronym {
    border-bottom: 1px dotted #000;
    cursor: help;
}

em {
    font-style: italic;
}

blockquote, ul, ol, dl {
    margin: 16px;
}

ol, ul, dl {
    margin-left: 32px;
}

ol li {
    list-style: decimal outside;
}

ul li {
    list-style: disc outside;
}

dl dd {
    margin-left: 16px;
}

th, td {
    border: 1px solid #000;
    padding: 8px;
}

th {
    font-weight: bold;
    text-align: center;
}

caption {
    margin-bottom: 8px;
    text-align:center;
}

p, fieldset, table {
    margin-bottom: 16px;
}

Comment: Eu [fiz um teste no JSFiddle](http://jsfiddle.net/rnxn/g3nmhk3q/) e mesmo com o reset não acertou as linhas. Nem mesmo usando `box-sizing:border-box` e `-webkit-box-sizing:border-box`.

CSS para diferentes navegadores


Custom view as a singleton in Android

Question: I have a custom view that is extended from RelativeLayout.
I wanted to try to make this custom view as a singleton.
I have this code:
private static CameraView sCameraView;
public static synchronized CameraView getInstance(Context context) {
    if (sCameraView == null) {
        sCameraView = new CameraView(context);
    }
    return sCameraView;
}

And tried to use this from a fragment as:
private CameraView mCameraView = CameraView.getInstance(getActivity().getApplicationContext());

mCameraView = (CameraView) mView.findViewById(R.id.camera_preview);

I'm getting a NullPointException from this code.
Then also an InflateException when I switch things around a little bit.
How would I approach to access the static instance from the custom view and assign it to a variable? because doing this:
CameraView.getInstance(getActivity().getApplicationContext()) = (CameraView) mView.findViewById(R.id.camera_preview);

isn't allowed.
Any help will be very appreciated.
Comment: "I wanted to try to make this custom view as a singleton" -- you will leak memory (making the singleton dangerous), and the view will not work in other activities (making the singleton useless). I strongly suggest that you come up with another plan. Beyond that, use LogCat to examine the Java stack trace associated with your crashes: https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this If you do not understand a stack trace, edit your question and post it.
Comment: Alright, Thanks for your answer #CommonsWare. I knew that singleton wasn't a good choice but I was experimenting about having a singleton view in android.
Answer: private static CameraView sCameraView; is a static reference, but it's not desirable. Read this
You should avoid declaring UI elements as static. Hope this solves your problem.

Custom view as a singleton in Android


how to use only 1 return in this recursive method

Question: I'm finishing up the easy portion project and my professor specified that he only wants methods with at maximum 1 return. I can't seem to figure out how to make this work correctly with only 1 return though. For context, I am finding how many nodes in a tree have exactly 1 non-null children.
// How many nodes have exactly 1 non-null children
    public int stickCt() {
        return stickCt(root);
    }
    private int stickCt(StringNode t) {
        int count = 0;
        if (t == null)
            return 0;

        else if ((t.getLeft() == null && t.getRight() != null) || (t.getLeft() != null & t.getRight() == null))
            count++;

        count = count + stickCt(t.getLeft()) + stickCt(t.getRight());
        return count;

    }

Answer: Something like this:
private int stickCt(StringNode t) {
    int count = 0;
    if (t != null) {
        if ((t.getLeft() == null && t.getRight() != null) || (t.getLeft() != null & t.getRight() == null))
            count++;
        count += stickCt(t.getLeft()) + stickCt(t.getRight());
    }
    return count;
}

However, in this case I find your formulation with the 2 returns easier to understand.
Answer: Instead using recursive algorithm you can use BFS of DFS algorithm.
Here is an example or BSF approach
public int stickCt(StringNode root){
        int count = 0;

        Queue<StringNode > queue = new LinkedList<StringNode >();
        queue.add(root);

        while (!queue.isEmpty()){
            StringNode tempNode = queue.poll();

            if (tempNode != null && (tempNode.getLeft() == null && tempNode.getRight() != null) || (tempNode.getLeft() != null && tempNode.getRight() == null)){
                count++;
            }

            /*Enqueue left child */
            if (tempNode.getLeft()!= null) {
                queue.add(tempNode.getLeft());
            }

            /*Enqueue right child */
            if (tempNode.getRight()!= null) {
                queue.add(tempNode.getRight());
            }
        }

        return count;
    }


"Authored by" field to be automatically filled

Question: On every creation of a node or edit of a node I need the "Authored by" field to be automatically populated with the username of anyone saving changes.
any ideas how I can do that?
Thanks.
Comment: Please elaborate, do you really want the author to change every time a node is edited? If so: do you need to keep the name of the original author, or is it OK if the name of the last editor overwrites the original author?
Comment: Sorry that wasn't clear,
yes I want the author to change every time a node is edited.
no problem if it overwrites the original author.
Comment: Look like this has been asked and answered http://stackoverflow.com/questions/4936968/change-node-author-automatically-drupal-7, http://drupal.stackexchange.com/questions/43936/change-node-author-on-node-save-with-rules.
Comment: Thanks for the Links Adam,
would be quite useful if there is a solution in detail, I am very new Drupal.
Answer: Personally I think that a module like Rules (powerful and awesome as it is) is overkill for something relatively simple as this.
Looking at node_form(), I see that the author is set by populating the author field with the username. I would create a custom module which implements hook_form_BASE_FORM_ID_alter, and set the default value of the author name field to the name of the current user. That would look something like this (disclaimer: untested code!).
<?php

function MODULENAME_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Always set the username to the current user. An empty string means anonymous.
  global $user;
  $form['author']['name']['#default_value'] = !empty($user->name) ? $user->name : '';
}

An advantage of this solution is that the field is populated in advance with a default value, allowing user with sufficient permissions (eg. administrators) to override the author as they always can. It would be harder to do that in a rules-based approach which only kicks in after the form has been submitted.

update:
The topic starter mentions in another answer that he ended up with the following code:
function module_name_form_alter(&$form, &$form_state, $form_id) {
  // Always set the username to the current user. An empty string means anonymous.
  global $user;
  if ($form_id == 'content_type_node_form') {
    $form['author']['name']['#default_value'] = $user->name;
  }
}

Some feedback on this code:

Of course, the if-statement makes sense if you only need this behavior in certain cases. You could even place the global $user; inside the if.
I would recommend that you keep the !empty($user->name) ? $user->name : '' part, instead of simply using $user->name. It may be an edge case, but as you can see in drupal_anonymous_user, the global $user object does not necessarily contain a 'name' property. If, at some point in the future, this form would become available for anonymous users, they will end up with php notices on their screen.
Answer: I'd use Rules to do this. You need to create a rule to respond to a node being updated, then add an action which sets the author value from the current user.
Answer: thanks a bunch, It worked well and I simply did this(just a few changes from what you've written)
function module_name_form_alter(&$form, &$form_state, $form_id) {
  // Always set the username to the current user. An empty string means anonymous.
  global $user;
  if($form_id=='content_type_node_form'){
    $form['author']['name']['#default_value'] = $user->name;
  }
}

Answer: If we want to implement this in any node form irrespective of Content type then we can use preg_match.
function change_author_form_alter (&$form, &$form_state, $form_id)
{

global $user;
// for all type of content node forms we can use preg_match
if (preg_match('/.*_node_form/',$form_id)) {
$form['author']['name']['#default_value'] = $user->name ;
}
}

Answer: This should just happen when created, if Author and Date information are ticked in admin/structure/types/manage/[your_content_type], under display settings.
If you want something else, you can use the token module and use a token as default value ; again in the content type settings.
If you want it updated with every save, you have to use hook_node_update() in a custom module, and set $node->uid to current user's ID (global $user; $user->uid).
Comment: I don't think this answers the question; the question says "populated with the username of anyone saving changes" By default, Drupal only sets the author when a node is created, but it doesn't update the author when the node is edited.
Comment: Hi rémy,
Thanks for the reply, but that is  done. My question is, how to automatically populate the username in the "Authored by field"


Mapped Network Drive with SMB1 and Windows 10

Question: I have a Windows Server 2003 machine (I know, but it's out of my control) with a bunch of network shares on it. I have a laptop that has just been rebuilt with Windows 10 2004. I've enabled CIFS/SMB1 in the Windows Features dialogue and I can browse to the network shares OK using the UNC in File Explorer and via the Run prompt.
However, as soon as I map one of these shares as a network drive File Explorer fails to connect. If I click on one of the drives it just seems to hang Explorer and eventually times out (if I don't force restart Explorer before that). Prior to the rebuild the laptop connected to the mapped drives fine even after being upgraded to Windows 10 2004, as do other laptops.
What am I missing that allows other laptops to connect to these drives? Are there any other settings that I should be using to resolve this?
Comment: Did I get downvoted because the question isn't clear or because it relates to Windows 2003?
Answer: I wrestled with this one today. The main points were:

Enable SMB1 support (run -> optionalfeatures -> SMB 1.0/CIFS File sharing support -> Client) and disable the Automatic removal feature.

Re-enable two services: "Function discovery resource publication" and "Function discovery Provider Host"

Create the following registry key:
HKEY_CURRENT_USER\Network\(DRIVE_LETTER_HERE)\ProviderFlagstype REG_DWORD and value 1

My starting point was an embedded CNC machining tool that runs 2k server and Windows 10 2004, explorer in Windows would completely freeze after attempting to connect the server, according the user it used to work before.
I tip my hat at Samuli for pointing me to the 3rd step that finally solved the whole thing.
Edit: Be sure to add the registry value to every mapped drive in case you have more than one.
Answer: I have the same problem with Windows 10 2004.
Try to restart Workstation service. It takes about 5-10 mins for me. (But after reboot it doesnt work too.) so after the Workstation service restart delete your mapped drive with "net use drive /delete"
and create a script which will connect your mapped drive, and put it into "startup" folder:
net use /persistent:no

net use yourdrive uncpath /persistent:no
Answer: I've had some success mapping the network shares using their IP address instead of using the server name. It only fails twice a month instead of every other day. It's not a fix but at least people can work for a few days without calling helpdesk.
If Windows lets you, you should rollback to 1909 or 1903 while you get rid of your Windows Server 2003 machines.
Of course, upgrading Windows Server 2003 to a version that's not end of life is the proper way to deal with this issue,
Comment: Thanks, I will give it a go. I'm not responsible for the presence or removal of the 2003 boxes.
Comment: @Darren How did it go?
Comment: same problem unfortunately. Haven't tried it since so no idea if it's been fixed in a recent update.


Why the href attributes of a tags are printed to screen?

Question:
Possible Duplicate:
Hyperlinks showing URL with Blueprint

DOM:

        Home
        Contact List
        Event Album

Looks weird, why the href are printed?
    /* Menu */
#menu{
 width:400px;
 height:50px;
 margin:10px auto;
 border:solid 1px #313131;
 background:#ffffff;
 overflow:hidden;
}
/*------ MENU ------*/

    #menu ul{
     list-style:none;
    }

    #menu ul a{
     text-decoration:none;

    }

    #menu ul a:hover{
     color:#7878ff;

    }

Comment: This is something blueprint specific, I remember seeing this in some other question.
Answer: Make sure the media attribute of your link item is set to "print"
<link rel="stylesheet" href="App_Themes/Default/print.css" type="text/css" media="print" />

The CSS that is responsible for this looks something like:
a:link:after, a:visited:after {content:" (" attr(href) ")";font-size:90%;}

Answer: It looks like you may be grabbing the print.css for the screen.  Make sure you have your media types set properly.


change Your search yielded no results

Question: I would like to set a custom message for my search using the core Drupal search module. Right now it says:

Your search yielded no results Check if your spelling is
  correct. Remove quotes around phrases to search for each word
  individually. bike shed will often show more results than "bike
  shed". Consider loosening your query with OR. bike OR shed will
  often show more results than bike shed.
Answer: The core Drupal search module uses several template files that dictate both how search results are displayed, and what's displayed when there are no search results.
If you're already using a custom theme on your Drupal site, the best way to customize those would be to copy and paste the entire 'search-results.tpl.php' file from the search/ module folder into your own custom theme subfolder.
Open that file up for editing and you'll see the following at the bottom:
<?php else : ?>

<?php print t('Your search yielded no results');?>

  <?php print search_help('search#noresults', drupal_help_arg()); ?>
<?php endif; ?>

This is what's displayed if search results are not found (thus the 'else')...  Modify the text to be anything you want here.  The second line, which calls the search_help() function is the one that displays the search suggestions.  Feel free to replace that too....
And as always, before you can see your changes, you'll probably need to clear cache!
Let us know if this works for you!

change Your search yielded no results


Conditional expectation given an independent and dependent variable

Question: Given $X,Y,Z$ with $X$ and $Z$ independent, is $\mathbb{E}[X\mid Y,Z] = \mathbb{E}[X \mid Y]$?
This has come up a few times when working on a separate problem - I don't think it is true (memories from a course) but haven't been able to put together a counterexample. Intuitively, it seems that conditioning on $Z$ should influence my understanding of how $Y$ and $X$ interact, which would make the equality false.  Since I didn't find a similar question on the site I thought it would be useful for others.
Answer: No. Suppose that $X$ and $Z$ are independent with
$$X \sim U([-1,1])\\
Z \sim U([-1,1])\\
Y = X + Z$$
Then: $\ \ \ \operatorname{E}[X\ |\ Y=0] = 0$
But: $\ \ \ \  \ \operatorname{E}[X\ |\ Y=0,\ Z=1] = -1$
This phenomenon, where two independent variables become dependent in the presence of a third, is known as conditional dependence


Can debug app on device but cannot profile: the app must be signed with a development identity

Question: I have custom schemes such as DebugStaging that are signed with a development identity.
I use these schemes to run the app on my phone from Xcode on debug. However, any attempt to profile using these schemes results in
Target failed to run: Permission to debug [app name] was denied. The app must be signed with a development identity (e.g. iOS Developer)
What in the heck is going on and how do I rid Xcode of this evil??
Edit: We long ago deleted the Debug scheme to use more verbose scheme names.
Comment: possible duplicate of [Can't launch my app in Instruments: At least one target failed to launch](http://stackoverflow.com/questions/18905450/cant-launch-my-app-in-instruments-at-least-one-target-failed-to-launch)
Answer: Go to the scheme for your target, Product -> Scheme -> Edit Scheme, then select 'Profile' from the left menu and set the Build Configuration to Debug.
Comment: I deleted derived data and everything started working :shrug:. You'll have to take my word that no `Debug` option exists since this is a private codebase.
Comment: There is no `Debug` option. `DebugStaging` is an option. Interestingly I can profile on our `DebugProduction` scheme with the `DebugProduction` build configuration. I'll try to investigate more into what the difference is here since there must be a deeper underlying reason the profiler works on one but not the other.
Comment: What version of Xcode are you using? Can you provide a screenshot?
Comment: I am using Xcode 6 and there us Debug option in Profile section.
Comment: Ya, but we removed that option in order to include more verbose options for our schemes.
Answer: Deleting derived data worked.
In my case, no Debug build configuration existed because it was deleted and I am using completely custom configurations.


How do I format date from NSFetchedResultsSectionInfo?

Question: I want to just be able to format my dates in the section titles of my table cleanly. Here's my code:
<code>- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSDate *date = [dateFormatter dateFromString:sectionInfo.name];
NSString *formattedDate = [dateFormatter stringFromDate:date];
NSLog(@"%@", formattedDate);
return formattedDate;
}
</code>
With this code, no section titles come up because date is null. For some reason dateFromString is not able to turn the string, sectionInfo.name into an NSDate. Any suggestions?
Comment: how exactly is your string `date` formatted?
Comment: +1 to Sebastian's question. Just I guess he meant the format of section's caption string - sectionInfo.name. If coredata read everything properly, then the only thing which can cause the error here is mismatch of formats.
Comment: hey, the string that shows up on my section title is in the form:2012-03-12 07:00:00 +0000 I'm trying to convert this to March 3, 2012
Comment: Can you do NSLog(@"%@", sectionInfo.name); and show the output?
Answer: Taking into account your comment, where you point out that the format of your date title is 2012-03-12 07:00:00 +0000, you can be sure that the problem is in formatting.
NSDateFormatterMediumStyle has the format "Nov 23, 1937" - and this is your mismatch :)
You have to use something like:
<code>[dateFormatter setDateStyle:@"yyyy-dd-MM HH:mm:ss ZZZ"];
</code>
to made an NSDate from the string of a format you have. Should work then.
If you need to return an NSString with NSDateFormatterMediumStyle format, then only after you got NSDate you can apply it to your dateFormatter object as you did:
<code>[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
</code>
and then use this dateFormatter to get the string from the date you got:
<code>NSString *formattedDate = [dateFormatter stringFromDate:date];
</code>
Comment: thanks makaron! I made a few edits, but the key insight was that in order to take a string and turn it into a date, I have to setDateFormat to the initial format of the string, not the format I want. then, it is converted into a date where i can manipulate its format.
Answer: In view did load I setup my date parser and date formatter
<code>@property(nonatomic, strong) NSDateFormatter *dateParser;
@property(nonatomic, strong) NSDateFormatter *dateFormatter;
@property(nonatomic, strong) NSDateFormatter *timeFormatter;

- (void)viewDidLoad {
    [super viewDidLoad];

    self.dateParser = [[NSDateFormatter alloc] init];
    self.dateFormatter = [[NSDateFormatter alloc] init];

    [self.dateParser setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
    [self.dateFormatter setDateStyle:NSDateFormatterFullStyle];
    ...
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
    NSDate *date = [self.dateParser dateFromString:sectionInfo.name];
    return [self.dateFormatter stringFromDate:date];
}
</code>


Find out which nodes use a specific filter

Question: How could I find out which nodes actually use a specific filter?
My nodes use an input format that has the Bbcode filter enabled. Now I need to know which (of the several thousand) nodes use BB code, to decide if I still need this filter (in which case I'd switch to Extensible BBCode, and for that I'd like to have a list of nodes to test if everything works correctly).
Comment: I think you can filter a view results by body format. Did you check it?
Comment: @drupality: I guess you mean the [same as suggested by Vishal Patil](http://drupal.stackexchange.com/a/150932/9223)? As I wrote in the comments to this answer, I can't get it to work (I guess it's because this Views filter is for input formats, not filters of input formats)?
Answer: Create a view for nodes & add Content: Body (body:format) in Filter Criteria, then set the text format value as bbcode.
Comment: I can't get it to work. I used "Is equal to" and the value "bbcode", but get 0 results (although I know some nodes that use it in the body). I tested it also with "Starts with" and the value "b", but nothing. -- Is this `…:format` filter criteria really for *filters* and not just for *text formats* (like "Filtered HTML")? **Edit:** I created a new format and using its name in "Is equal to" works, so I guess this filter is only for formats, not filters?
Comment: It is text format filter, which can be used in filter criteria of views. Please check if you have limited the view by content type or any other filters.
Comment: I checked it (not limited by content type, no other filters). Just to be sure that we use the same terminology: I have an input format (aka. text format) that is named "Filtered HTML". And this has several filters enabled: "Limit allowed HTML tags", "Convert BBCode to HTML", and "Convert line breaks into HTML". All my nodes use this input format, but not every filter of this format is used in all nodes. -- And when I search for "Contains all words" → "Filtered HTML" than it finds the nodes (i.e., the format, not the filter).


Chance of... consecutive events

Question: I'm calculating probabilities for a game but I am uncertain about my calculations.
In the game, you're able to draw cards ($10$ cards in a row each time). Each time you draw a card you have a certain % chance to draw a card, like:
$2$ of spades: $12\%$, $4$ of spades: $14\%$ and so on...
You can draw the same card over and over, so we can consider infinite cards, drawing a 2 of spades three times in a row will not change any probability (still 12%).
I'm trying to know what are my chances to get at least one of each during 10 draws.
This is what I think it would be:
$1-((1-$probability$)$^$10)$
Why I did that:
"1-probability" equals the chance of NOT obtaining the card.
"^$10$" for $10$ consecutive draws
That would give me the chances of not obtaining the card on any of those 10 draws.
So, $1$ minus that value would give me the probability of obtaining at least one of the card...
Am I right, or did I miss something?
Thanks!
Comment: What do you mean by "...get at least one of **each** during 10 draws."
Comment: I mean i'm calculating it for all of them, but not at the same time.
Answer: Your ^$10$ would only work if there were two cards you were dealing with. To calculate the probability, you need to calculate the chance of all the remaining cards. I am assuming the total possible types cards are 10, as your "one of each" implies. If we let $P_{ace},P_{2},...P_{10}$ be the probabilities of drawing the respective card, we can derive the following:
Probability of getting a specific card at a draw (of ten cards): $$P=1-(1-P_{card})^{10}$$
Probability of getting all 10 card types at a draw in a specific order (of ten cards): $$P=P_{ace}\cdot P_{2}\cdot P_{3}\cdot...\cdot P_{10}$$
Probability of getting all 10 card types at a draw in any order (of ten cards):
$$P=(P_{ace}\cdot P_{2}\cdot P_{3}\cdot...\cdot P_{10})\cdot10!$$
The $10!$ (or $10⋅9⋅8⋅...⋅2⋅1$) represents the $3,628,800$ rearrangements the $10$ unique cards you draw can be in.
Hope this helps!
Comment: Yes, i see...
Thanks, it did help!

Chance of... consecutive events


What is the name of the default articulation?

Question: Is there a term for the "default" articulation that is played when no articulation symbols are present? When the note is played for nearly its full duration value, but with just a tiny rest to separate it from the next note.
Comment: The middle is not notated  - same for dynamic as discussed in [this question](https://music.stackexchange.com/q/45772/2600) -, therefore the reason to have a name for it is diminished.
Comment: In the pipe organ world this is called "ordinary touch." Basically non-legato, neither legato or notably detached, just a slight articulation between notes, such as you would get from sliding one finger from one key to the next on a mechanical (tracker) action organ. That sound is very different from the default articulation on piano and even more different from what would be standard for a singer or clarinettist.
Comment: In most cases, "no special notation" means "do what you would normally do" for music like this. Composers who wrote a lot for a regular ensemble of players tended not to notate minute details that they knew their band would do automatically (Bach, Haydn, Ellington/Strayhorn). Notation is usually in response to a default, so "piano" does not mean "soft" but "softer than you'd think"; "staccato" means "I know you want to connect this, but don't".
Answer: 'Normal' playing is somewhat like speaking normally. Notes flow into each other - there doesn't need to be even that tiny rest you mention. Most times, notes can be given their full duration value, and if a writer wanted something different, he would write shorter notes and rests, or put staccato marks. Imagine a trumpet or sax player not joining up notes in a phrase? Sometimes it's necessary, due to limitations of the instrument or large jumps in pitch, but generally, legato is the default way to play.
Comment: Well that depends heavily on style. In the eighteenth century Viennese tradition there is a lot of talk about "regular touch" which is still slightly separated (of course the absence of articulation markings does not mean you shouldn't play any - many are implicit).
Comment: @11684 - taking all of music, not one specific genre, the answer is legato. The 'slightly separated' works for 18C Viennese, but that's not representative of much music.
Comment: Well that's not the only counter-example. I don't claim non-legato is "the default", I'm saying neither is legato, considering the amount of music before 1800 is larger than the amount of music after. Besides, the OP clearly describes non-legato; we can argue all we want about whether that's "the default" or not, that's what they want to know the name of.
Comment: @11684 - what confuses me is that the OP mentions 'when no articulation symbols are present' which covers an awful lot of written music. OP seems of the opinion that default = detached, with no reference to any period. Ambiguous! +1 for your answer, which *could* be the one the OP is searching for...
Comment: Good point, after re-reading it _is_ more ambiguous than I thought.
Answer: While Tim is correct that many players simply play legato by default, that is clearly not what you're describing.
What you're describing would simply be called non-legato (meaning not short but also not slurred).
What you describe would be the default in 18th century German/Austrian repertoire, at which time it was called "regular touch". Note that the absence of articulation markings does not mean you have to constantly play regular tough; articulation was left up to the performer to a large extent.
For most nineteenth century London repertoire for example, I would say legato is the default.
In the twentieth century composers tend to be more explicit.
In conclusion, what you describe is not "the" default but would be called non-legato.
Comment: This answer is correct for the 'detached' style of playing described by the OP. However, the question itself is ambiguous. Default generally speaking is legato, and the style described is not 'default' - except to that particular style!
Comment: As a (counter)example, string instruments use detache as a default, and the sheer absence of any articulation mark does not imply legato. Rather, the musical context dictate whether the detache is more of legato, or more of staccato.
Answer: Would be different for each instrument group, no?  For wind instruments, for example, "default" would mean to tongue the note.  Legato notes would be slurred and have a slur marking.  Without that slur, the default would be to tongue the note.
No articulation mark, the default, for strings would mean changing the bow direction between notes.  Notes with slurred articulation would mean to bow in one direction for the duration of the slur.
Answer: Not really.  Partly because absence of any special instruction doesn't mean 'no accent, slightly detached...'.   It means 'use your musical good sense'.
Today's musicians, constructing music on a computer, may have to be more specific!   And it's true that a notation-based sequencer such as Sibelius or Finale treats 'no special instructions' by default as 'full length but with a slight gap'.  I've never seen this given a special name though.
Comment: "use your musical good sense" seems like good advice generally! Here, one implication is that **the default articulation isn't necessarily the same for all notes:** it may depend on the phrasing, the shape of the line, the rhythm of it, how you analyse it, and on the style in which you're playing it. Very few pieces have every note played the same way!


Finding the constants for a PDE

Question: Here we have the straight forward PDE
$U_{xx}=\frac{1}{4}U_{tt}$
Solving it by separation of variables, we get the two ODEs:
\begin{equation}
\begin{array}
f\frac{F_{xx}}{F}=k\\
\frac{G_{tt}}{G}=k
\end{array}
\end{equation}
which are easily solved individually by finding their characteristic equation without the first order derivative term, giving the solutions for F: $\lambda=\frac{\pm\sqrt{-4\cdot(-k)\cdot 4}}{2}=\pm\frac{1}{2}\sqrt{k}$; for G: $\lambda=\frac{\pm\sqrt{-4\cdot(-k)}}{2}=\pm\sqrt{k}$.
Now we have the two solutions:
\begin{equation}
\begin{array}
rF(x)=c_1e^{1/2\sqrt{k}x}+c_2e^{-1/2\sqrt{k}x}\\
G(t)=c_3e^{\sqrt{k}t}+c_4e^{-\sqrt{k}t}
\end{array}
\end{equation}
With initial conditions, $U(0,t)=U(x,0)=0$ and $U(\frac{\pi}{2},t)=\sin2t$ we should have for F(x):
$0=c_1e+c_2e \longrightarrow c_1=c_2=A$:
$F(x)=A(e^{1/2\sqrt{k}x}+e^{-1/2\sqrt{k}x})$.
The same can be found for G, yielding:
$G(t)=B(e^{\sqrt{k}t}+e^{-\sqrt{k}t})$
But at this stage, we still have 3 unknown coefficients including k, because the next initial condition would act on the product of these two equations, since u(x,t)=f(x)y(t):
\begin{equation}
u(x,t)= A(e^{1/2\sqrt{k}x}+e^{-1/2\sqrt{k}x})B(e^{\sqrt{k}t}+e^{-\sqrt{k}t})
\end{equation}
So with the third condition, and renaming $AB=C$ we get:
\begin{equation}
\sin2t= C(e^{1/2\sqrt{k}\frac{\pi}{2}}+e^{-1/2\sqrt{k}\frac{\pi}{2}})(e^{\sqrt{k}t}+e^{-\sqrt{k}t})
\end{equation}
which gives that the coefficient A:
\begin{equation}
C= \frac{\sin2t}{(e^{1/2\sqrt{k}\frac{\pi}{2}}+e^{-1/2\sqrt{k}\frac{\pi}{2}})(e^{\sqrt{k}t}+e^{-\sqrt{k}t})}
\end{equation}
which would give:
\begin{equation}
u(x,t)= \frac{\sin2t(e^{1/2\sqrt{k}x}+e^{-1/2\sqrt{k}x})(e^{\sqrt{k}t}+e^{-\sqrt{k}t})}{(e^{1/2\sqrt{k}\frac{\pi}{2}}+e^{-1/2\sqrt{k}\frac{\pi}{2}})(e^{\sqrt{k}t}+e^{-\sqrt{k}t})}
\end{equation}
then, cancelling the common terms we get
\begin{equation}
u(x,t)= \frac{\sin2t(e^{1/2\sqrt{k}\frac{\pi}{2}}+e^{-1/2\sqrt{k}\frac{\pi}{2}})}{(e^{1/2\sqrt{k}x}+e^{-1/2\sqrt{k}x})}
\end{equation}
But this is not a normal answer for a PDE problem as such, usually the k-constant is solve for too?
When I put in an arbitrary value for k, I get the following plot:

Though this looks fine, it is strange that the k-coefficient is left unknown.
Thanks
Comment: You have three boundary conditions and the problem needs four. What is lacking?
Comment: This is all I got from the exercise of the old exam.  Thanks for confirming, I will inform the Prof.
Answer: Supposing an additional condition, for instance $U_t(0,x)=0$ we can solve the problem by using the Laplace Transform. After transforming, the problem to solve for $x$ now is
$$
s^2U(x,s)=4U_{xx}(x,s),\ \ U(0,s)=0, U\left(\frac{\pi}{2},s\right)= \frac{2}{s^2+4}
$$
thus we obtain the transformed solution
$$
U(x,s) = \frac{2 e^{\frac{\pi  s}{4}-\frac{s x}{2}} \left(e^{s x}-1\right)}{\left(e^{\frac{\pi  s}{2}}-1\right) \left(s^2+4\right)}
$$
now to invert $U(x,s)$ we use the residues at the solutions for $\left(e^{\frac{\pi  s}{2}}-1\right) \left(s^2+4\right)=0$ which are $s=\{\pm 2i\}\cup\{ \pm 4i k\}, k\in \mathbb{Z}$
and the residues at $\{\pm 2i\}$ are
$$
\lim_{s\to\pm 2i}\frac{2 e^{\frac{\pi  s}{4}-\frac{s x}{2}} \left(e^{s x}-1\right)}{\left(e^{\frac{\pi  s}{2}}-1\right) \left(s\pm 2i\right)}
$$
giving $\frac{2 \sin (x)}{s^2+4}$ and the residues at $\pm 4ik,\ \ k\in \mathbb{Z}$
$$
\lim_{s\to\pm 4ik}\frac{2 e^{\frac{\pi  s}{4}-\frac{s x}{2}} \left(e^{s x}-1\right)}{\left(s^2+4\right)}
$$
giving
$$
\frac{2 \sin (2 k x) (s \sin (\pi  k)+4 k \cos (\pi  k))}{\left(4 k^2-1\right) \left(16 k^2+s^2\right)},\ \ k\in \mathbb{Z}_{\ge 0}
$$
and after inversion we have
$$
U(x,t) = \sin (2 t) \sin (x)+\sum_{k=0}^n\frac{2 \sin (2 k x) (\sin (\pi  k) \cos (4 k t)+\cos (\pi  k) \sin (4 k t))}{4 k^2-1}
$$
Follows a plot with $n=10$
Comment: Beautiful solution Cesareo, but this looks like Bessel wavefunction. Is that a solution to the original PDE

Finding the constants for a PDE


How to create a graph representing multiple time invervals per day

Question: Given the following dict containing pairs of opening/closing hours per day:
timetable = {
    'monday': ['08:00', '12:00', '13:00', '18:00'],
    'tuesday': ['08:00', '12:00', '13:00', '18:00'],
    'wednesday': ['08:00', '12:00', '13:00', '18:00'],
    'thursday': ['08:00', '12:00', '13:00', '18:00'],
    'friday': ['08:00', '12:00', '13:00', '18:00', '19:00', '23:00'],
    'saturday': ['10:00', '16:00'],
    'sunday': ['10:00', '16:00'],
}

Is there a way to create a graphical representation that would look like this https://i.stack.imgur.com/fe9ND.jpg (this is done with gimp, that is only to get a general sense of what it would look like)?
Comment: Check this SO question: https://stackoverflow.com/questions/3695117/python-module-for-plotting-gantt-charts
Answer: Try something like this.
import matplotlib.pyplot as plt
import datetime
timetable = {
  'monday': ['08:00', '12:00', '13:00', '18:00'],
  'tuesday': ['08:00', '12:00', '13:00', '18:00'],
  'wednesday': ['08:00', '12:00', '13:00', '18:00'],
  'thursday': ['08:00', '12:00', '13:00', '18:00'],
  'friday': ['08:00', '12:00', '13:00', '18:00', '19:00', '23:00'],
  'saturday': ['10:00', '16:00'],
  'sunday': ['10:00', '16:00'],
}
COLOR_LIST = ['blue', 'red', 'green', 'pink', 'brown', 'orange', 'yellow']
HEIGHT = 2
fig, ax = plt.subplots()
y_parameter = 0
for day, day_data in timetable.iteritems():
    st = [datetime.datetime.strptime(i, "%H:%M") for i in day_data[::2]]
    et = [datetime.datetime.strptime(i, "%H:%M") for i in day_data[1::2]]
    color = COLOR_LIST.pop()
    for start_time, end_time in zip(st, et):
        diff = (end_time - start_time).total_seconds()
        x_paramter = datetime.timedelta(hours=start_time.hour, minutes=start_time.minute,
                                    seconds=start_time.second).total_seconds()
        ax.add_patch(plt.Rectangle((x_paramter, y_parameter), int(diff), HEIGHT, facecolor=color))
        centerx = x_paramter + 100
        centery = y_parameter + 1
        plt.text(centerx, centery, day, fontsize=5, wrap=True)
        plt.text(centerx, centery - 1, str(int(diff)), fontsize=5, wrap=True)
    ax.autoscale()
    ax.set_ylim(0, 24)
    y_parameter += 3
plt.show()

Output is something like:
Comment: Hello, thank you for your answer. The way you used the slicing operators to get `st` and `et` is particularly interesting to me (as a Python beginner). How would deal with interchanging `x` and `y` axes in order to have days on the `x` axis? As for the ticks, how would you set the labels to represent respectively hours (given that HH:MM isn't a simple `int`) and days?
Comment: @user11392621 you would have to play around with it :) it is doable :)


Chaining resource in angularjs

Question: I would like to chain resource in AngularJS.
The goal is that resource B wait the end of ressource A before the launch.
I tried this:
var p = $q.when(true);
p = p.then(function() {
    return $resource(...).query().$promise;
});
p = p.then(function() {
    return $resource(...).query().$promise;
});
p = p.then(function() {
    return $resource(...).query().$promise;
});

The point is that the call is not synchronous.
Answer: There is a way to group many asynchronous calls using $q.all.  The docs for this are here.
$q.all() will allow you to send in all your queries and then wait for them all the return before resolving a combined promise.  However, if you want your queries to happen in a specific order, this may not work.
Hope this helps.
Comment: This is working fine with `$q.all`but are you sure that `query` return a promise. It's not clear in my mind. "It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data."
Comment: On a second read of the docs, I think you are right to use `$promise`.  I'll change my answer a bit.

Chaining resource in angularjs


How do I get the JSON body in Jersey?

Question: Is there a <code>@RequestBody</code> equivalent in Jersey?
<code>@POST()
@Path("/{itemId}")
@Consumes(MediaType.APPLICATION_JSON)
public void addVote(@PathParam("itemId") Integer itemId, @RequestBody body) {
    voteDAO.create(new Vote(body));
}
</code>
I want to be able to fetch the POSTed JSON somehow.
Comment: Please be gentle enough to mark an answer to the asked question or update if they don't suit.
Answer: You don't need any annotation. The only parameter without annotation will be a container for request body:
<code>@POST()
@Path("/{itemId}")
@Consumes(MediaType.APPLICATION_JSON)
public void addVote(@PathParam("itemId") Integer itemId, String body) {
    voteDAO.create(new Vote(body));
}
</code>
or you can get the body already parsed into object:
<code>@POST()
@Path("/{itemId}")
@Consumes(MediaType.APPLICATION_JSON)
public void addVote(@PathParam("itemId") Integer itemId, Vote vote) {
    voteDAO.create(vote);
}
</code>
Answer: <code>@javax.ws.rs.Consumes(javax.ws.rs.core.MediaType.APPLICATION_JSON)
</code>
should already help you here and just that the rest of the parameters must be marked using annotations for them being different types of params -
<code>@POST()
@Path("/{itemId}")
@Consumes(MediaType.APPLICATION_JSON)
public void addVote(@PathParam("itemId") Integer itemId, <DataType> body) {
    voteDAO.create(new Vote(body));
}
</code>
Answer: if you want your json as an Vote object then simple use @RequestBody Vote body in your mathod argument , Spring will automatically convert your Json in Vote Object.
Comment: can you clarify this  a bit?

How do I get the JSON body in Jersey?


Checking integrity of redux state on initialization

Question: I am using redux to keep the state of the view so when users come back they have the exact same view and settings they selected before, I do this emitting events to the server and replicating the changes in a store on the backend and storing the state on the database.
Every time a user logs in we get his settings using this cide:
if(!user.state){
            socket.store = redux.createStore(reducer);
        }else{
            socket.store = redux.createStore(reducer, user.state);
        }

The problem arises when I want to add new reducers for new features and the state saved on the database becomes outdated, when I try passing the old state object to the createStore function I get
[Error: Reducer "fooReducer" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may n
ot be undefined.

And my reducers:
//this is a new reducer
function fooReducer(state, action) {
    if (!state) {
        state = defaultState.foo
    }
    switch (action.type) {
    ...
        default:
            return state
    }

}

module.exports = combineReducers({
    theme: themeReducer,
    settings: settingsReducer,
    foo: fooReducer,
});

Shouldn't the reducer check for undefined state cover these escenarios?
What would be the best practice to handle this and future scenarios when I want to add new reducers?
I am thinking to write a function to check if each key on the state is initialized but this seems like something the reducer should already be doing
Answer: I found that the problem was because I didn't set a value for foo in the default state
defaultState.foo = {x: 'var'}


Solve ordinary differential equation with undetermined coefficients

Question: It's Sarah again. I have the following two kind of related linear ordinary differential equations:
$$\bigg(\frac{d^2x}{dt^2}\bigg) + x = t \cos t \quad \quad ; \quad\quad \bigg(\frac{d^3x}{dt^3}\bigg) + \bigg(\frac{dx}{dt}\bigg) = \cos t$$
I am trying to solve them by the method of undetermined coefficients. The solution to the corresponding homoegeneous equations are no problem, but when I try to find a particular solution the problems arise.
I have tried linear combinations of $t \cos t, \cos t, t \sin t, \sin t$ but they don't work. Also tried linear combinations of $t^2 \cos t, t \cos t, \cos t$, but they failed. Could you indicate some set whose span I should examine? Thanks in advance.
Answer: We have
$$x'' + x = t \cos(t)$$
We find the homogeneous solution as
$$x_h(t) = c_1 \cos(t) + c_2 \sin(t)$$
We now look at the ODE's RHS and it is $t \cos(t)$ and the homogeneous solution also has a $\cos(t)$, so we would choose something that includes the sum of all trig terms up to that power of $t$, like $(a \cos(t) + b \sin(t) + t \cos(t) + t \sin(t))$. Because this shares a cosine term with the solution of the ODE, we multiply that entire expression by $t$, so we choose
$$x_p(t) = t(a \cos(t) + b \sin(t) + c~ t \cos(t) +d ~t \sin(t)) \tag 1$$
Note, if the solution had been $t^2 \cos(t)$ we would add two more $t^2$ terms and so forth.
Substituting $(1)$ into the ODE and simplifying, we have
$$2 (\sin (t) (-a-2 c t+d)+\cos (t) (b+c+2 d t)) = t\cos(t)$$
Equating like terms, we find
$$a = \dfrac{1}{4}, b = 0, c = 0, d = \dfrac{1}{4}$$
The final solution is
$$x(t) = x_h(t) + x_p(t) = c_1 \cos t + c_2 \sin(t) + \dfrac{1}{4}( t \cos(t) + t^2 \sin(t))$$
For the second problem, using the same logic, we have
$$x_p(t) = t(a \cos(t) + b \sin(t))$$


deleting only first instance occurring in a list

Question: I have a data-frame that has text in the first column named 'original_column'.
I have successfully been able to pick specific words out of the text column 'original_column' with a list and have them appended to another column and deleted from the original column with the following code:
list1 = {'text' , 'and' , 'example'}

finder = lambda x: next(iter([y for y in x.split() if y in list1]), None)

df['list1'] = df.original_column.apply(finder)

df['original column']=df['original column'].replace(regex=r'(?i)'+ df['list1'],value="")

I would now like to build on this code by being able to delete ONLY THE FIRST instance of the the specific words in the list from the 'original_column' after appending the listed word to a new column.
The data-frame currently looks like this:
|   original column  |
__________________________
|   text text word   |
--------------------------
|    and other and   |

My current code outputs this:
|   original column   | list1
______________________________
|        word         | text
------------------------------
|        other        |  and

My desired to output this:
|   original column   | list1
_______________________________
|      text word      | text
-------------------------------
|      other and      |  and

Answer: To match the first pattern occurrence and remove it without removing the text before this first occurrence you may use
^(.*?)pattern
and replace it with the backreference to the capturing group value, here, \1.
You may match any of your words in the list1 list as whole words (with \b(?:word1|word2|wordN)\b like pattern) and capture all the text before it with (?s)^(.*?) pattern that would match the least amount of any chars from the start of the string.
Use
df['original column'] = df['original column'].str.replace(rf"(?s)^(.*?)\b(?:{'|'.join(list1)})\b", r"\1").str.strip()

The regex used is
(?s)^(.*?)\b(?:text|and|example)\b

See the regex demo.
Details

(?s) - re.DOTALL enabled to let . match any char including line break chars
^ - start of string
(.*?) - Group 1: any 0 or more chars, as few as possible
\b(?:text|and|example)\b - a whole word from a list of alphanumeric words (that may also contain an undersocre)

The replacement is \1, the backreference to the value captured with the first (and only here) capturing group.


Looking to optimize grid search for optimal parameters

Question: I need to check 12 parameters to see what combination of those is best.  Of course it could be done with nested loops but it would take ungodly amount of time but I don't have idea how to optimize this to run in resonable time, some gradient descent maybe? Number of different parameter values can be changed to lower number. Lower is code that you can use as general idea of what I'm trying to accomplish.
from make_segmentations import make_segmentations
from validation import score_all
import numpy as np

l_mean = np.arange(0, 101, 1)
l_std = np.arange(0, 101, 1)
a_mean = np.arange(0, 101, 1)
a_std = np.arange(0, 101, 1)
b_mean = np.arange(0, 101, 1)
b_std = np.arange(0, 101, 1)

h_mean = np.arange(0, 1.01, 0.01)
h_std = np.arange(0, 1.01, 0.01)
s_mean = np.arange(0, 1.01, 0.01)
s_std = np.arange(0, 1.01, 0.01)
v_mean = np.arange(0, 1.01, 0.01)
v_std = np.arange(0, 1.01, 0.01)

high_score = np.array((0,0))
best_params = np.array((0,0,0,0,0,0,0,0,0,0,0,0))

#%%
for l_m in l_mean:
    for l_s in l_std:
        for a_m in a_mean:
            for a_s in a_std:
                for b_m in b_mean:
                    for b_s in b_std:
                        for h_m in h_mean:
                            for h_s in h_std:
                                for s_m in s_mean:
                                    for s_s in s_std:
                                        for v_m in v_mean:
                                            for v_s in v_std:

                                                make_segmentations(Lab_params = np.array((l_m,l_s,a_m,a_s,b_m,b_s)), Hsv_params= ((h_m,h_s,s_m,s_s,v_m,v_s)))
                                                score = score_all(number_of_cases = 30)

                                                if score[0] > high_score[0] and score[1] > high_score[1] :
                                                    high_score = score
                                                    best_params = np.array((l_m,l_s,a_m,a_s,b_m,b_s,h_m,h_s,s_m,s_s,v_m,v_s))

Answer: You can use the scipy.optimize function minimize on the (negative) score to optimize the parameters for the best fit.
Since your parameters seem to be statistical properties and you seem to have a number of datapoints available, I would also suggest just computing them directly. That will give you a good initial guess for the optimization, and also serve as a sanity check for the final value.
Sidenote, you can compress those nested loops using the product function from itertools to go through all possible combinations. That would look something like this (I only added the first four):
from itertools import product
for l_m, l_s, a_m, a_s in product(l_mean, l_std, a_mean, a_std):
   #do stuff

This won't improve performance (you're still searching through a parameter space with 100^12 points), but it will make you're code a whole lot more pleasent to look at and work with.
Answer: I think itertools.product is the one you are looking for you can use it as
from itertools import product
a = [1,2,3]
b = [2,3,4]
c = [4,9,3]
combinations = list(list(product(a,b,c)))
# It's output is
"""
[(1, 2, 4), (1, 2, 9), (1, 2, 3), (1, 3, 4), (1, 3, 9), (1, 3, 3), (1, 4, 4), (1, 4, 9), (1, 4, 3), (2, 2, 4), (2, 2, 9), (2, 2, 3), (2, 3, 4), (2, 3, 9), (2, 3, 3), (2, 4, 4), (2, 4, 9), (2, 4, 3), (3, 2, 4), (3, 2, 9), (3, 2, 3), (3, 3, 4), (3, 3, 9), (3, 3, 3), (3, 4, 4), (3, 4, 9), (3, 4, 3)]
"""

after generating combinations you can use it in your code
for tupl in combinations:
    #your function call and logic
    #required values can be extracted from tupl[index]


how to hide the adminblog link in the teaser

Question: how to remove admin`s blog in footer of teasers i can remove the add comment link with this code :
function  mytheme_node_view_alter(&$build){
if ($build['#view_mode'] == 'teaser')
{
    // remove "add comment" link from node teaser mode display
    unset($build['links']['comment']['#links']['comment-add']);

    // and if logged out this will cause another list item to appear, so let's get rid of that
    unset($build['links']['comment']['#links']['comment_forbidden']);
}

but i cant remove admins blog what can i do ?!
Answer: Try to use something like the below code to hide admin's blog from teaser's view in your theme's template.php, hope it will work for you:
function THEME_preprocess_node(&$variables) {
      if ($variables['view_mode'] == 'teaser') {
        if ($variables['type'] == 'blog' && (arg(0) != 'blog' || arg(1) != $variables['uid'])) {
          unset($variables['content']['links']['blog']['#links']['blog_usernames_blog']);
          unset($variables['content']['links']['node']['#links']['node-readmore']);
        }
      }
    }

Comment: this is work tnx for your tip mrs astha chauhan ;)
Answer: Check out the module Tab Tamer

Tab Tamer is an administration utility that provides easy re-ordering,
  hiding, and deactivation of tabs and subtabs. You can also rename tab
  labels.
Comment: tnx for your tip mr pontus but i can`t find any thing about node links in this module!
Comment: @hgp ahh, I see now that it was a link and not a tab you were trying to change :)


Proving a congrent modular

Question: How do I show that $3^{1974}+5^{1974}\equiv 0 \pmod {13}$? I have tried feeding the values onto a calculator but they are so big to be computed. What is the best approach?
Comment: Hint:  $3^3\equiv 1 \pmod {13}$, hence $3^{3k}\equiv 1 \pmod {13}$ for any $k$.  Can you work out powers of $5$?
Comment: Will it be 5^K=13(mod 0)?
Comment: do you understand the meaning of mod ?
Comment: There can't be any $k$ with $5^k\equiv 13 \pmod {13}$.  Can you work out $5^2, 5^3,5^4, 5^5,\cdots$?  (all $\pmod {13}$ of course). You need to find a pattern...so you can quickly compute, say,  $5^{100}\pmod {13}$ instantly.
Comment: Who said $9\equiv 1 \pmod {13}$?
Comment: You can't figure out why $27\equiv 1\pmod {13}$?  Go back to the definition, work a lot of examples.
Comment: Now am getting it.
Answer: By Fermat's Little Theorem,
$$3^{12}\equiv5^{12}\equiv 1\pmod{13}$$
and since $1968$ is divisible by $12$,
$$3^{1974}+5^{1974}\equiv 3^6+5^6\pmod{13}$$
etc.
Comment: I fully appreciate that, but how will this ,lead to the 0 mod13 part?
Answer: since Fermat's little theorem, implies $3^{12}\equiv5^{12}\equiv 1\pmod{13}$ we have:
$$
3^{1974}+5^{1974}=3^{12*164+6}+5^{12*164+6}=(3^{12})^{164}3^6+(5^{12})^{164}5^6\equiv 3^6+5^6 \pmod{13}
$$
Now, you can easily see that:
$$3^3=27\equiv 1\pmod{13}\Rightarrow 3^6=1\pmod{13}$$
and:
$$5^2=25\equiv -1\pmod{13}\Rightarrow5^6=-1\pmod{13}$$
thus, summing the above:
$$
3^{1974}+5^{1974}\equiv 3^6+5^6 \equiv 1-1 =0 \pmod{13}
$$

Proving a congrent modular


Delete duplicate number in text cell (Teradata database)

Question: I have columns in which coordinates are presented in the text format. Each set of coordinates in one cell. All coordinates all coordinates are in one table cell, like text. And i have more than 1000 cells and each contains more than 100 coordinates.
For example:
23.453411011874813 41.74245395132344, 23.453972640029299 41.74214208390741, 23.453977029220994 41.741827739090233, 23.454523642352295 41.741515869012523, 23.441100249526403 41.741203996333724, 23.441661846243466 41.740892121053918,
23.456223434003668 41.74058024317317, 23.441661846243466 41.740892121053918
In the case of repeating coordinates, I need to delete the last of them (bold in the example) and delete the coordinate located between them (italic in the example).
Please tell me how this can be done?
Thanks a lot!
Comment: Is that one or several rows of data? How many columns?
Comment: I'd probably start by splitting the coordinates (pairs of values) into separate rows with a sequence number, e.g. using STRTOK_SPLIT_TO_TABLE. But what happens if a coordinate appears more than twice?
Comment: update your question and add  the related  table schema  ..
Comment: Аll coordinates are in one table cell
Answer: OLAP functions will be your friend.
 - ROW_NUMBER() will identify the 2nd, 3rd,... occurences
 - with COUNT() OLAP you can identify the double ones
 - with CASE and some MAX-ROWS PRECEEDING you can tag the rows between 1st and 2nd
Two crucial questions for the concrete solution, you have to ask:
 - by which criteria are your rows ordered (I guess a not shown column with TimeStamps...)
 - what happens if a coordinate occurs 3 -times (or even more)? - Delete all between 1st and last or just between 1st and 2nd or always between uneven&even?


Text to mp3 in VBa

Question: I'm writing a program in Visual Basic to pronounce aloud the text and save it later. But I do not know why the pronunciation is wrong
Private Sub CommandButton2_Click()
 Dim msg, sapi, FileStream, Path
 msg = "siema"
 Path = "C:\test\test.wav"
 Set FileStream = CreateObject("sapi.SpFileStream")
 Set sapi = CreateObject("sapi.spvoice")
 FileStream.Open Path, SSFMCreateForWrite, True
 Set sapi.AudioOutputStream = FileStream
 sapi.Speak "hello"  <<<<<<<<<<<<<<<<<<Error
 FileStream.Close
 Set FileStream = Nothing
 Set sapi = Nothing
End Sub

Answer: Consider using a cell:
Sub SayHello()
    [A1] = "Hello"
    [A1].Speak
End Sub

Text to mp3 in VBa


Keep the drop down menu on top of other elements

Question: I have a drop down menu to change the language but when the list got longer and the menu now is behind the other element.
I don't really get what is need to be change or what CSS I have to apply to get the dropdown stay on top of the other elements so that they can still see the list and select them.

I'm trying to get most of the CSS that applied to the element, but they are "LESS"
These are part of them
li.lang-picker:first-child {
  border-right: none;
}
.ui-append.ui-select {
  background-color: white;
}
#lang-picker {
  margin: -7px 15px 0 -18px;
  border-color: transparent;
}
#lang-picker:hover {
  border-color: #CCC;
}
#lang-picker ul {
  background: white;
  display: inline-block;
}
#lang-picker ul li {
  display: block;
}
#lang-picker .ui-select-menu {
  width: auto;
  border-color: #CCC;
}
#lang-picker .ui-select-menu ul {
  width: auto;
}
#lang-picker .ui-selected::before {
  margin-right: 5px;
}
#lang-picker .ui-smedium {
  width: auto;
}
#lang-picker > .icon {
  background: none;
  color: #555;
  padding: 0 10px 0 0;
}
#lang-picker > .icon:hover {
  background: none;
  color: #555;
}
/*********************************************************
* Filter
*/
.gallery-header .header {
  float: left;
  padding-bottom: 10px;
  font-family: 'Open Sans Light', sans-serif;
  -webkit-font-smoothing: antialiased;
  margin-right: 20px;
}
.gallery-header .header h1,
.gallery-header .header p {
  display: inline;
  margin-right: 10px;
  font-weight: normal;
  letter-spacing: -0.25px;
}
.gallery-header .header h1 {
  font-size: 2.4em;
  line-height: 16px;
  color: #3fb58e;
}
.gallery-header .header p {
  font-size: 1.4em;
  color: #555555;
}
.gallery-header .header p a {
  color: #20abdc;
  text-decoration: none;
}
.gallery-header .header p a:hover {
  text-decoration: underline;
  color: #4abce5;
}
#tools h1 {
  line-height: 1.4em;
}
.filter {
  position: relative;
  background: #3fb58e;
  float: right;
  z-index: 3;
  padding: 0.5em 1em 1em;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
.filter label {
  color: #FFF;
  line-height: 1.6;
}
.filter #search-filter {
  border-color: #38a27f;
}
.filter #search-filter:hover {
  border-color: #2b7c61;
}
.filter #search-filter .icon {
  background: #328f70;
}
.filter #search-filter .ui-select-menu {
  border-color: #3fb58e;
}
.filter:before {
  content: "";
  display: block;
  position: absolute;
  top: 100%;
  left: 50%;
  width: 0;
  height: 0;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-top: 10px solid #3fb58e;
  margin-left: -10px;
}

Comment: Most likely you need to change the z-index. Please post your HTML and CSS here.
Comment: I'm going to get the CSS and HTML that I can and update them.
Comment: possible duplicate of [How do I get this dropdown to be on top of the other elements](http://stackoverflow.com/questions/12526631/how-do-i-get-this-dropdown-to-be-on-top-of-the-other-elements)
Answer: You can use 'z-index' property together with 'position' property.
In order 'z-index' to work, position should be set to 'relative'.
Comment: It does work @mikeGordo except is not the way it suppose to be I guess https://dl.dropboxusercontent.com/spa/n5v3bx9nnjkdpzf/_dv2hfnv.png
Comment: Sorry is this a better picture? https://dl.dropboxusercontent.com/spa/n5v3bx9nnjkdpzf/u-oyrnu9.png it shouldn't go way off the menu itself.
Comment: I don't know how to get all those up in the question but this is the file in the github page https://github.com/mozilla/login.webmaker.org/blob/master/app/http/public/css/account.less
Comment: @Ali not sure what am I looking at. How should it be?
Comment: @Ali oh i see. your css listing for those elements would help to understand what exactly is going on here :)
Answer: Give z-index:100 or more try giving more.
div.ui-select-menu
{
    z-index:100;
}

Comment: You're making assumptions here. You don't know if a z-index of 100 is enough to accomplish what the OP needs, but more importantly, a z-index rule alone won't do anything unless the element has been positioned.
Answer: First you need to set the position attribute to something that is not static. If there are only static(the default value) elements in the page, then setting position: relative; will do. However if there are elements whose position isn't static then you need to set the z-index attribute to a value higher than the other elements' z-index.


Implication in local noetherian domain of Krull's dimension 1.

Question:
Let $(A,m)$ be a local noetherian domain with Krull dimension $1$. Let $k$ be the field $A/m$.
I'm trying to prove that if $m/m^2$ has dimension $1$ as a $k$-vector space, then every ideal $I$ of $A$ is a power of $m$.

I started the argument with; If $I=A$ then trivially $I=m^0$ and we're done. Otherwise it must be
$I\subset m$ since every element of $A\setminus m$ is invertible;
but I can't think of a way to use the hypothesis from this point.
Could someone sketch a way to prove this? Thank in advance.
Comment: Well, it has to be a power $\mathfrak{m}^k$. Can you think of a way to find $k$?
Comment: @Hoot That it has to be a power of $m$ is what I want to prove. I feel like it has to be easy, but I just don't see it. I've been thinking about it a while but reasoning picking a point $i\in I$ leads me nowhere.
Comment: I guess what's most natural depends on what's available to you. Do you know Krull's intersection theorem? It says that $\bigcap_i \mathfrak{m}^i = 0$. My point is that you need to at least get some candidate $k$ from the initial data.
Comment: @Hoot I don't know Krull's theorem. Just looked for it. In any case I can't think of a candidate to the power.
Comment: I'll try to think of whether there's an easier way. Krull is a good fact to know, though. Anyway, if $I \neq 0$ then there is some $k$ such that $I \subseteq \mathfrak m^k$ but $I \not\subseteq \mathfrak{m}^{k+1}$. If this thing is going to be true then we must have $I = \mathfrak{m}^k$, so this is at least something to hold onto. Can you prove that $\mathfrak{m}$ is principal, by the way?
Comment: @Hoot You're using Krull's intersection theorem when saying that $I\subset m^k$ but $I\not\subset m^{k+1}$ for some $k$ right? But how you deduce from here that $I=m^ k$? This implication is a part of an exercise that shows equivalence between several conditions, one of which is that $m$ is principal.
Comment: I'm not deducing that $I = \mathfrak{m}$, I'm saying that's the goal! Showing $\mathfrak{m}$ is principal is an easy application of Nakayama's lemma.
Answer: Since the question is already answered here, I will give you another sketch, which uses the fact that any regular local domain is factorial. This might be an overkill, but we already have an elementary solution anyway.
The assumptions precisely state that $A$ is a one-dimensional regular local ring. In particular we have

$A$ is factorial (a more or less non-trivial fact)
$A$ has precisely one non-zero prime ideal, namely $\mathfrak m$ (a trivial fact).

Any irreducible element generates a non-zero prime ideal. Hence up to units, there is only one single irreducible element, say $a$. In particular any element looks like $a^n$ up to a unit. Thus any Ideal is equal to $(a^n)$, where $n$ is the minimal exponent occuring within elements of $I$.
Comment: Finally it is clear to me why the implication needed to be true!! Thank u


Lilypond: how to restore Fingering.staff-padding?

Question: In all examples I saw, the only value ever assigned to Fingering.staff-padding is #'() to make fingering be placed inside the staff. What should I do to go back to placing fingering outside the staff? What was the previous value of Fingering.staff-padding?
Answer: The effects of an \override can be undone with a \revert.
In particular:
\override Fingering.staff-padding = #'()
can be "cancelled" with:
\revert Fingering.staff-padding

You could try a number instead of the empty list, i.e.:
\override Fingering.staff-padding = #0
which seems to be about right.
Or you could (of course) try a larger number if you want more padding.
If you look in the Documentation Internals 3.1.51 Fingering, it says that the default value for fingering staff padding is 0.5.
So:
\override Fingering.staff-padding = #0.5
is the way to manually reset this setting to its default value.

However applying \revert is obviously a simpler method than messing around with numbers.


How to migrate multi role to an user using migrate csv plugin

Question: I have migrated bunch of users using the Migrate Source CSV and am succeeded in it, But I want multi-roles to be defined for single user.
Here is my config file,

Here is my following cases that I have tried out in a CSV file and it failed,

Is there is anything am missing out?
Answer: First put your all roles inside double quote separating by comma (,) and be sure that your all roles on csv file must be role's machine name.

then edit your config file something like this....
process:
  name: name
  mail: email
  pass: password
  roles:
    plugin: explode
    delimiter: ','
    source: roles
  status: status
destination:
  plugin: 'entity:user'
  md5_passwords: true

you have to use plugin: explode provided by drupal to import multiple roles separated by comma (,).
And if you are importing password also then use md5_passwords: true
Answer: I had the same issue those days and I came up with the following workaround (I don't think is the best but at least works!)
You roles should be comma separated in the CSV. Also, I had to make the match between the rids as in D7 the rid where numbers (eg 1,2,4) and in D8 it was strings (eg admin, default_role, etc)
Create a custom module only for the migration and use hook_user_presave in your module file.
//check if the user has multiple roles comma separated
if( strpos($current_roles[1], ',') !== false )
{
  //split the roles
  $tmp = explode(', ', $current_roles[1]);
  foreach ($tmp as $role){
    //add each role separately to the user
    $user->addRole($role);
  }

  //remove the old roles added by the CSV (all user roles comma separated)
  $user->removeRole($current_roles[1]);
}
else{
  // Default role assigned to all other users - optional
  $user->addRole('default_role');
}

Also another way to do that is this but I didn't try it so I don't know if/how it works.
Answer: This is with ref to Drupal 8/9
Create your CSV with Roles column containing : machine_name only seperated by only comma and no spaces around ex; role_update,role_create
Update CSV data accordingly, this is an example for reference
First Name Last Name Name      E-Mail     Roles
fname      lname     username  user@email role_update,role_create # No Space in the Cell of Roles data

Keep your CSV at public folder : webroot/sites/default/files/User-List-D7.csv
YML file should include the import in following way:
id: user_migration_csv
migration_tags: null
migration_group: Usermigration
label: 'User migration from CSV'
source:
  plugin: csv
  path: public://User-List-D7.csv
  header_row_count: 1
  ids:
    - ID
process:
  field_first_name: First Name
  field_last_name: Last Name
  name: Name
  mail: E-mail
  roles:
    plugin: explode
    delimiter: ','
    source: Roles


Convolution proof (symmetric)

Question: I want to show, that for some functions $ f,g \in L^1(\mathbb{R^n})$ hold:
$$f*g=g*f$$
My proof so far:
$ f*g= \int_{\mathbb{R^n}} f(x-y)f(y) dy$
Substitution: $\phi(y) =x-y$
This leads to:
$$\int_{\mathbb{R^n}} f(\phi(y)) g(y) | Det(D \phi(y)| = \int_{\mathbb{R^n}} f(\phi(y)) g(y) (-1)^n dy$$
How can I go on from there?
Answer: The Jacobian is $1$, not $(-1)^{n}$. (You forgot the absolute value). So $\int f(x-y)g(y)dy=\int f(y)g(x-y)dy$ and $(f*g)(x)=(g*f)(x)$.
Comment: I see:) But then I have $ \int_{\mathbb{R^n}} f(\phi(y)) g(y) dy$ How do you get to $ \int f(y)g(x-y)$ ?
Comment: $\int f(\phi(y))g(y)dy=\int f(z)g(\phi^{-1}(z))dz$ Note that $x-y=z$ is same as $x-z=y$. hence $\phi^{-1}=\phi$ so we get $\int f(z)g(\phi (z))dz$. Now change the 'dummy' variable $z$ to $y$.
Comment: Sorry I do not unterstand why $ x-y=z$ and $x-z=y$ should be the same. Both are linear transformations.
Comment: $x-y=z$ means $x=y+z$. $x-z=y$ also means $x=y+z$.
Comment: Thank you for your help:)

Convolution proof (symmetric)


Qual é mais performático - foreach ou array_map?

Question: Qual de ambos são mais performáticos, foreach?
foreach ($example as $val) $ex[] = str_replace(...);

ou
$ex = array_map(function ($val) {
    return str_replace(...);
}, $example);

Acredito que seja o foreach, se for em quais caso devo utilizar o array_map e porque?
Qual de ambos segue melhor boas práticas de programação, ou não se encaixa neste escopo?
Comment: Sabes as diferenças entre os dois? sabes a razão de usar array_map para mapear uma array? (pergunto para podermos responder de forma adaptada ao teu conhecimento atual)
Answer: O problema a vezes é confundir o propósito de cada coisa.
array_map tem inúmeras funcionalidades, que vão além das apresentadas nos exemplos da pergunta.
array_map tem como finalidade mapear um array baseando-se numa função passada por callback.
Exemplo:
  array_map('trim', [' wallace ', ' bacco ', ' guilherme ']);

Resultado:
  ['wallace', 'bacco', 'guilherme']

Observe que a função trim foi chamado para cada item do array.
Nesse caso, se for comparar com foreach, pensaria na praticidade (e não somente em performance), pois se fosse fazer com foreach, esse código ficaria assim:
$arr = [' wallace ', ' bacco ', ' guilherme '];

foreach ($arr as &$value) $value = trim($value);

Então, você tem que ter em mente que a finalidade/propósito de cada um é diferente.
Outro exemplo para você entender isso é: Já se perguntou por quê no array_map o callback é passado como argumento primeiro que o array? É porque array_map permite múltiplos arrays - coisa que diferenciaria muito do foreach.
Veja:
array_map(function ($v1, $v2, $v3) {
       echo $v1, $v2, $v3;
}, ['a', 'b', 'c'], [1, 2, 3], ['@', '!', '&']);

O resultado seria:
'a1@'
'b1!'
'c3&'

Ou seja, com array_map você tem a possibilidade de mapear um ou mais array, e não só mapear apenas um.
NOTA: No exemplo acima, eu utilizei echo dentro do callback de array_map, mas não é algo que seja muito útil de se fazer com array_map.
No final das contas, eu fiz esses exemplos com array_map apenas para entender que não há necessidade de comparar foreach  com array_map, uma vez que os mesmos têm finalidade diferentes.
Você poderia, por exemplo, querer comparar array_map com array_walk, mas se você ver a finalidade de cada um, você vai ver que não fazem a mesma coisa.
Então minha conclusão é: Use array_map para mapear, e  foreach, para percorrer o array.


Destructuring/Unpacking first and rest in Clojure

Question: In Python 3, if you want to unpack the first and rest of a list (or tuple), you do
x, *y = [1, 2, 3]
#x = 1, y = [2, 3]

How do you do this inside a let block in Clojure? I've tried :as parts and
(defn destructurer [vec]
  (let [[beginning the-rest :as parts] vec]
    [beginning the-rest]
    )
  )
;; (destructer [1 2 3])
;; [1 2] <- missing the 3

Answer: You need to add an & to make the next binding capture rest:
(defn destructurer [vec]
  (let [[beginning & the-rest :as parts] vec]
    [beginning the-rest]
    )
  )

There's a nice github gist on clojure destructuring capabilities here.