Question regarding local martingales.

Question: In the definition of a local martingale I have that for a filtered probasbility space $(\Omega, \mathcal{F},P,\mathbb{F})$. A local martingale is an adapted process M, such that there exists a sequence of increasing  stopping times such that $\tau_{n}\rightarrow \infty$ a.s., and $M(t\wedge\tau_n)$ is a martingale for each n. This is also the definition given on Wikipedia.
I have a problem showing that if M is a local martingale, and $\tau$ is a stopping time, then $G(t)=M(t\wedge \tau)$ is a local martingale. The proof I have been given seems wrong:
By doobs optional sampling theorem we can show that for each n:
$E[G(t\wedge \tau_n)|\mathcal{F}_{s\wedge \tau}]=E[M(t\wedge \tau\wedge \tau_n)|\mathcal{F}_{s\wedge \tau}]=E[M((t\wedge \tau)\wedge \tau_n)|\mathcal{F}_{s\wedge \tau}]=_\text{optional sampling}M((s\wedge \tau)\wedge \tau_n)=G(s\wedge \tau_n)$.
In the theorem I used the two bounded stopping times $t\wedge \tau$
, and $s \wedge \tau$.
But this only shows that $E[G(t\wedge \tau_n)|\mathcal{F}_{s\wedge \tau}]=G(s\wedge \tau_n)$. But I need that $E[G(t\wedge \tau_n)|\mathcal{F}_{s}]=G(s\wedge \tau_n)$.
Do you see how to finish the proof? I am stuck.
Comment: Writing $M^{\tau_n}$ for the martingale $t\mapsto M(t\wedge \tau_n)$, observe that $G(t\wedge \tau_n)=M^{\tau_n}(t\wedge\tau)$, which is therefore a martingale because (thanks to Doob) a stopped martingale is a martingale.
Comment: @JohnDawkins Thank you, but how do you prove that a stopped martingale also is a martingale? I tried proving it, but I get the same problem as above.
Comment: @JohnDawkins How do you prove that a stopped martingale is a martingale, unless it is almost surely right-continuous (and the filtration is right-continuous)? See https://math.stackexchange.com/questions/2329717/is-a-stopped-local-martingale-a-local-martingale.
Answer: In answer to the question in your comment on my comment: Let $X$ be a martingale, $T$ a stopping time, and $Y_t=X_{t\wedge T}$ the stopped process. By Doob, for $0\le s<t$, $E[Y_t\,|\,\mathcal F_{s\wedge T}]=Y_s$. Now let $A$ be an event in $\mathcal F_s$. On $A\cap \{T\le s\}$ we clearly have $Y_t=Y_s$. And $A\cap\{s<T\}$ is an element of $\mathcal F_{s\wedge T}$. Thus
$$
E[Y_t\cdot 1_{A\cap\{T\le s\}}]=E[Y_s\cdot 1_{A\cap\{T\le s\}}]]
$$
and (using optional sampling)
$$
\eqalign{
E[Y_t\cdot 1_{A\cap\{s<T\}}]
&=E[E[Y_t\,|\,\mathcal F_{s\wedge T\}}] 1_{A\cap\{s<T\}}]]\cr
&=E[Y_s\cdot 1_{A\cap\{s<T\}}]\cr.
}
$$
Adding these two we obtain
$$
E[Y_t\cdot 1_A]=E[Y_s\cdot 1_A],
$$
which proves that $E[Y_t\,|\,\mathcal F_s]=Y_s$.
Comment: Thank you very much for your help, it was very good.

Question regarding local martingales.


Limilabs IMAP exception

Question: I am trying to use Limilabs imap library to connect to email;
  tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);

works fine ;  while  limilabs imap does not
using (Imap imap = new Imap())
{
    imap.Connect("imap.gmail.com", 993);

gives exception :
Limilabs.Client.ServerException was unhandled
  HResult=-2146233088
  Message=Tried to read a line. No data received. Please make sure that antivirus and firewall software are disabled or configured correctly.
  Source=Mail
  StackTrace:
       at   .()
       at   .(MemoryStream )
       at   .()
       at Limilabs.Client.IMAP.ImapResponse.(Stream )
       at Limilabs.Client.IMAP.Imap.(ImapResponse )
       at Limilabs.Client.IMAP.Imap.(String , Boolean )
       at Limilabs.Client.IMAP.Imap.ReceiveResponse(String tag)
       at Limilabs.Client.IMAP.Imap.wqf45mzzsju7786nbrb2h8aclqm8jmnx    ()
       at Limilabs.Client.ClientBase.Connect(String host, Int32 port, Boolean useSSL)
       at Limilabs.Client.ClientBase.Connect(String host, Int32 port)
       at ConsoleIMAP.Program.Main(String[] args) in c:\users\hmohamed\WcfServiceLibrary1\ConsoleIMP\Program.cs:line 136
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:
       HResult=-2146233088
       Message=Tried to read a line. No data received.
       Source=Mail
       StackTrace:
            at   .()
       InnerException:

Comment: Let me guess, Limilabs expects to speak IMAP without TLS, gmail expects IMAP with TLS, and as a result none of them ever speak to each other?
Comment: so can i try hotmail!
Comment: tried connectssl  but it times out
Answer: Limilabs imap.Connect has an overload to specify if SSL is to be used. It does not infer it from the port you specify. You can also use the imap.ConnectSSL method.
For more info, see:
http://www.limilabs.com/blog/use-ssl-with-imap
Answer: I know this question is 2 years old, but it may be important for someone else having this problem.
Imap.Connect/Imap.ConnectSSL methods not only connect, they also start TLS/SSL negotiation (if needed), receive initial server response, and get extensions supported by IMAP server.
That's why connecting with TcpClient may look like it's working at first, but in fact, you haven't started TLS/SSL negotiation nor any other communication with the server.
Gmail supports TLS/SSL connections only, so you must use ConnectSSL method, there is also no need to specify port explicitly:
using (Imap imap = new Imap())
{
    imap.ConnectSSL("imap.gmail.com");

    //...

    imap.Close()
}

Remember that you must enable IMAP access for your account in Gmail.
Answer: I know this is a very old question, we just had the same error and solved it, hope can help anyone who has the same situation as us.
We use Amazon Simple Email Service (SES) and SES provides different ports: STARTTLS Port(25, 587 or 2587) and TLS Wrapper Port(465 or 2465)
In our code, we call smtp.StartTLS() after smtp.Connect(Server, Port), we should use the port STARTTLS Port(25, 587 or 2587), if we use TLS Wrapper Port(465 or 2465) will raise the error:
Tried to read a line. Only '' received. Please make sure that antivirus and firewall software are disabled or configured correctly.

Limilabs IMAP exception


When should I use mb_strpos(); over strpos();?

Question: Huh, looking at all those string functions, sometimes I get confused. One is using all the time mb_ functions, the other - plain ones, so the question is simple...
When should I use mb_strpos(); and when should I go with the plain one (strpos();)?
And, yes, I'm aware about that mb_ functions stand for multi-byte, but does it really mean, that if I'm working with only utf-8 encoded strings, I should stick with mb_ functions?
Thanks in advance!
Answer: You should use the mb_ functions whenever you expect to work with text that's not pure ASCII. I.e. you can work with the regular string functions, even if you're using UTF-8, as long as all the strings you're using them on only contain ASCII characters.
strpos('foobar', 'foo')  // fine in any (ASCII-compatible) encoding, including UTF-8
strpos('ふーばー', 'ふー') // won't work as expected, use mb_strpos instead

Comment: And what about performance when using `mb_` functions on UTF-8 strings containing only ASCII characters? Would it be slower/faster/no significant difference (as always..)? *interested because `mb_` looks like de facto choice when working with UTF-8 strings, even if they contain only ASCII*
Comment: @Tom As always: profile it, if you're concerned. :) My hunch is that it would be slightly slower, but not in any significant way, unless you're working on massively large strings.
Comment: no point in profiling if the result is ms's in either way (and lets not argue on this one, of course in long-running scripts it could become noticeable) and/or you can _kind of_ predict the result logically. But, huh, I already thought that it'd be slower, just wanted to know different opinion. Anyways, thanks, accepted!
Answer: Yes, if working with UTF-8 (which is a multi-byte encoding : one character can use more than one byte), you should use the mb_* functions.
The non-mb functions will work on bytes, and not characters -- which is fine when 1 character == 1 byte ; but that's not the case with (for example) UTF-8.
Comment: Should be: "...that's not ***necessarily*** the case with UTF-8." The lower UTF-8 ranges are identical to ASCII and work just fine with the regular string functions.
Comment: @deceze just curious, are there any pitfalls to using mb_* all the time rather than the regular string functions? Microptimization aside.
Comment: Chose deceze's answer because of _ASCII only_ statement.
Answer: I'd say yes, here's the description from the php documentation:
mbstring provides multibyte specific string functions that help you deal with multibyte encodings in PHP. In addition to that, mbstring handles character encoding conversion between the possible encoding pairs. mbstring is designed to handle Unicode-based encodings such as UTF-8 and UCS-2 and many single-byte encodings for convenience....
If you're not sure that the mb extension is loaded, you should check before because mb-string is a non-default extension.


AWK, cut or ced...double parsing mail log to get authentication failures

Question: I would like to parse mail log files, which originally look like this:
2018-10-23 23:27:51,026 INFO  [ImapServer-4] [ip=10.10.11.50;oip=22.214.171.124;via=10.10.11.50(nginx/1.7.1);ua=Zimbra/8.8.7_GA_1964;cid=127325;] imap - authentication failed for [firstname.lastname@example.com] (invalid password)

for keywords, either:
"invalid password" or "authentication failed"
Goal is to sort them by either "OIP" (original IP) or by user MAIL accoount, to see in first case the attacking IP, and in second case, which user account is under attack.
Those should be 2 command lines (will incorporate them into my bash script for easier administration of mail servers).
What I came to is this:
cat /opt/zimbra/log/mailbox.log | grep "invalid password" | awk -F " " '{print $1 $2 $5 $11 }'

...but I am stuck there. I do not know how to double-parse attacker IP from "oid=" and make some "uniq" and "sort" against results. I am trying to get results like this:
Case 1 - display attacking IPs, sorted by number of invalid logins:
37    18.104.22.168
16    220.127.116.11
 8    18.104.22.168

Case 2 - display attacked MAIL accounts, sorted by number of invalid logins:
128   firstname.lastname@example.com
 37   email@example.com
  6   email@example.com

I will then run manually my (above) one-liner to analyze deeper, but for overview can you help me with AWK or cut or sed commands, please?
Comment: Had a quick look: `awk 'BEGIN{FS=OFS=";"}/invalid password/{ oips=substr($2,index($2," - ")+5);oip[oips]++} END { for (ip in oip) printf("%s\t%s\n", oip[ip],ip)}'  logfile`. Give it a try. The email part is easy as well: `awk -v RS="[][]"  '/@/{email[$1]++} END { for (e in email) print e,email[e]}' logfile`
Answer: Using space or semicolon as the field separator, you can do
$ awk -F '[ ;]' '/authentication failed/ {print $7, $17}' file
oip=18.104.22.168 [email@example.com]

Or perl
$ perl -lne '/authentication failed|invalid password/
         and /oip=(.+?);.*for \[(.+?@.+?)\]/
         and print "$1 $2"' file
18.104.22.168 email@example.com

Use either one of those, then sort | uniq -c the output
Answer: $ cat $$
2018-10-23 23:27:51,026 INFO  [ImapServer-4] [ip=10.10.11.50;oip=188.8.131.52;via=10.10.11.50(nginx/1.7.1);ua=Zimbra/8.8.7_GA_1964;cid=127325;] imap - authentication failed for [email@example.com] (invalid password)
$ cat $$ | egrep '(authentication failed|invalid password)' | egrep -o "[[a-z]*@[a-z]*\.[a-z]*]" | sort | uniq -c
      1 [firstname.lastname@example.com]
$ cat $$ | egrep '(authentication failed|invalid password)' | egrep -o "oip=[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*" | sort | uniq -c
      1 oip=126.96.36.199
$

Comment: This one is almost perfect! I just modified `sort` to `sort -nr` so to have descending order. Thank you!


VBA - Maximo de caracteres no dropdown-list

Question: ' Validação Motivo
Columns(motivo).Select
With Selection.Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:= _
    "TESTE1;TESTE2;TESTE3;TESTE4;TESTE5;TESTE6;TESTE7;TESTE8;TESTE9;TESTE10;TESTE11;TESTE12;TESTE13;TESTE14;TESTE15;TESTE16;TESTE17;TESTE18;TESTE19;TESTE20;TESTE21;TESTE22;TESTE23;TESTE24;TESTE25;TESTE26;TESTE27;TESTE28;TESTE29;TESTE30;TESTE31;TESTE32;TESTE33"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With

Se minha lista de 'testes' exceder os 256 characteres, minha lista fica bloqueada e se exceder 1024, um erro é recebido.
No exemplo acima, tenho uma lista até teste33, totalizando 256 characteres. Como eu adicionaria o teste34 e assim, contornar este erro?
Answer: Referindo a esta resposta do SO Global: Maximum drop-down list/formula length in Excel
O passo-a-passo será explicado a seguir:
Criar Planilha com Dados de Validação
Primeiro uma planilha deve ser criada com os dados de validação e não do modo:
Formula1:= _
 "TESTE1;TESTE2;TESTE3;TESTE4;TESTE5;TESTE6;TESTE7;TESTE8;TESTE9;TESTE10;TESTE11;TESTE12;TESTE13;TESTE14;TESTE15;TESTE16;TESTE17;TESTE18;TESTE19;TESTE20;TESTE21;TESTE22;TESTE23;TESTE24;TESTE25;TESTE26;TESTE27;TESTE28;TESTE29;TESTE30;TESTE31;TESTE32;TESTE33"
A Planilha de Nome ListaValid deve ser criada e os dados de validação colocados em alguma coluna, no exemplo na Coluna A, como na imagem:

Código
O código abaixo insere a lista da Coluna A da planilha ListaValid como validação na coluna C da planilha Planilha1.
LastRow = Worksheets("ListaValid").Cells(Rows.Count, "A").End(xlUp).Row
ActiveWorkbook.Names.Add Name:="List", RefersTo:="=ListaValid!$A$1:$A$" & LastRow
Worksheets("Planilha1").Range("C:C").Validation.Delete
Worksheets("Planilha1").Range("C:C").Validation.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="=List"

Obs.: Para evitar erros de células em branco na lista de validação, uma função para deletar estes dados pode ser adicionado.
Resultado
Um teste foi realizado com a lista de validação com dados de TESTE1 a TESTE400, ou seja, 400 linhas.
O resultado é o seguinte:

Explicação
Última linha
LastRow = Worksheets("ListaValid").Cells(Rows.Count, "A").End(xlUp).Row
Achar a última linha da planilha da lista de validação e coluna A, ou seja, os dados da lista devem ser preenchidos a partir da linha 1, em ordem.
Criar Name List
ActiveWorkbook.Names.Add Name:="List", RefersTo:="=ListaValid!$A$1:$A$" & LastRow
Cria uma List com os dados da planilha de validação, no Range de A1 até A & Última Linha
Deletar Validação
Worksheets("Planilha1").Range("C:C").Validation.Delete
Deleta toda a validação da coluna C, para inserí-la na próxima linha e evitar erros.
Inserir Validação
Worksheets("Planilha1").Range("C:C").Validation.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="=List"
Insere a validação com os dados da lista criada.
Comment: Daniel, obrigado pela resposta. Consegui solucionar meu problema anteriormente e foi exatamente como sua resposta.


How do orchestras synchronize bow movement?

Question: The last few times I've been to see the orchestra, I've noticed that the bow movements of all the strings are synchronized. I've been in bands and choirs before but never a group with strings, so this just amazes me that there's not a single person out of sync.
I figure the three options are:

There's some musical standard and everyone just does it the same way.
It's explicitly notated in the scores from the composer, or
The section leaders choreograph the movement for each section.

How is this achieved?
Comment: Principals are responsible for issuing bowings to their respective sections.
Comment: Sometimes conductors have strong views about bowings.
Comment: 1-2-3: it's a little of each, to one degree or another.
Comment: With typical seating arrangements, bowing the wrong way can cause bows to hit the next player's arm, so bowing the same way can be necessary to make playing possible at all.
Answer: All the three options you enumerate come into play:

some bowings are obvious: a measure of four quarter notes with no markings is very likely going to be down-up-down-up. A forte note by itself will normally be a down bow.
composers or arrangers very often explicitly notate bowings for the strings
the section leaders will usually have the music beforehand, and they will mark the bowings in the parts for their section (possibly changing the composer's markings)
at rehearsals the section leaders, or possibly the conductor,  will often announce bowing changes
the string players will often add markings to their part during rehearsals
even if there has been little or no rehearsal and the parts are not properly marked, professional string players are normally experienced enough to be able to follow the leader's bowings on-the-fly
Comment: @ThorbjørnRavnAndersen The bowing has a has a big effect on the sound.
Comment: Does it influence the sound if bowing is not the same for all, or is it just a visual thing?
Answer:
How is this achieved?

There is a hierarchy throughout the orchestra for each group of musicians (woodwind, brass, violinists, violists, cellists, etc.). Each group has a leader who is responsible for that section and whom the players in that section must watch. The largest group is the violinists, split into first violins and second violins. Sometimes the first and second violins play different notes to each other but quite often they play the same notes.
The conductor is the head of the orchestra hierarchy and he or she guides the musicians via their gestures. The leader of the violinists is called the concertmaster and they have several duties:

They are usually responsible for all the musicians tuning their instruments in the pre-concert period.
They usually issue bowings to the other violinists. This makes sure that all the violinists in the two sections are playing the same notes with the same bowings. Nobody is bowing a note up when everybody else is bowing down.
They are the leader for the violinists. This means that they watch the conductor and to this end they usually sit closest to the conductor. The other violinists have to watch the concertmaster from whom they take the lead whilst also keeping an eye on the conductor. By watching the concertmaster they know what their bow should be doing when.
Answer: You're missing

The conductor tells them what to do.

Phrasing is somewhat standardised when you learn an instrument, particularly the tendency to start bars/phrases on a down bow.  The composer may have marked phrasing and slurs on the score, or the engraver may add them as guidance, so that bowing on these is explicitly stated.
The conductor (not the section leader) is the person who ultimately sets bowing though.  Different bowings can sound different, most obviously for short notes at either end of the bow, so the conductor will choose bowings that create what they want "their" version of the music to sound like. Staccato notes (one note per bowing) obviously sound different too.  And phrasing generally (where you change bow direction) can be set by the conductor separately from anything written on the sheet music.
Note that the leaders of their respective sections sit in front of their section.  The rest of their section are able to follow them - but only the conductor can see musicians who go wrong.
Comment: "The conductor (not the section leader) is the person who ultimately sets bowing though": that may or may not be true depending on several factors, including the level of the performance (world-class professional or community music school) and the degree to which the conductor likes to micromanage.  In most professional situations, the conductor is only going to get into that level of detail in certain critical sections.  But +1 for bringing up the conductor, because the conductor certainly has input, just as with breathing decisions in the winds and brass and other details of phrasing.


uniform distribution with density function?

Question: If $0.3,0.2,0.8,0.3,0.4$ are found from one random instance with uniform distribution with following density function, We need to find $\theta $ estimate with Method of moments. how should we do this?
$f_\theta = \frac {1}{\theta}, 0<x< \theta $
Any hint or idea?
Comment: Please don't post homework-style questions without marking with the `self-study` tag (and following the guidelines at the [tag wiki](http://stats.stackexchange.com/tags/self-study/info)).
Comment: @Alecos Quite so; I do understand that, but if you found my comment unclear, please consider my second sentence to mean "Why insist on using this method of moments?"
Comment: @NickCox, this is extracted from this book ?
Comment: Sorry, but I don't understand your comment. I just gave two references; no more.
Comment: You can solve $\bar{x} = E(X)$ for $\theta$.
Comment: As @ocram hints, doubling the mean is one way to go here. Why insist on the method of moments? Is this an exercise? There are many approaches to this famous problem.
Comment: @NickCox Doubling the mean _is_ Method of Moments here.
Comment: @NickCox Now that is interesting! I hope you will have the time to post something more elaborate on the matter.
Comment: There was a treatment in E.T. Jaynes' book, _Probability Theory: The Logic of Science_ Cambridge U.P. 2003 He (rather characteristically) ignores previous work in different styles, e.g. Leo A. Goodman. Serial number analysis. _Journal, American Statistical Association_ 47: 622-634, 1952.
Answer: The pdf of the uniform distribution $U[0,\theta]$ is
$$
f(x) =
  \begin{cases}
   \dfrac{1}{\theta}, &  0\leq x \leq \theta \\
   0,       & \mathrm{otherwise}
  \end{cases}
$$
Hence the first population moment is
$$
\mu_{1} = \mathrm{E}(X)=\int_{0}^{\theta}\frac{x}{\theta}\,\mathrm{d}x = \frac{\theta}{2}
$$
The first sample moment is
$$
\hat{\mu}_{1} = \frac{1}{n}\sum_{i=1}^{n}X_{i} = \bar{X}
$$
Now we equate the sample moment to the population moment and solve for $\theta$:
$$
\hat{\mu}_{1} = \frac{\theta}{2}   \Longrightarrow \hat{\theta} = 2\times\hat{\mu}_{1} = 2\times \bar{X}
$$
So as @AlecosPapadopoulos said in the comments: Doubling the sample mean is the Method of Moments estimator for $\theta$.
More information about Method of Moments estimation and the uniform distribution can be found in this pdf document.
Comment: I think without the specific numerical result this is actually a very good answer.
Comment: @Glen_b Your first comment was spot-on, I think. I apologize for violating the policy, I meant no harm. In hindsight, it is obvious that this is a homework question but I was in a hurry when I wrote the answer and somehow I missed it. I deleted the numerical result now. Sorry again.
Comment: It looks fine now.


Appending dictionary with new keys and values in for loop

Question: I'm currently trying to loop through a dataframe for linear regression. After each iteration, I want to save the current column name and the resulting Adj. R squared value in a dictionary:
import statsmodels.api as sm

for columns in [x for x in var_sel.columns if x != 'price']:

    fit_d = {}

    Y = var_sel['price']

    X = var_sel[columns]

    X = sm.add_constant(X)

    model = sm.OLS(Y,X, missing = 'drop').fit()

    fit_d[columns] = model.rsquared

But when I print the dictionary it only outputs {'room_type_Shared room': 0.0003039648861731248} which is the last column of the dataframe. How do I append the dictionary with each iteration result?
Comment: declare a dictionary outside and append the value as the iteration progresses.
Answer: you have to declare the dictionary outside the for loop. in your above code, you are redeclaring the dictionary everytime when the loop runs.
import statsmodels.api as sm

fit_d = {}

for columns in [x for x in var_sel.columns if x != 'price']:

    Y = var_sel['price']

    X = var_sel[columns]

    X = sm.add_constant(X)

    model = sm.OLS(Y,X, missing = 'drop').fit()

    fit_d[columns] = model.rsquared


Template matching false positive

Question: I am using template matching on openCV java to identify if a subimage exist in larger image. I want to get coordinates of match only if exact subimage is available in larger image. I am using this code but getting a lot of false positive. Attached is the subimage and larger image. Subimage is not present in larger image but i am getting match at (873,715) larger image subimage
    public void run(String inFile, String templateFile, String outFile,
    int match_method) {
    System.out.println("Running Template Matching");

    Mat img = Imgcodecs.imread(inFile);
    Mat templ = Imgcodecs.imread(templateFile);

    // / Create the result matrix
    int result_cols = img.cols() - templ.cols() + 1;
    int result_rows = img.rows() - templ.rows() + 1;
    Mat result = new Mat(result_rows, result_cols, CvType.CV_32FC1);

    // / Do the Matching and Normalize
    Imgproc.matchTemplate(img, templ, result, match_method);
    // Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new
    // Mat());
    Imgproc.threshold(result, result, 0.1, 1.0, Imgproc.THRESH_TOZERO);
    // / Localizing the best match with minMaxLoc
    MinMaxLocResult mmr = Core.minMaxLoc(result);

    Point matchLoc;
    if (match_method == Imgproc.TM_SQDIFF
            || match_method == Imgproc.TM_SQDIFF_NORMED) {
        matchLoc = mmr.minLoc;
    } else {
        matchLoc = mmr.maxLoc;
    }
    double threashhold = 1.0;
    if (mmr.maxVal > threashhold) {
        System.out.println(matchLoc.x+" "+matchLoc.y);
       Imgproc.rectangle(img, matchLoc, new Point(matchLoc.x + templ.cols(),
                matchLoc.y + templ.rows()), new Scalar(0, 255, 0));
    }
    // Save the visualized detection.
    Imgcodecs.imwrite(outFile, img);
}

Answer: I am not familiar with OpenCV in Java but OpenCV C++.
I don't think following code is necessary.
Imgproc.threshold(result, result, 0.1, 1.0, Imgproc.THRESH_TOZERO);

The min/max values of 'Mat result' will be between -1 and 1 if you uses normalized option. Therefore, your following code will not work because your threshold is 1.0 if you use normalized option.
if (mmr.maxVal > threshold)

Also, if you use CV_TM_SQDIFF, above code should be
if (mmr.minVal < threshold)

with proper threshold.
How about drawing minMaxLoc before comparing minVal/maxVal with threshold? to see it gives correct result? because match at (873,715) is ridiculous.
Answer: Here is an answer of the same question: Determine if an image exists within a larger image, and if so, find it, using Python
You will have to convert the python code to Java
Comment: Thanks it was very helpful.! Solved my problem.

Template matching false positive


Startup services are not getting started in CENTOS

Question: I deployed my project on a Shared Hosting that has Root access the Server in picture is CENTOS
now although I have defined the service to start on boot it not getting started
chkconfig --level 35 thin.startup on

chkconfig --list | grep 'thin'
thin.startup    0:off   1:off   2:off   3:on    4:off   5:on    6:off

Here the script look like the script is stored under /etc/init.d/thin.startup
#!/bin/sh
#
#
# network Bring thin server up
#
# chkconfig: 35 20 80
# description: Starts and stops the thin Server and
#
#
# See how we were called.

thin -C /home/perwe100/public_html/1001/fedena-v2.3-bundle-linux/config/fedena.yml start

Not sure what is going wrong since I can find anything in boot.log and chkservd.log
am I missing something
Btw I can see the symlink present in /etc/rc3.d/ and /etc/rc5.d/
S20thin.startup@
Any one has an idea what I'm doing wrong
I want the script to start server on REBOOT
Answer: A couple of things you might need to check -
1 - you enabled thin for run levels 35, make sure your server is running in either run level 3 or 5. If not you might need to enable it for additional run levels. Although a CentOS server is most likely to run in run level 3 or 5, just double check it.
       runlevel
2 - Specify the full path to the thin binary.
something like this -
DAEMON=/fullpathhere-to-binary-here/bin/thin
$DAEMON -C /yml-path-here/.yml start
3 - Before adding it to a start up script, confirm that the script works fine from the command line -
  thin -C /home/perwe100/public_html/1001/fedena-v2.3-bundle-linux/config/fedena.yml start

Answer: Init scripts are a bit more complex than your script. Check out here: http://werxltd.com/wp/2012/01/05/simple-init-d-script-template/
If you didn't want to write a complex init script than you can put your stuff into /etc/rc.d/rc.local see: http://www.centos.org/docs/5/html/5.1/Installation_Guide/s1-boot-init-shutdown-run-boot.html
Comment: Good to know this but I cant see it working either  not working added the script `/usr/local/bin/thin -C /home/perwe100/public_html/1001/fedena-v2.3-bundle-linux/config/fedena.yml start` when added in `/etc/rc.d/rc.local` any other solution my friend
Comment: Try /etc/rc.local
Comment: `/etc/rc.local -> rc.d/rc.local*` symlink already added as mention above
Comment: You should have the simplink /etc/rc?.d/S99local to ../rc.local on your desired runlevel. It is not by default. See the answer at: http://serverfault.com/questions/475568/centos6-etc-rc-d-rc-local-not-running-at-boot-why


Exact link of vertical tabs

Question: I am using Field Group.
With 2 Vertical Tab, 'Step 1' and 'Step 2'.
I want to put a link "NEXT" on 'Step 1' that should open 'Step 2', same a back link on 'Step 2' that should go back to 'Step 1'.

I tried different combinations with Multipage but did not work here. How can I do this? I can put text but I don't know how to get the link of the other tabs directly.
Comment: As far as i remember, there is no such thing as  "link to tab", because Field Group's tabs are just like Form API vertical tabs: on one page, and switching them happens with JavaScript. If so, you need to script your "next" and "previous" links to switch tabs, and in that case URL in these links does not really matter anyway.
Answer: Just add the ID of the pane (fieldset) to the URL as a fragment, e.g.
http://example.com/node/[ID]/edit#edit-metatags

Assuming metatag is installed, that code will open the metatags tab directly on page load.
An example for core might be:
http://example.com/node/[ID]/edit#edit-options

For the "Publishing options" tab.

Exact link of vertical tabs


The isomorphic between rings

Question: Suppose $\Gamma$ is a finite group ,$R$ is a commutative ring with $1$.
Then the set of maps between $\Gamma$ and $R$ become a commutative ring . The zero element is the zero map ,the identity is the map which maps all $g\in \Gamma$ to $1$ .We denote the ring as $R^{\Gamma}$. From one note I see that $R^{\Gamma}$ is isomorphic to $\Pi_{g\in\Gamma}R$
My question is what is the $\Pi_{g\in\Gamma} R$? I don't know it is meaning.
And then why they are iso morphic ?
Thank you very much.
Comment: Do these maps respect structure? What kind of structure do they preserve?
Comment: If you just consider 'all' map, then the group structure is not used. Can view Gamma as a purly set
Comment: You can also imbue $R^\Gamma$ with a ring structure with a different multiplication using the group operation, but that multiplication might not be commutative.  This ring is still isomorphic to the product of R's as a module, not as a ring.
Answer: It is immaterial that $\Gamma$ is a group.
If $J$ is a set, then $\displaystyle\prod_{j\in J} R$ is the direct product of $|J|$ copies of $R$.
One of the concrete definitions of directed product is exactly the set of functions $J\to R$ with ring operations defined pointwise. The set of these functions is usually denoted $R^J$.
Comment: Thank you very much. I got it . I thougt it is might be important that $\Gamma$ is a group.
Comment: As a side note, it's important that we're taking all maps $\Gamma \to R$ of sets. If we restrict ourselves to homomorphisms of groups we won't necessarily get the ring structure.
Comment: Homomorphisms from any group to a ring is (obviously) a ring.

The isomorphic between rings


How do we go from Exp distribution to Gamma distribution?

Question: I was reading a proof on a paper online and he said that the exponential is a special case of the Gamma distribution, how's that?
Answer: This is really a lazy question, you can get your answer easily by doing a simple search on google.
Anyway, the Exponetial distribution is related to a lot of other distributions: https://en.wikipedia.org/wiki/Exponential_distribution#Related_distributions
Comment: This should be a comment, link-only answers are frowned upon.
Comment: @JuhoKokkala I'm sorry, I didn't know that.


Padrão para tipificar erros/exceções?

Question: Até onde sei, JavaScript não tem tipificação de erro.
Em C# e Java, e possível fazer coisas do tipo:
try {
    /* .. snip .. */
} catch (FooException foo) {
    /* .. snip .. */
} catch (BarException bar) {
    /* .. snip .. */
} catch (NotEnoughCoffeException nec) {
    /* .. snip .. */
} /* etc. */

E assim damos um tratamento de erro diferente para cada tipo de exceção.
Em javascript, o melhor que temos é:
try {
    /* .. snip .. */
} catch (couldBeAnything) {
    /* dize-me com quem erras e te direi quem és */
}

E o que é pior, não tem nem tipagem de pato  que ajude nessa hora.
Quando temos algum código em JavaScript que pode falhar de várias formas diferentes... Existe algum padrão de design, alguma metodologia para identificar o que ocorreu? Alguma forma de inserir um código de erro na exceção, por exemplo?
Answer: Existem as exceções condicionais (semelhante ao que terá em C# 6) que é até mais flexível que isso, você pode filtrar qualquer coisa:
try {
    myroutine(); // pode lançar umas das três exceções abaixo
} catch (e if e instanceof TypeError) {
    // código que manipula a exceção TypeError
} catch (e if e instanceof RangeError) {
    // código que manipula a exceção RangeError
} catch (e if e instanceof EvalError) {
    // código que manipula a exceção EvalError
} catch (e) {
    // código que manipula exceções não especificadas
    logMyErrors(e); // passa o obejto da exceção para um manipular
}

Coloquei no GitHub para referência futura.
Neste caso específico a verificação (a condição), que é basicamente um if normal, é em cima do tipo da exceção através do instanceof. Então você captura a exceção apenas se ela for uma instância daquele tipo especificado no if de cada catch.
Não é um recurso padrão e não está disponível em todas as implementações do EcmaScript, então use por conta e risco. E o risco é grande. Não é algo recomendado.
Você pode obter resultado semelhante de forma padrão:
try {
    myroutine(); // pode lançar umas das três exceções abaixo
} catch (e) {
    if (e instanceof TypeError) {
       // código que manipula a exceção TypeError
    } else if (e instanceof RangeError) {
       // código que manipula a exceção RangeError
    } else if (e instanceof EvalError) {
       // código que manipula a exceção EvalError
    } else {
       // código que manipula exceções não especificadas
       logMyErrors(e); // passa o obejto da exceção para um manipular
    }
}

Fonte: MDN
Answer: Para o tratamento de erros e exceções como você exemplificou muito bem em sua pergunta, pode ser visto nesse link: Tratamento de exceções aonde expõe os tipos de erros e de construtores de objetos de erro.
Em minhas pesquisas puder encontrar também referencias com relação a tratamento de exceções para a windows store que pode ser visualizado nesse link :Tratamento global de exceções

Padrão para tipificar erros/exceções?


How can I limit the winston log files to a specific number

Question: I am thinking of using the log rotation feature of Winston. Is there any way to limit the number of log files. For example if I am rotating files daily, is there a way to specify I want to keep only logs for last three days ?
Comment: *`maxFiles`: Limit the number of files created when the size of the logfile is exceeded.*
Comment: That's great, reading thru the doc now :) thanks !
Answer: From the comments - @Aleksandr M
maxFiles is that property.
It could read like this:
<code>dailyRotateFile: {
    colorize: false,
    timestamp: true,
    datePattern: '.yyyy-MM-ddTHH-mm',
    filename: filename,
    maxFiles: 5,
    maxsize: 100000000,
    json: false
}
</code>


Verificar double - Java

Question: Não estou conseguindo fazer esta verificação já tentei de tudo, mas sempre me da este erro:

java.lang.NumberFormatException: Invalid double: ""

Se alguem poder ajudar agradeço.
package com.calculadora;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private Button btncalc, btnlimpar;
    private AppCompatEditText edn1, edn2;
    private AppCompatTextView txtResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        btncalc = (Button) findViewById(R.id.calcular);
        btnlimpar = (Button) findViewById(R.id.limpar);

        edn1 = (AppCompatEditText)findViewById(R.id.n1);
        edn2 = (AppCompatEditText)findViewById(R.id.n2);

        txtResult = (AppCompatTextView)findViewById(R.id.result);

        btncalc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                double n1 = Double.parseDouble(edn1.getText().toString());
                double n2 = Double.parseDouble(edn2.getText().toString());
                double res = (n1*2 + n2*3) / 5;

                if(res >= 6){
                    txtResult.setText("Voce Foi Aprovado Parabens Sua nota é: " + res);
                    txtResult.setTextColor(Color.parseColor("#3F51B5"));
                    edn1.setText("");
                    edn2.setText("");

                }else if(res < 6){
                    txtResult.setText("Voce Foi Reprovado Estude Mais da Próxima Sua nota é: " + res);
                    txtResult.setTextColor(Color.parseColor("#F44336"));
                    edn1.setText("");
                    edn2.setText("");

 /*Linha Com Erro é essa*/                   }else if(TextUtils.isEmpty(edn1.getText().toString()) && TextUtils.isEmpty(edn2.getText().toString())) {
                        AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                        dialog.setTitle("Aviso");
                        dialog.setMessage("Campo Vazio!");
                        dialog.setNeutralButton("OK", null);
                        dialog.show();
                    }

                }
            });

        btnlimpar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edn1.setText("");
                edn2.setText("");
                txtResult.setText("");
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if(id == R.id.action_sobre){
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setTitle("Sobre o App");
            dialog.setMessage(R.string.mensage);
            dialog.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent it = new Intent();
                    it.setData(Uri.parse("http://www.facebook.com/diogosilvam"));
                    startActivity(it);
                }
            });
            dialog.show();

        }

        return super.onOptionsItemSelected(item);
    }
}

XML:

<include
    android:id="@+id/toolbar"
    layout="@layout/toolbar" />

<LinearLayout

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/toolbar"
    android:padding="10dp">

    <android.support.v7.widget.CardView

        android:layout_width="match_parent"
        android:layout_height="320dp"
        android:layout_marginTop="50dp"
        app:cardBackgroundColor="#fff"
        app:cardCornerRadius="4dp"
        app:cardElevation="4dp">

        <ImageView
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="5dp"
            android:src="@drawable/logo" />

        <android.support.v7.widget.AppCompatTextView
            android:textStyle="bold"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:paddingLeft="48dp"
            android:text="Preencha as suas notas para calcular sua média"
            android:textColor="#000"
            android:textSize="18sp" />

        <android.support.v7.widget.AppCompatTextView
            android:textStyle="bold"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="60dp"
            android:paddingLeft="14dp"
            android:text="N1 (0-10)"
            android:textColor="#000"
            android:textSize="18sp" />

        <android.support.v7.widget.AppCompatEditText
            android:textStyle="bold"
            android:id="@+id/n1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="90dp"
            android:hint="0.0"
            android:numeric="decimal"
            android:paddingLeft="14dp"
            android:textColor="#000"
            android:textColorHint="#919191"
            android:maxLength="3"/>

        <android.support.v7.widget.AppCompatTextView
            android:textStyle="bold"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="130dp"
            android:paddingLeft="14dp"
            android:text="N2 (0-10)"
            android:textColor="#000"
            android:textSize="18sp" />

        <android.support.v7.widget.AppCompatEditText
            android:textStyle="bold"
            android:maxLength="3"
            android:isScrollContainer="false"
            android:id="@+id/n2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="160dp"
            android:hint="0.0"
            android:numeric="decimal"
            android:paddingLeft="14dp"
            android:textColor="#000"
            android:windowSoftInputMode="adjustPan"
            android:textColorHint="#919191" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                android:textStyle="bold"
                android:id="@+id/calcular"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="12dp"
                android:layout_marginTop="210dp"
                android:layout_weight="1"
                android:background="@color/colorPrimary"
                android:elevation="4dp"
                android:stateListAnimator="@anim/btn_anim"
                android:text="Calcular" />

            <Button
                android:textStyle="bold"
                android:id="@+id/limpar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="12dp"
                android:layout_marginTop="210dp"
                android:layout_weight="1"
                android:background="@color/colorPrimary"
                android:elevation="4dp"
                android:stateListAnimator="@anim/btn_anim"
                android:text="Limpar" />
        </LinearLayout>

        <android.support.v7.widget.AppCompatTextView

            android:textStyle="bold"
            android:id="@+id/result"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="270dp"
            android:paddingLeft="14dp"
            android:text="Resultado"
            android:textColor="#000"
            android:textSize="18sp" />
    </android.support.v7.widget.CardView>
</LinearLayout>

Comment: O erro ocorre porque você está passando um valor vazio de string para o parseDouble, e ele não consegue converter.
Comment: Em que linha do código estoura essa exceção?
Comment: Linha 64 amigo!
Comment: E como vamos saber qual é a linha 64 no código? Seria interessante você apontar na pergunta que linha é essa.
Comment: Poste o xml também, acho que o problema está na hora de recuperar os valores da view, com o findViewById.
Comment: Já coloquei Da uma olhada ai
Comment: Isso o que eu quero é que ele verifique quando for vazio me exiba um Alert de que o editText Não tem nenhum valor
Comment: Então você está fazendo errado. Primeiro faça o if que verifica se os campos estão vazios, depois tente efetuar o parse. Você está primeiro tentando fazer o parse e depois checar se está vazio.
Comment: Ok Vou tentar aqui wlw
Comment: Como marcar como resolvido?
Comment: Pra marcar como resolvido precisa de uma resposta. Você mesmo pode responder sua pergunta.
Comment: Galera Agradeço os comentario mais eu já consegui wlw mesmo!!!
Comment: @DiogoSilva Você pode responder a sua pergunta dando a solução para ela, e não apenas dizendo que resolveu, rs.. A solução é importante para caso alguém chegue nesse tópico com a mesma dúvida que você saiba aprenda como resolver o problema. Depois de respondida você pode marcá-la como aceitar clicando no ✓ ao lado dela, deixando ele verde.
Answer: Você pode utilizar a função antes de fazer o Double.parseDouble para verificar se a String pode ser convertido para Double.
boolean isDouble(String str) {
    try {
        Double.parseDouble(str);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

Verificar double - Java


Lock the concurrent reading row table

Question: I have a table called "Consecutives" in SQL Server, in this table a number is stored.
I have another table "Data", where they store the records and one of the columns is a number, this number is take from "Consecutives" table.
To assign the consecutive, I read the "Consecutives" table, then increase the value by 1, and save.
The problem is that when multiple threads are executed, it does not read the current value of "Consecutives" and repeats the numbers.
How can I block the row of the table so that only one thread can read and update it at the same time and thus avoid repeating the numbers?
Comment: Hi Andres! Try using the IDENTITY property: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property?view=sql-server-2017
Answer: It is best to not have this requirement - because it means that all transactions trying to insert to data are serialized and blocked until previous ones commit or rollback.
Ideally you should use IDENTITY or SEQUENCE instead.
But neither of these guarantee consecutivity and if this is a "must have" then the best way is to do an atomic update and read the value at the same time.
Suppose you have the following setup
CREATE TABLE Consecutives
  (
     Scope  VARCHAR(20) PRIMARY KEY,
     Number INT
  );

INSERT INTO Consecutives
VALUES     ('Data',
            76);

Then code to increment the value and read the result whilst blocking other transactions is below.
DECLARE @Number INT;

UPDATE Consecutives
SET @Number = Number+=1
WHERE Scope = 'Data';

SELECT @Number

This uses the SET @variable = column = expression semantics of UPDATE to assign the post update column value to the variable.
This should be in the same transaction as the insert to Data if you want to ensure no gaps (at least in the absence of any deletes or updates to that column)

Lock the concurrent reading row table


Legitimate IV for panel?

Question: In a panel regression using fixed effects, is it correct to use an instrument that does not vary by year?  To use an old but simple example, Angrist and Kruger 1991 use quarter of birth as an instrument for education.  If one had access to similar data that was in panel form, is it still correct (and I don't mean specifically quarter of birth, I know there are problems with the validity of this IV) to use quarter of birth (same for each respondent regardless of panel wave) as an instrument in the panel IV regression?  Why or why not?
Answer: Since the instrument does not vary across years, it would be perfectly related to a linear combination of the fixed effects in the model. This would lead to a lack of identification.
In a panel, a better bet would be to employ a difference-in-difference approach, so long as treatment/the endogenous variable is changing across time. The individual fixed effects control for non-time varying unobservable characteristics (e.g., IQ). Year/time period fixed effects control for non-individual varying unobservable characteristics (e.g., the state of the labor market). Any endogeneity problem would stem from time and individual varying omitted variables.
Comment: My endogenous and treatment var's change over time, but my treatment is an ordered variable.  Is it possible to use the DiD method with a non-binary treatment (ie a 'dose' treatment)?  I know I could choose a value of my ordered treatment and generate a 1/0 var, but then I lose information.

Legitimate IV for panel?


Properties of orthogonal vectors.

Question: I am trying to find all unit vectors orthogonal to $\vec{v}=\langle{3,4,0}\rangle$.

So, in this pursuit, I considered the possibility of a property of vectors:
For a given non-zero vector $\vec{v}=\langle{a,b,c}\rangle$ there exists an orthogonal vector $\vec{u}=-\langle{\frac{1}{a}, \frac{1}{b}, \frac{1}{c}}\rangle$.

Is this true? I think I may be able to use this conclusion to aid in my prime objective.
Answer: No, your assertion is not true: $\left<\vec{v},\vec{u}\right>$ is the sum of the products of their entries, i.e., $a\cdot(-1/a)+b\cdot(-1/b)+c\cdot(-1/c)=-3\neq 0$.
Trivially, the vector $\left<0,0,1\right>$ is orthogonal to your vector. A second vector can be found via using the cross product $\left<3,4,0\right>\times\left<0,0,1\right>$ and normalization. For references, see also this and this post.
Note that the two vectors you thus got span a two-dimensional space. Every vector in this two-dimensional space is orthogonal to your vector.

Properties of orthogonal vectors.


Run JavaScript after Ajax Call

Question: I have a form file:
namespace Drupal\h_scheduler\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use \Drupal\node\Entity\Node;

class DayAddEntries extends FormBase {

  public counter = 0;

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'hs_day_add_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form_state->setCached(FALSE);

    $form['#attached']['library'][] = 'h_scheduler/form_actions';

    /*...More fields....*/

    /* Special */
    $form['specials'] = array(
      '#type' => 'fieldset',
      '#tree' => TRUE,
      '#title' => t('Specials'),
      '#prefix' => '
',
      '#suffix' => '
',
    );

    if ($this->counter) {
      for ($i = 1; $i <= $this->counter; $i++) {
        $form['specials']['special'.$i] = array(
          '#type' => 'fieldset',
          '#title' => t('Special ') . $i,
          '#tree' => TRUE,
        );
        $form['specials']['special'.$i]['field'] = array(
          '#type' => 'number',
          '#title' => t('Every'),
          '#title_display' => 'before',
        );
        $form['specials']['special'.$i]['field'] = array(
          '#type' => 'textfield',
          '#title' => t('Prefix'),
          '#title_display' => 'after',
        );
      }
    }
    $form['specials']['operations']['#type'] = 'actions';
    $form['specials']['operations']['add_special'] = array(
      '#type' => 'button',
      '#value' => $this->t('Add special'),
      '#ajax' => array(
        'callback' => '::ajaxAddSpecial',
        'wrapper' => 'specials',
      ),
    );

    /* Not working */
    $form['specials']['operations']['remove_special'] = array(
      '#type' => 'button',
      '#value' => $this->t('Remove special'),
      '#ajax' => array(
        'callback' => '::ajaxRemoveSpecial',
        'wrapper' => 'specials',
      ),
    );

    /* Submit */
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
    );

    $this->counter++;

    return $form;
  }

  /**
   * Increments the number of specials to have
   */
  public function ajaxAddSpecial($form, FormStateInterface $form_state) {
    return $form['specials'];
  }

  /**
   * Decrements the number of specials to have
   */
  public function ajaxRemoveSpecial($form, $form_state) {
    $this->counter -= 2;
    return $form['specials'];
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    /* Do stuff */

  }
}

jQuery:
jQuery(function($) {
  $('#edit-specials .fieldset-wrapper .fieldset-wrapper, #edit-regular .fieldset-wrapper').addClass('entry-wrapper').each(addStyleClasses);

  function addStyleClasses() {
    console.log('hi');
    $(this).children('.form-item')
      .addClass(function() {
        var regex = /form-item-\S+-(\S+)/;
        return regex.exec($(this).attr('class'))[1];
      })
      .not('.every').wrapAll('
');
  }

});
I'm able to add a new "special" item, but when I do it appears wacky.
This is because I've styled the form using a jQuery function that adds classes and wraps elements. However, that function does not run when the form['specials'] is rebuilt.
My question, how do I run a JS function after an ajax call?
Comment: Use Drupal.behaviors and jquery once in your code and you'll be fine.
Comment: Can you please post your jQuery code? The problem is likely to be there.
Comment: @NoSssweat Added JS. I can confirm that my jQuery code works the on load, but when I rebuild the `form['specials']` the JS doesn't apply to it.
Comment: @IvanJaros Thanks, I'll check it out and get back to you.
Comment: @IvanJaros I solved it using Drupal.behaviors and jquery once! Thanks, and if you'll add an answer, I'll accept it!
Comment: Related: https://www.drupal.org/docs/drupal-apis/ajax-api/core-ajax-callback-commands
Answer: This has a solution on Stackexchange here already, but:
This would be your full javascript file:
(function ($, Drupal) {
  Drupal.behaviors.myModuleName = {
    attach: function (context, settings) {
      // I am doing a find() but you can do a once() or whatever you like :-)
      $('#element', context).find('.sub-element').each(function () {
        // Do your thing here
      });
    }
  };
})(jQuery, Drupal);

Note on the question's js: I would say when calling a function like your addStyleClasses() it would be more reliable to explicitly pass your target element in the function call than using $(this) in there.

Run JavaScript after Ajax Call


How to give an 'editor' role rebuild/clear cache permission?

Question: I'm setting up an "editor" role for a D8 site. I noticed there's no "Flush all caches" in the Tools menu. I don't see any permission setting related to caches. How to enable cache clearing/cache rebuilding for non-admins?
Comment: On all projects I have worked so far there was always a custom route with a button to do that due to "administer site configuration" is just too powerful to give to editor or any non-superadmin role.
Comment: Agreed that "admin site config" is too powerful of a permission. Have you seen any discussion on why clearing cache isn't broken out to it's own permission?
Answer: I'd like to mind the following answer to a similar feature request on DO:

I kind of disagree with this because of the that shouldn't be
  necessary in the first place. With cache tags, any change that an
  editor can make should automatically invalidate all relevant caches.
  Anything else is a bug IMHO.

Nevertheless in real world sometimes it may be necessary to have other roles than the one with administer site configuration being able to rebuild caches.
Basically all you need to do is to build a trigger of some kind (button, route etc.) and let it fire drupal_flush_all_caches(). Have a look at the Devel module for a great example of this approach.

Since I was in need of this myself – which was why I came here in the first place – I finally built a small module and published it on DO. It adds its own permission and places a button on the admin toolbar from which every user with the new permission is now able to flush all caches:
https://www.drupal.org/project/rebuild_cache_access
Answer: To access this, they would need the administer site configuration permission.
From system.routing.yml:
system.performance_settings:
  path: '/admin/config/development/performance'
  defaults:
    _form: 'Drupal\system\Form\PerformanceForm'
    _title: 'Performance'
  requirements:
    _permission: 'administer site configuration'


If $m$ is the Lebesgue measure, $f\in L^1(m)$ and define $d\nu = f dm$, show $\nu$ is a regular measure.

Question: My professor mentioned briefly during the class, that if $\nu$ is defined as above, then $\nu$ is a regular measure. The first criterion - every compact set has a finite $\nu$ measure is easy to show, but I have been struggling with the second piece.
My ultimate goal is to show: $\nu(E) = \inf \{\nu(U); E\subset U, U \text{open}\}$.
My thought is that since $m$ is regular

Folland theorem 1.18 implies for all $m$-measurable set $E$, $m(E) = \inf \{m(U); E\subset U, U \text{open}\}$

and the way that $\nu$ is defined, I can use

Folland corollary 3.6 implies if $f\in L^1(m)$, for every $\epsilon>0$, there is $\delta >0$ such that $|\int_E fd\nu|<\epsilon$ whenever $m(E)<\delta$.

to somehow connect $\nu(E)$ and $\inf \{m(U); E\subset U, U \text{open}\}$. However, when I try to write this, I had a hard time connecting the quantifiers and making things work. Thank you for the help!
Update: so I read over the paragraph on Folland that proves the statement given that $f\in L^+\cap L^1_{loc}$ and understood the argument. May I ask if the result holds for $f\in L^+\cap L^1_{loc}(m)$, can I prove it holds for $f\in L^1(m)$ using linearity?
Answer: $d\nu = f dm$ implies $$\nu(E) =\int_Efdm$$
Then $\nu$ is a signed measure (need not be non negative)
If $f\ge 0$ then $\nu$ is a measure.
Then rest of the proof follows from the properties of Lebesgue measure and Lebesgue integral.


Best practice while saving data in HttpApplication.Application

Question: So I have a web service that returns data from a certain data source.
Some of the data retrievals takes really long (>15 sec) which is unacceptable while serving data to a web page via ajax calls.
I was thinking that I can cache the data in the following method:
Run a worker thread in Global.asax that retrieves deltas every X minutes/hours and updates a variable, which will then be returned in the web service. The best solution that came to my mind was saving the data in the Application dictionary.
Basically my question is, should I do it? (We are talking about data that can exceed 100MB) Are there any ramifications doing it? If so, what solution will be best?
Answer: You're probably better off using caching for this case, as it will automatically be flushed out if the server is running low on memory.
See 'Application Considerations' here:  https://msdn.microsoft.com/en-us/library/ms178594.aspx
Comment: Seems a good enough answer, thanks! However, which caching manager do you recommend? Is there a built-in cache manager? A short google search yielded cachemanager.net. Is it any good?
Comment: Yup.  ASP.Net includes an output cache which is pretty straight forward.  You can read more here:  https://msdn.microsoft.com/en-us/library/xsbfdd8c.aspx
Answer: It really depends on the nature of your data. Caching is the perfect solution for the data that doesn't change very often and is somewhat static.
You can also use a short time caching for the data that is dynamic (changes often), but it is ok if user is using the data that is a little bit old.
.Net framework has a CacheManager class, which lets you to define expiry for the cached data.
I'd say instead of reading ALL data and saving them in the memory, using .Net cache manager, just cache the data that is requested for x minutes.
You can write your own code and get very creative on when and how to refresh your cached data. For example, you could add a counter property to the cached data and count how many time the data was accessed from cache, then either refresh the data of expand the lifetime of the cached data by extending its expiry timestamp.
Take a look at this link for start:
http://cachemanager.net/Documentation/Index/cachemanager_getting_started
Comment: Was just looking at cachemanager.net! Anyway, I have to read ALL the data and keep it updated, because I display ALL the data to the user. It's not exactly 'static'. Also, the data is assumed to not be changed 'behind the scenes' so every change of data can trigger a re-retrieval or a cache update.
Comment: Still cache manager is a good choice. Your server will require a lot of memory though. You can still use the date and time stamp of the last update or last load to reduce the DB calls and improve the performance.
Comment: I have used the cachemanger class in an enterprise application to cache the sessions for over 10,000 concurrent users and it worked very well for us.  (we were saving our sessions in DB, in order to use them in a server farm)


Partial sums of trig functions identity

Question: Using the fact that
$$\sum\limits_{k=0}^{n}z^k=\frac{1-z^{n+1}}{1-z}$$
I want to find the partial sum for multiples of the trig funtions, ie. $1+\cos(\theta)+\cos(2\theta)+\cdots+\cos(n\theta)$ and $\sin(\theta)+\sin(2\theta)+\cdots+\sin(n\theta)$ by substituting in $z=e^{i\theta}$
By substituting and expanding, the LHS becomes
$$1+\cos(\theta)+i\sin(\theta)+\cos(2\theta)+i\sin(2\theta)+\cdots+\cos(n\theta)+i\sin(n\theta)$$
and the right hand side becomes
$$\frac{1-(e^{i\theta})^{n+1}}{1-e^{i\theta}}=\frac{1-e^{(n+1)\theta i}}{1-e^{i\theta}}=\frac{1-(\cos(n\theta+\theta)+i\sin(n\theta+\theta))}{1-(\cos(\theta)+i\sin(\theta))}$$
Taking real coefficients, this becomes
$$1+\cos(\theta)+\cos(2\theta)+\cdots+\cos(n\theta)=\frac{1-\cos(n\theta+\theta)}{1-\cos(\theta)}$$
But apparently the result for $\cos$ is
$$\frac{1}{2}+\frac{\sin(n+\frac{1}{2})\theta}{2\sin(\theta/2)}$$
and I can't get to this from what I've got.
Answer: Hint
$$\frac{1-e^{(n+1)\theta i}}{1-e^{i\theta}}=\frac{e^{i\theta\frac{n+1}2}}{e^{i\theta/2}}\frac{e^{-i\theta\frac{n+1}2}-e^{i\theta\frac{n+1}2}}{e^{-i\theta/2}-e^{i\theta/2}}=e^{in\theta/2}\frac{\sin(\theta(n+1)/2)}{\sin(\theta/2)}$$
and use the trigonometric relation
$$\cos(a)\sin(b)=\frac12(\sin(a+b)+\sin(a-b))$$
Answer: You cannot take the real component of a complex fraction by taking the real of the numerator and dividing it by the real of the denominator.
Instead, multiply top and bottom by $(1-\cos\theta) -i\sin\theta$ to make the denominator real and then take the real of the resulting fraction.
Thus, to go from your result to the given solution, calculate (making use of various trigonometric sum of angle and double angle identities)
$$\Re\left(\frac{(1-\cos(n+1)\theta+i\sin(n+1)\theta)(1-\cos\theta-i\sin\theta)}{2(1\color{red}{-\cos\theta})}\right)\\=\frac{1}{2}+\frac{\color{blue}{\sin(n+1)\theta\sin\theta+\cos\theta\cos(n+1)\theta}-\cos(n+1)\theta}{2(1\color{red}{-1+2\sin^2(\theta/2))}}\\=\frac{1}{2}+\frac{\color{blue}{\cos n\theta}-\cos(n+1)\theta}{4\sin^2(\theta/2)}\\=\frac{1}{2}+\frac{2\sin(\theta/2)\sin((n+1)\theta/2)}{4\sin^2(\theta/2)}\\=\frac{1}{2}+\frac{\sin((n+1)\theta/2)}{2\sin(\theta/2)}$$

Partial sums of trig functions identity


node.html.twig gets cached while other templates do not

Question: I disabled cache with the command

drupal site:mode dev

I have overridden html.html.twig and node.html.twig.
If I change something on html.html.twig and refresh the page, the changes take place.
If I change something on node.html.twig and refresh the page, the changes do not appear, unless I also clear the cache or edit the node.
If I open the same page with a different browser, changes do take place, but if I make another edit and refresh, it won't work.
So I thought of some kind of browser caching, but clearing the caches in Chrome doesn't help.
How can I force Drupal to re-read node.html.twig without clearing the caches or editing a node everytime?
Thanks!
Comment: thanks, un-commenting all the bins-related lines from example.settings.local.php and copying them over to default/settings.local.php solved the issue. If you can post your answer as an actual answer I will mark it as accepted.
Comment: seems like the cache is still populated. Is dynamic_page_cache module enabled on your Drupal site? Seems like it is and the cache bin wasn't nulled out with drupal site:mode command. Please have a look at sites/example.settings.local.php file and check if your sites/default/settings.(local.)php was modified accordingly.
Answer: drupal site:mode dev won't turn off all the caches. Tunning caching for dev purpose requires manual changes to the settings.(local.)php.
Open the example.settings.local.php file located in the sites directory and copy its content over to site's settings.(local.)php file.
Focus on the cache bins - in your case render and dynamic_page_cache.
$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

Comment: And don't forget to uncomment this line  `if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
   include $app_root . '/' . $site_path . '/settings.local.php';
 }` in your `settings.php`


Why are neural networks better at avoiding local minima?

Question: In simulated annealing, from my understanding, it is a process where it stochastically searches the whole landscape at the beginning for the global minima and then hones down on the best solution it can find. With neural networks, how does it do this when you set the weights only once and randomly. Changes fall straight into local minima with gradient descent. How does it get out of this and find a better solution?
Comment: I don't understand your premise. The standard approach to training a neural network (as opposed to a regression model) is backprop and gradient descent. This is explicitly a local optimization, and there is no guarantee that the solution is a global minimum. As a practical matter, these solutions are usually "good enough." The most relevant contrast to simulated annealing is that modern neural nets often have millions of parameters; I don't believe simulated annealing works well in a search space that large (but I might be wrong -- not a SA specialist).
Comment: All global optima are also local optima, but not all local optima are global optima. In optimization we're looking for local optima that are also global optima. We often use greedy optimization methods, which do not garuntee that the local optima found by the algorithm are also a global optima.
Comment: I suspect that the vanilla setup of a multilayer perceptron is more capable of being stuck in a local minima than simulated annealing (under random mutations to the solution).
Comment: There are many adjustments that are made to neural networks these days, including a paper I saw a while back where they used simulated annealing in the training of a neural network. Simulated annealing is a metaheuristic that can be combined with other optimization techniques, and many choices can be made on how a neural network is trained (some which may trade efficient convergence for less greed).
Comment: @Sycorax says Reinstate Monica  - I can see your point on how with high dimensional data, simulated annealing may not be very useful in some circumstances due to such a huge landscape. What i mean by my premise, is that you start at a point, which is the random weights- then from wherever it starts it's going to just move down into whatever (bowl) local minimum, it is in, where it can't escape. I can see how something like momentum can help- but this is more of an add-on, rather than how a NN works fundamentally.- this is what is confusing me
Comment: @Galen do you mean instead of random weights at the beginning they give it a better head start simulated annealing? -
Comment: @snackbob I think you're starting from the premise that neural networks must achieve a global minimum to be "good." But it happens to be the case that local minima are often "good enough," in the sense that the resulting models are very effective. Understanding why neural networks work this way, and characterizing just how different local and global optima are for NNs and other modern ML models, is an active area of research, so my summary here may be glossing over some important findings.
Comment: @snackbob No, not at all.
Comment: The bottom line is that neural networks are not inherently better at avoiding local-only optima compared to simulated annealing.
Answer: It's true that if a neural network uses regular gradient descent it will only be able to properly optimize convex functions. In order to address this, most neural networks use some variant on Stochastic Gradient Descent which introduces noise by considering fewer points so the algorithm can jump out of local minima. However, it's worth noting that there is no guarantee to find the global optima and this is usually used over simulated annealing because it is (typically) faster.
Comment: The neural network itself is really just a model (similar to how linear regression is a model) that uses an optimization algorithm to minimize some loss function. These algorithms you have suggested could indeed be used in conjunction with a neural network instead of using stochastic gradient descent and this has been tried in the past; however, there are issues associated with most of these algorithms that have favored stochastic gradient descent variations. Specifically, with simulated annealing, the space is too large to perform this in a reasonable amount of time.
Comment: I would recommend checking out this post: https://stats.stackexchange.com/questions/235862/is-it-possible-to-train-a-neural-network-without-backpropagation
Comment: why is it that they have been shown to be so good at optimization compared to other methods. If that is the case, surely other methods that actively try to escape local minima, ie, genetic algorithms, simulated annealing, would be hone in on a better solution purely by chance. With my current understanding, this defies logic, or at least it shows there is huge scope and potential for better methods to come.


I am getting a PDO error which seems related to the Media module

Question: After Drupal 8.8 upgrade media module is not working.
In admin media links are not working e.g /admin/content/media
Error :
The website encountered an unexpected error. Please try again later.

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'media' doesn't exist: SELECT COUNT(*) AS expression FROM (SELECT 1 AS expression FROM {media} base_table GROUP BY base_table.vid, base_table.mid) subquery; Array ( ) in Drupal\media\MediaListBuilder->getEntityIds() (line 158 of core/modules/media/src/MediaListBuilder.php).
Comment: After upgrading, Did you run /update.php?
Comment: Try uninstalling and reinstalling the media module.
Answer: it seems you have not done the update completely. one part of Drupal updating is Database updating.
there are some solutions to update it.

solution go to YOUR_WEBSITE_ADDRESS/update.php  the go through the steps.
solution if you have drush, run drush updb


Hooks called after installation profile is installed?

Question: I'm stuck writing an installation profile.
There are certain things that I want to do only after the installation is completed.
I analyzed top ten installation profiles and checked the documentation, but I couldn't find it. I might be missing something small though.
Is there such hook? If not, how can I execute something at the end of the installation?
Thanks!

UPDATE
I know for hook_install and hook_install_tasks, and they are not exactly what am I looking for.
They both are called during the installation. I want to execute code after the installation has been completed.
For example, setup Backup & Migrate schedules. If I do this using hook_install_tasks(), the cron run at the end of installation does not seem to work properly/in full, and I get errors when backup_migrate tries to write to private directory. Private directory is set up properly and if I just re-run the cron afterwards, it works as it should.
Comment: You can try to run `drupal_cron_run();` before the hook you want to call.
Comment: sounds like you need `hook_enable`
Answer: Move your post-installation hooks to a module/part-of-your-profile (that can implement any hook and move things around even after the system modules is installed).
That way you can overcome problems like custom block's BLOCK_VISIBILITY_LISTED not working on profile installation hook_install()?, and have a solid last installation step, that makes all your final configs.
bonus * why not even choose or make configs in that installation step's form_alter() ;)
Answer: Here's an example of a feature revert done at the end of the installation.
/**
 * Implements hook_install_tasks().
 */
function MYPROFILE_install_tasks($install_state){
  $tasks = array(
    'MYPROFILE_setup_cleanup' => array(
      'display_name' => st('Cleanup'),
      'display' => FALSE,
      'type' => 'normal'
    ),
  );

  return $tasks;
}

/**
 * Cleanup install task.
 */
function MYPROFILE_setup_cleanup() {
  features_revert();
}

Comment: Thanks for your message, but that's not what I am looking for exactly. I updated the question.
Comment: @Ivanhoe123 could you try setting the private files directory in a feature or in a install task? variable_set('file_private_path', 'mypath');
Comment: I'm setting it up in an install task actually; I create  the folder, set chmod and add `.htaccess`. However, I think that's not the issue.
Comment: Do you also setup file_default_scheme "Default download method"? Or maybe just execute this whole form :) https://api.drupal.org/api/drupal/modules%21system%21system.admin.inc/function/system_file_system_settings/7
Comment: Thanks again. I set everything manually, and I don't setup the file default scheme. I pasted the code I use [here](http://pastebin.com/wtwbdauY). I think it's not the main issue simply because private file system works properly after the installation.
Answer: Module Site pre-install and post-install hooks might just do what you need. It's installed as a library and registered with your installation profile. The module provides two hooks: hook_site_pre_install() and hook_site_post_install(). They are run before the installation tasks and then after Finished task.
From module page:

Sample Use Cases
Here are some scenarios where you'd want to use this approach:
You need to configure certain site settings before installing a module that requires those settings (hook_site_pre_install()).
  You need to modify user passwords, tweak menu paths, or adjust settings (such as the site name) that would otherwise be bashed if set in hook_install() in the installation profile (hook_site_post_install()).

I usually use it to e.g. enable Shield module in certain environments at the very end of the installation.
Answer: It's hooks
hook_install and hook_install_tasks
Comment: Thanks for your message, but that's not what I am looking for exactly. I updated the question.
Answer: You can add tasks to be run after the "Finished" task by implementing hook_install_tasks_alter().


Problema em capturar a posição do elemento quando existe um scroll em jQuery

Question: Estou com um problema quando elemento esta sobre o scroll do navegador e o jQuery não captura corretamente a posição, criei um simples Tab-bar e quando o tamanho é utra passado é colocado o scroll e neste momento, existe um efeito em baixo dos tab indicando a navegação, veja o código:

$(document).ready(function() {

  var origin = $('.md-tab>li'),
    activates = $('.md-tab>.slider'),
    whatTab = origin.outerWidth(),
    howFar;

  if (!activates.length) {
    return;
  }

  activates.css("width", whatTab);

  origin.each(function() {
    $(this).find('a').addClass('ripple');
  });

  origin.click(function() {
    whatTab = $(this).outerWidth();
    howFar = $(this).position().left;

    activates.css({
      'left': howFar,
      'width': whatTab
    });
  });

});
ul.md-tab {
  position: relative;
  padding: 0;
  white-space: nowrap;
  overflow-x: auto;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  -ms-box-shadow: 0 2px 5px rgba(0, 0, 0, .16), 0 2px 10px rgba(0, 0, 0, .12);
  -o-box-shadow: 0 2px 5px rgba(0, 0, 0, .16), 0 2px 10px rgba(0, 0, 0, .12);
  box-shadow: 0 2px 5px rgba(0, 0, 0, .16), 0 2px 10px rgba(0, 0, 0, .12);
}
ul.md-tab > li {
  position: relative;
  display: inline-block;
  height: 60px;
}
ul.md-tab > li > a {
  position: relative;
  display: inline-block;
  overflow: hidden;
  text-decoration: inherit;
  text-transform: uppercase;
  text-align: center;
  letter-spacing: .01em;
  font-weight: 500;
  height: 60px;
  line-height: 61px;
  margin-bottom: -8px;
  padding-left: 1.3em;
  padding-right: 1.3em;
}
ul.md-tab > li.slider {
  position: absolute;
  display: block;
  bottom: 0;
  left: 0;
  height: 4px;
  pointer-events: none;
  background-color: #ffeb3b;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
  -ms-transition: all 0.5s;
  -o-transition: all 0.5s;
  transition: all 0.5s;
}

Início

Card

Typography

Tables

Form

User Interface

Quando rola o scroll no final o jQuery não consegue capturar a posição corretamente somente no inicio do scroll.
Answer: Além da posição atual, você precisa somar o scrollLeft do parent no caso o UL pai.
howFar = $(this).position().left + $(this).parent().scrollLeft();

Caso o problema esteja ocorrendo com o scroll da tela em si, some o scroll da janela:
howFar = $(this).position().left + $(window).scrollLeft();

$(document).ready(function() {

  var origin = $('.md-tab>li'),
    activates = $('.md-tab>.slider'),
    whatTab = origin.outerWidth(),
    howFar;

  if (!activates.length) {
    return;
  }

  activates.css("width", whatTab);

  origin.each(function() {
    $(this).find('a').addClass('ripple');
  });

  origin.click(function() {
    whatTab = $(this).outerWidth();
    howFar = $(this).position().left + $(this).parent().scrollLeft();
    activates.css({
      'left': howFar,
      'width': whatTab
    });
  });

});
ul.md-tab {
  position: relative;
  padding: 0;
  white-space: nowrap;
  overflow-x: auto;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  -ms-box-shadow: 0 2px 5px rgba(0, 0, 0, .16), 0 2px 10px rgba(0, 0, 0, .12);
  -o-box-shadow: 0 2px 5px rgba(0, 0, 0, .16), 0 2px 10px rgba(0, 0, 0, .12);
  box-shadow: 0 2px 5px rgba(0, 0, 0, .16), 0 2px 10px rgba(0, 0, 0, .12);
}
ul.md-tab > li {
  position: relative;
  display: inline-block;
  height: 60px;
}
ul.md-tab > li > a {
  position: relative;
  display: inline-block;
  overflow: hidden;
  text-decoration: inherit;
  text-transform: uppercase;
  text-align: center;
  letter-spacing: .01em;
  font-weight: 500;
  height: 60px;
  line-height: 61px;
  margin-bottom: -8px;
  padding-left: 1.3em;
  padding-right: 1.3em;
}
ul.md-tab > li.slider {
  position: absolute;
  display: block;
  bottom: 0;
  left: 0;
  height: 4px;
  pointer-events: none;
  background-color: #ffeb3b;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
  -ms-transition: all 0.5s;
  -o-transition: all 0.5s;
  transition: all 0.5s;
}

Início

Card

Typography

Tables

Form

User Interface

Comment: Nossa eu pensava que o `jQuery` conseguia capturar a posição do elemento mas pelo seu código tem que mostrar para o `jQuery` que existe um scroll e no meu caso está na tela do navegador ou em outras palavras o `window` do `scrollLeft()`.


How to configure ckeditor for different toolbars?

Question: In D7 I would like to use ckeditor with a specific profile for a user role. The user is only allowed to use bulleted listed. How to do this?
I did the following:

Configured in drupal a ckeditor profile call "builder"
For a role say"Client" I added a text format say "Bullitsformat"
for a field in a content type "testfield" I configures user can choose own filter.

If I test the edit form no toolbar is displayed when user selects Bullitsformat.
What to do?
Comment: How did you set up the "Bullitsformat" so that it would only allow bulleted lists?
Comment: Configured the HTML filter, only allow
Answer: Found the solution to first add the bullitsformat and then edit the profile, so this profile is shown in the profile of the ckeditor.


jsTree Contextmenu get selected node id

Question: Hi I am currently having an issue with the jsTree Context menu.
I would like to grab the id of the selected node however I've looked at a number of solutions and none have worked. My code is below.
The function I have which uses tree.get_selected($node) does return an object of the selected node but I'm struggling to access the id parameter of the object. Below I used tree.get_selected($node).id but it says it's undefined but its clearly not when I look at the console.
Can anyone help as to where I'm going wrong?
$("#tree_1").jstree({
    "core" : {
    "themes" : {
        "responsive": false
    },
    // so that create works
    "check_callback" : true,
    'data' : {
        'url' : function (node) {
                if(node.id=='#') {
                    var id = 0;
                } else {
                    var id = node.id;
                }
                return 'organisation/getOrganisationLocations/'+id;
            }
        }
    },
    "types" : {
        "default" : {
            "icon" : "fa fa-folder icon-state-warning icon-lg"
        },
        "file" : {
            "icon" : "fa fa-file icon-state-warning icon-lg"
        }
    },
    "state" : { "key" : "demo3" },
    "plugins" : [ "dnd", "state", "types", "contextmenu" ],
    "contextmenu":{
    "items": function($node) {
            var tree = $("#tree_1").jstree(true);
            return {
                "Create": {
                    "separator_before": false,
                    "separator_after": false,
                    "label": "Create",
                    "action": function (obj) {
                        $node = tree.create_node($node);
                        tree.edit($node);

                        console.log(tree.get_selected($node).id);
                    }
                },
                "Rename": {
                    "separator_before": false,
                    "separator_after": false,
                    "label": "Rename",
                    "action": function (obj) {
                        tree.edit($node);
                    }
                },
                "Remove": {
                    "separator_before": false,
                    "separator_after": false,
                    "label": "Remove",
                    "action": function (obj) {
                        tree.delete_node($node);
                    }
                }
            };
        }
    }
});

Comment: Check this old post.

http://stackoverflow.com/questions/10481773/jstree-context-menu-selected-item/25115210#25115210
Answer: This approach worked for me:
$(node).attr('id')

Comment: can You provide the sample application treeview with CRUD with database?
Answer: Declare your id above the jstree declaration (at line 1, put var id;)
Then, in the data.url function, remove var from before each line that assignes to id.

jsTree Contextmenu get selected node id


Does domain extension affect seo?

Question: I am not sure if this is the right place to ask. However... does domain extension affect SEO rank?
For example, I know that the extension .com means commercial, or .org means something non-commercial but how about SEO ranking stand-point?
.com vs .website vs .me vs .us vs .co
Thanks in advance.
Comment: I'm voting to close this question as off-topic because it is about SEO and likely belongs to other site like http://webmasters.stackexchange.com/
Comment: I voted to close this question because it is not a programming question and it is off-topic on Stack Overflow. Non-programming questions about your website should be asked on [webmasters.se]. In this case the question has already been asked and answered there: [Does Google penalize sites on "commercial" country code domains such as .me or .tv?](https://webmasters.stackexchange.com/questions/2330/does-google-penalize-sites-on-commercial-country-code-domains-such-as-me-or)
Comment: Side note: consider to read tag information on tags you've selected - SEO - http://stackoverflow.com/tags/seo/info...
Comment: OP posted it on [webmasters.se]: [Does domain extension affect seo?](http://webmasters.stackexchange.com/q/78965/17633)
Answer: No not at all. Domain extension don't give a ranking boost. They are treated equally by default (at least in Google).
Answer: No...
Domain extension doesn't affect your SEO score.
Based on your business type & category it is very important to know about the extensions and select the one which suits your business.

Does domain extension affect seo?


What is different between encoding and font?

Question: Encoding is maping that gives characters or symbols a unique value.
If a character is not present in encoding no matter what font you use it won't display correct fonts
Like Lucida console, arial or terminal
But problem is terminal font is showing line draw characters but other font is not showing line draw characters
My question is why terminal is behaving different to other font
Plz note
Windows 7
Locale English
Answer: For the impatient, the relevant link is at the bottom of this answer.

Encoding is maping that gives characters or symbols a unique value.

No, that are the specifics of a character-set, which maps certain characters to code points (using the Unicode terminology). Lets ignore the above for now.

If a character is not present in encoding no matter what font you use it won't display correct fonts Like Lucida console, arial or terminal

Font formats map Unicode code points to glyphs. Not all code points may be mapped for specific fonts - somebody has to create all these symbols. Again, lets ignore this.
Not all binary encodings may map to code points within a certain character set; this is possibly what you mean.

But problem is terminal font is showing line draw characters but other font is not showing line draw characters

Your terminal seems to operate on a different character set, probably the "OEM" or "IBM PC" character set instead of a Unicode compliant character set or Windows-1252 / ISO 8859-1 / Latin.
If it is the latter than you are out of luck unless you can set your output-terminal to another character set, as Windows-1252 doesn't support the box drawing characters at all.
Solutions:

If possible try and set the output to OEM / IBM PC character set.
If it is Unicode you can try and convert the output to Unicode: read it in (decode it) using the OEM character set and then re-encode it using the box drawing subset.
Comment: I think the 'Terminal Font' is different compared to other fonts because it is rastor bitmap format, its old and designed for the terminal.  when I try to print line draw the character using codepage 437, then no matter what font I use, it displays line draw character, so there seems to be either similarity between code 437 and terminal
Comment: Sounds like the IBM "OEM" font to me. That was used to draw textual "Windows" and stuff.


Using StrongParameters permit without removing other keys

Question: In a controller, I'm trying to pass params received from the view to another object (responsible for handling the logic required to complete the action) but I'm struggling with StrongParameters.
Is there a way to permit specific values on a key while letting the other params pass through?
For instance, for my Role model I'd like to permit name and activity_ids.
So when the controller gets
"role"=>{"name"=>"simple", "activity_ids"=>["", "1", "2"]},
"auth_code"=>"123", "button"=>"", "id"=>"simple"}

It should pass
"role"=>{"name"=>"simple", "activity_ids"=>["", "1", "2"],  permitted: true},
"auth_code"=>"123", "button"=>"", "id"=>"simple"}

So The role can be created/updated with mass-assignment.
And, at the same should be passed when it receives
"role"=>{"name"=>"simple", "activity_ids"=>["", "1", "2"], "injected" => "DELETE FROM roles"},
"auth_code"=>"123", "button"=>"", "id"=>"simple"}

The only way I can use permit is chaining it after require but this removes all the other keys.
Thanks for the help.
Comment: you can chain require statements to achieve your need,`params.require(:role).require(:auth_code).require(:id).permit!`
Answer: You can achieve this using two methods,
Method 1:
Using permit_all_parameters
permit_all_parameters - If it's true, all the parameters will be permitted by default. The default is false.
ActionController::Parameters.permit_all_parameters = true
Eg:
params = ActionController::Parameters.new
params.permitted? # => false

ActionController::Parameters.permit_all_parameters = true

params = ActionController::Parameters.new
params.permitted? # => true

The reference for permitted parameters
Method 2:
you can chain require statements to achieve your need.
params = { "role"=>{"name"=>"simple", "activity_ids"=>["", "1", "2"]},
"auth_code"=>"123", "button"=>"", "id"=>"simple" }

params.require(:role).require(:auth_code).require(:id).permit!

Comment: Thanks for your reply. Besides the fact that either method filters out the role parameters. I'm not able to chain `require` statement. When I run your code I get `ActionController::ParameterMissing: param is missing or the value is empty: auth_code`.
Comment: okay, have you tried the first method, `ActionController::Parameters.permit_all_parameters = true`
Comment: try permitting the params directly and check once `params.permit!`


Imprimir Modal com estilo CSS

Question: Estou tentando imprimir um modal com estilo css usando a função abaixo:
Conteúdo do modal:

           Imprimir

Função:
function imprimeModal(){

        var conteudo = document.getElementById('infoModal').innerHTML,
        tela_impressao = window.open('about:blank');
        tela_impressao.document.write('<!DOCTYPE html>');
        tela_impressao.document.write('');
        tela_impressao.document.write('<title>Teste</title>');
        tela_impressao.document.write('<link href="../css/print.css" rel="stylesheet">');
        tela_impressao.document.write('');
        tela_impressao.document.write(conteudo);
        tela_impressao.document.write('');
        tela_impressao.window.print();
        tela_impressao.window.close();

    }

Quando eu clico no botão imprimir a primeira vez gera o arquivo sem estilo CSS, mas quando eu clico uma segunda vez ele gera o arquivo com estilo CSS. Se eu fecho o modal e abro de novo acontece a mesma coisa... Alguém sabe me dizer se estou fazendo algo de errado?
Answer: Você pode estar utilizando a solução abaixo, você consegue realizar a impressão sem perder o CSS.
Se o site for para acesso via mobile remove a seguinte linha do script.
// Remover div uma vez impresso
$print.remove();

function imprimir(selector) {
  var $print = $(selector)
    .clone()
    .addClass('print')
    .prependTo('body');

  // Pausa JS executado
  window.print();

  // Remover div uma vez impresso
  $print.remove();
}
  @media print and (color) {
    @page {
      margin: 5mm;
      size: A4 portrait;
    }

    * {
      overflow: visible !important;
      -webkit-print-color-adjust: exact !important;
      print-color-adjust: exact !important;
      margin: 0 !important;
      padding: 0 !important;
      color: #212121 !important;
      visibility: hidden;
    }

    html,
    body {
      margin: 0 !important;
      padding: 0 !important;
    }

<button type="button" onClick="imprimir(nomeModal)">
                 Imprimir
                </button>

Imprimir Modal com estilo CSS


Only the first MySQL call works in a php page

Question: I have a PHP script where I need to call 3 mysql stored procedures. But for some reason only the one I call first gets displayed. This is the code:
$raceid = $_GET['raceId'];
$race = "CALL GetRace($raceid)";
if ($stmt = $con->prepare($race))
{
    $stmt->execute();
    $stmt->bind_result($results);
    while ($stmt->fetch())
    {
        echo $results;
    }
    $stmt->close();
}
$fastround = "CALL GetFastestRound($raceid)";
if ($stmt = $con->prepare($fastround))
{
    $stmt->execute();
    $stmt->bind_result($results);
    while ($stmt->fetch())
    {
        echo $results;
    }
    $stmt->close();
}
$uitslag = "CALL GetUitslagByRaceID($raceid)";
if ($stmt = $con->prepare($uitslag))
{
    $stmt->execute();
    $stmt->bind_result($results);
    while ($stmt->fetch())
    {
        echo $results
    }
    $stmt->close();
}

In this case, only the $race results get displayed. But if I put for example the $fastround code above the $race code (or simply remove the $race code) the $fastround results get displayed.
I've made the code on my Windows machine with WAMP, and wanted to move it to a Linux environment for the production environment. Another weird thing is that it worked perfectly on WAMP.
What am I doing wrong here?
Answer: Stored procedures may return more than one result set, therefore you must loop over all of them before issuing your next statement mysql_store_result() call.
Comment: Could you explain what you mean? Or maybe wive an example?


How do I run an if statement in aspx?

Question: I would like to run an if statement but the condition uses a variable from the code behind.  How do I call that variable? Side note... I am using a gridview and the variable is in a dataset (dsResult - idnbr colum)
<ItemTemplate>
   <% string temp = (Eval("idnbr").ToString());
   if (temp.Contains("X")) { %>
       <asp:Label ID="Label1" runat="server" Text='<%# (Eval("old_amt").ToString(),"ccTot") %>'></asp:Label>
   <% } else { %>
       <asp:Label ID="Label2" runat="server" Text='<%# (Eval("new_amt").ToString(),"ccTot") %>'></asp:Label>
   <% } %>
</ItemTemplate>

Answer: Create c# side method that does it for you:
Than use one of 2 ways:

If you deal with well known entity (saying when GridView bound to ObjectDatasource) you
can just cast it to your entity and pass back:

C#:
 protected String MySelectorImpl(Object rowData)
 {
     MyEntity ent = (MyEntity)rowData;
     if(ent.idndr .... )
        return ....
     else
        return ...
 }

ASP.Net:
<ItemTemplate>
    <asp:Label Text='<%# MySelector(Container.DatatItem) %>' ...

Second case - just use eval syntax
C#:
protected string MySelector(Object condition, Object value1, Object value2)
{
    if((String)condition ....) return value1.ToString ....
}

ASP.Net:
<ItemTemplate>
    <asp:Label Text='<%# MySelector(Container.DatatItem("idnbr", ... %>' ...

(,
Answer: I know this doesn't completely answer your question but why not just do this in the code behind?  I'm assuming you're doing something with DataBinding?
string temp  = (string)DataBinder.Eval(e.Item.DataItem, "idnbr");
string newAmount = (string)DataBinder.Eval(e.Item.DataItem, "new_amt");
string oldAmount = (string)DataBinder.Eval(e.Item.DataItem, "old_amt");
Label lbl1        = e.Item.FindControl("label1") as Label;

if(temp.Contains("X") {
 lbl1.Text = oldAmount;
} else {
 lbl1.Text = newAmount;
}

Answer: You can read from a property that is declared in the code behind; does this satisfy what you want?
Instead of string temp = ..., you can use this.MyProperty.Contains("X")...
Comment: just have to make sure it's visible (public or protected)
Comment: @David Right... I meant that when I said property, but I suppose I should be explicit :-)
Answer: <a href="javascript:onclick= window.location = 'RenewalPaymentGateway.aspx?RPID=<%# Eval("RPID")%>'" title="Pay">
 <asp:Label ID="TEMP" Text='<%# If(Eval("PaymentStatus").ToString() = "Paid", "View", "Make payment") %>'  runat="server" />

here in label the text view will appear when PaymentStatus=paid or the text will be make payment

How do I run an if statement in aspx?


Check whether the series is uniformly convergent or not?

Question: which of the following series converges uniformly for $x\in (-π,π)$.
1.$\sum_{n=1}^\infty \frac{x^n}{n^n}$.
2.$\sum_{n=1}^\infty \frac{1}{((x+π)n)^2}$
I was trying to  put putting $x = 0$,then both are uniformly convergent.I'm confused.
Please give me hints or any idea, or tell me the solution.I would be much thankful.
Answer: For part (1) you have $$ \left|\frac{x}{n}\right|^n< \left|\frac{\pi}{n}\right|^n$$ and $$\sum_{n=1}^\infty  \left|\frac{\pi}{n}\right|^n$$ converges so the M-test applies here.
Part (2) is funny, cause it seems pretty benign: $$ \sum_{n=1}^\infty \frac{1}{((x+\pi)n)^2} = \frac{1}{(x+\pi)^2}\sum_{n=1}^\infty \frac{1}{n^2} = \frac{\pi^2}{6(x+\pi)}$$ and yet it doesn't uniformly converge since whatever small difference remains from the nicely converging $\sum \frac{1}{n^2}$ is blown up arbitrarily large by the divergence as $x\to -\pi$