Equivalent markings on Riemann surfaces

Question: This is the definition in Introduction to Teichmuller Spaces by Imayoshi.
Let $(R,\Sigma_p)$ be a pair where $R$ is the riemann surface and $\Sigma_p$ is called marking where $\Sigma_p$ is a set of generator of $\pi_1(R,p)$. Two markings $\Sigma_p,\Sigma_q$ are equivalent if there is a curve inducing an isomorphism of $\pi_1(R,p)\cong\pi_1(R,q)$.
Q: Shouldn't riemann surface path connected imply that all such markings are equivalent? Path connected says there is no difference in taking fundamental group. What am I missing here?
Answer: Two markings are equivalent if they are related by conjugation (inner automorphism of $\pi_1(R)$). But there is still a big family of markings that are related by automorphisms of $\pi_1(R)$ that are not conjugations, which are non-equivalent. The group of automorphism quotiented by the inner automorphisms is called outer automorphism group of $\pi_1(R)$ and denoted $\operatorname{Out}(\pi_1(R))$.
For example, consider the markings $\Sigma_p = \{ [A_j], [B_j] \}$ and $\Sigma'_p = \{ {T_{B_1}}_*([A_j]), {T_{B_1}}_*([B_j]) \}$ where $T_{B_1} : R \to R$ is the Dehn twist about the curve $B_1$. Note that ${T_{B_1}}_*([A_1])=[A_1 \circ B_1]$, while ${T_{B_1}}_*([B_j])=[B_j]$ for $j=1,\cdots,g$ and ${T_{B_1}}_*([A_j])=[A_j]$ for $j=2,\cdots,g$, so these two markings are not related by a conjugation.
As a note, the group $\operatorname{Out}(\pi_1(R))$ is an extension of the mapping class group of the surface (see The Dehn–Nielsen–Baer theorem, a good reference on this is Primer on Mapping class groups by Farb and Margalit).

Equivalent markings on Riemann surfaces


rewrite url in htaccess file codeigniter

Question: I am using codeigniter for development. I've used .htaccess file to shorten my URL i.e. to remove index.php from all URL's.
which is :
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

I have page in which I'm displaying user's portfolio through following link
www.example.com/users/username/id
Here 'users' is controller, 'username' is first parameter which is not unique and 'id' is second parameter which is unique so that i can display unique portfolio of user. It calls 'users' index function in which I pass this parameter.
Now, I want my URL to be like this 'www.example.com/username/id' by rewriting URL through .htaccess file.
When I try to do this, codeigniter considers 'username' as controller instead of parameter.
Is there any way to achieve this? If yes I'll appreciate your time.
Thank you.
Answer: From the docs it says you can just add a route so you can hide the users part:
http://ellislab.com/codeigniter/user-guide/general/routing.html
$route['username/:num'] = "users/username/$1";

Now you can use the link to show the user (with specific id) like this:

Instead of
for example
Hopefully it helps you :)
Comment: I used your reference and it helped me lot. Thank you


Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away'

Question: My website was working till a few days ago. It suddenly stopped working and showing white screen on every page only when some users including administrator are logging in to it. I added the following line at the top of the index.php
error_reporting(E_ALL); ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

The following error is displaying

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away' in /home/******/public_html/includes/database/database.inc:2204 Stack trace: #0 /home/******/public_html/includes/database/database.inc(2204): PDOStatement->execute(Array) #1 /home/******/public_html/includes/database/database.inc(683): DatabaseStatementBase->execute(Array, Array) #2 /home/******/public_html/includes/database/database.inc(2383): DatabaseConnection->query('SELECT expire, ...', Array, Array) #3 /home/******/public_html/includes/lock.inc(167): db_query('SELECT expire, ...', Array) #4 /home/******/public_html/includes/lock.inc(146): lock_may_be_available('theme_registry:...') #5 /home/******/public_html/includes/theme.inc(449): lock_acquire('theme_registry:...') #6 /home/******/public_html/includes/bootstrap.inc(455): ThemeRegistry->set(Array) #7 [internal function]: DrupalCacheArray->__destruct() #8 {main} thrown in /home/******/public_html/includes/database/database.inc on line 2204

I really have no idea what to do.
thanks in advance
Answer: 99% of the times I've seen that error it is because the website is trying to save more data than the amount expected by MySQL.
It is fixed increasing the value of the mysql variable max_allowed_packet
The value of this variable is given in bytes, and by default it is set to 1048576 (1 Mb).
You can try to modify it to something bigger, like 4194304 (4 Mb) and keep increasing it to a value that do not give you this error.
Comment: The server administrator told me `max_allowed_packet=500 M`
Comment: Well, i just found this other question: http://drupal.stackexchange.com/questions/32642/database-general-error-2006-mysql-server-has-gone-away?rq=1 Maybe there is the solution to your issue.


Div display:none escondendo o restante do código após ela

Question: Tenho o seguinte código:
  $htmlPDF = $html;

  $html .= '

' . $htmlPDF . '

      <button type="button" class="button" onclick="createPDF();">pdf</button>
    <form action="pdf.php" method="post">
        <input type="hidden" name="htmlPDF" value="' . $htmlPDF . '
" />
      <input type="submit" class="button formularios" value="Gerar PDF" >
    </form>

    <button id="btnGrafico" class="button formularios">Gerar Gráfico</button>

    <canvas class="line-chart"></canvas>
  ';

Por que é que se eu fizer display: none na div#conteudoHTML, o resto do código não roda?
Nem os buttons, nem o form e nem o canvas
Conteúdo da variável $htmlDF e o CSS:

    @import url('http://fonts.googleapis.com/css?family=Open+Sans');
    * {
        margin: 0;
        padding: 0;
        border: 0;
        outline: none;
    }
    html, body {
        min-height:100%
    }
    html {
        font-family: 'Open Sans';
        font-size: 1em;
        background-image: radial-gradient(rgb(172,204,193) 20%, rgb(40, 22, 111));
        background-size: cover;
        background-repeat: no-repeat;
        box-sizing: content-box;
    }

    img {
        max-width: 100%;
    }
    ul {
        list-style: none;
    }
    a, a:hover {
        text-decoration: none;
    }
    select {
     box-sizing: content-box;
    }

    textarea {
        border: 1px solid rgb(0,0,0);
        border-radius: 10px;
        padding: 8px;
        display: inline-block;
    }

    img.voltar {
     display: block;
     margin: 0 auto;
    }

    .divMensagem {
        display: block;
        width: 500px;
        margin: 0 auto;
    }
    .menu {
     width: auto;
     margin: 0 auto;
     text-align: center;
    }
    .textoPrincipal, .sucesso, .erro {
     width: 100%;
     height: 300px;
     line-height: 300px;
     text-align: center;
    }

    .erro, .hCentralizadoAvisos {
     color: rgb(255,0,0);
    }
    .hCentralizado, .hCentralizadoAvisos, .erro {
     width: auto;
        line-height: 50px;
        text-align: center;
     margin: 0 auto;
    }
    .formularios {
        margin: 0 auto !important;
    }
    .labelPequeno {
        width: 150px;
        height: 30px;
        padding: 3px;
        display: inline-block;
    }
    .labelMinimo {
     display: inline-block;
        height: 30px;
        padding: 3px;
     width:100px;
    }
    .labelMini {
     display: inline-block;
        height: 30px;
        padding: 3px;
     width:50px;
    }
    .inputTextMedio {
        border: 1px solid rgb(0,0,0);
        border-radius: 10px;
        width: 250px;
        height: 30px;
        padding: 3px;
        display: inline-block;
    }

    .button {
        width: 250px;
        height: 30px;
        margin: 3px;
    }
    .btnAcesso, .btnPesquisa {
        background-size: contain;
        background-repeat: no-repeat;
        background-position: right;
        width: 208px;
        height: 44px;
    }
    .btnAcesso {
        background-image: url(../../_imgs/acesso.png);
    }
    .btnPesquisa {
        background-image: url(../../_imgs/pesquisar.png);
    }
    .modelos {
        color: red;
    }
    .todo {
        background-color: rgb(255,255,255);
        margin: 0 auto;
        width: 1000px;
    }
    .topo, .cont, .final {
        display: block;
    }
    .cont {
     min-height: calc(100vh - 120px);
    }
    .final {
     position: relative;
     margin-bottom: 0;
        background-color: #000;
        color: #FFF;
    }
    .finalEsquerda, .finalDireita {
        display: inline-block;
        vertical-align: middle;
    }
    .finalEsquerda {
        width: 78%;
        margin-left: 0;
        text-align: left;
    }
    .finalDireita {
        width: 20%;
        margin-right: 0;
        text-align: right;
    }

    /*///////////////////////// INICIO LISTAGENS ///////////////*/
    div.lista {
        margin: auto;
    }
    ul.listaTopo, ul.listaRegistros, ul.listaFuncoes, ul.menuItens {
        width: auto;
        margin: 0 auto;
        text-align: center;
    }
    ul.listaTopo {
     background-color: rgb(217,217,217);
        color: rgb(255,255,255);
    }
    ul.listaTopo li, ul.listaRegistros li, ul.listaFuncoes li {
        display: inline-block;
        height: 50px;
        line-height: 25px;
        text-align: center;
        vertical-align: middle;
        font-weight: bold;
    }
    ul.menuItens li {
        width: 22%;
        display: inline-block;
        text-align: center;
        vertical-align: top;
        margin: 10px;
    }
    /*///////////////////////// FIM LISTAGENS /////////////////*/

    div.relatorio {
        width: 95%;
        margin: 0 auto;
    }
    div.relatorio .centralizado {
        text-align: center !important;
    }
    div.relatorio .backCinza {
        background-color: rgb(217,217,217);
    }
    div.relatorio ul.detalhes {
        display: block;
        width: 100%;
        height: auto;
        text-align: left;
        margin: 0 auto;
    }
    div.relatorio ul.lancamento li, div.relatorio ul.resumo li {
        height: 100%;
        line-height: 18px;
        font-size: .85em;
        border-left: .1px rgb(0,0,0) solid;
        text-align: center;
        vertical-align: middle;
    }
    div.relatorio ul.lancamento li {
        width: 113.5px !important;
    }
    div.relatorio ul.resumo li {
        width: 150px !important;
    }
    div.relatorio ul.lancamento li:first-child, div.relatorio ul.resumo li:first-child {
        border-left: none;
    }
    div.relatorio ul.ulInlineBlock li {
        display: inline-block;
    }
    div.relatorio ul.border {
        border: .1px rgb(0,0,0) solid;
    }
    span.vertical {
     -webkit-writing-mode: vertical-lr;
         -ms-writing-mode: tb-lr;
             writing-mode: vertical-lr;
     -webkit-transform: rotate(180deg);
         -ms-transform: rotate(180deg);
             transform: rotate(180deg);
    }
    span.comum {

    }
    div.cabecalhoVertical{
     display: -webkit-box;
     display: -ms-flexbox;
     display: flex;
        margin: 0 auto;
     width: 800px;
     height: 220px;
     border: .1px rgb(0,0,0) solid;

    }
    div.cabecalhoVertical div {
     display: -webkit-box;
     display: -ms-flexbox;
     display: flex;
     border-right: .1px rgb(0,0,0) solid;
     -webkit-box-align: center;
         -ms-flex-align: center;
             align-items: center;
     -webkit-box-pack: center;
         -ms-flex-pack: center;
             justify-content: center;
    }
    div.cabecalhoVertical div span {
     text-align: center;
     font-weight: bolder;
    }

Relatório Mensal

Nome do Gcéu

Supervisor

Líder

Houve Supervisão

Houve dia de Jejum

Houve dia de Evangelismo

Membros Compromissados

Visitantes

Crianças de 0 à 12 anos

Total de presentes

Ofertas

Disicpulados

Número de decisões

Célula 1

Cleonice

Jonas

Não

Não

Não

50

10

13

73

22,65

2

11

Celula 2

Carlos

Jonas

Não

Não

Não

10

5

3

18

78,39

3

1

Celula TOP

Carlos

Carlos

Não houve Reuniões para esse Gcéu

Jesuita

Josefina Etelvina

Josefina Etelvina

Não houve Reuniões para esse Gcéu

Tassito

Carlos

Carlos

Não houve Reuniões para esse Gcéu

https://jsfiddle.net/wv2jnydp/
Comment: 99% de certeza que o problema está no conteúdo de `$htmlPDF`.
Answer: Ao utilizar o display: none você faz com que elemento (sua div) não seja renderizada, apenas incluída no DOM. É um atributo explícito indicando "isto não precisa aparecer na tela".
Segundo a documentação:

A propriedade CSS  display especifica o tipo de caixa de renderização usada por um elemento. No HTML, os valores padrões da propriedade  display são feitas a partir do comportamento descrito nas especificações HTML ou da folha de estilo padrão do navegador/usuário. O valor padrão em XML é inline.
Além dos muitos tipos diferentes de exibição de caixa, o valor  none permite desativar a exibição de um elemento; quando você usa none, todos os elementos descendentes também tem a sua exibição desativada. O documento é renderizado como se o elemento não existisse na árvore do documento.
Comment: Era tag div não fechada
Comment: E os buttons, o form e o canvas abaixo dessa div. Porque não aparacem também? Esse é o problema. dsplay: none é para não imprimir mesmo. Minha dúvida é os que estão depois dela. Porque não apareceram tb?
Comment: Por favor inclua o conteúdo do `$htmlPdf` e quaisquer CSS incluído nesta página. Se necessário, você pode criar um [JsFiddle](http://jsfiddle.net).
Comment: Adicionada à pergunta e https://jsfiddle.net/wv2jnydp/
Comment: Ótimo! Sugiro que você explique com alguns detalhes como solucionou o problema e envie como uma resposta, então marque-a como solução :)


WSUSUTIL export fails do to reference of an instance to an object

Question: I am running WSUS on a Internet connected Windows 2016 Server using WID. I used that as my upstream server to download my updates and use the WSUSUTIL tool to export the metadata and the content to my air gapped systems for patching. I did a wsusutil export
wsusutil export EXPORT201802.xml.gz Export.log

and it ran fine and exported. I then synched the server to get the latest of everything and downloaded what I needed.
I did some clean up of my server using the Clean up utility and Adamj-Clean-WSUS V3.2 script. Now when I do the same command.
wsusutil export EXPORT201802-2.xml.gz Export-2.log

Now I am getting an error in the log and on the screen.
Export failed to export updates. please look at the log file for error details. Fatal Error: Object reference not set to an instance of an object.

The log shows the same error. I haven't made any changes to the system other than the installation of the cumulative 2018-02 update for server 2016. I can't find anything on google about this error with wsusutil. I am hoping I won't have to do a full WSUS reinstall. Has anyone had this problem?
OUTPUT LOG from Adamj-WSUS-Script:
Output
Last line of the Export Log file:
<Update UpdateId="51147b68-d2b4-409c-a228-aca52d049252" RevisionNumber="200" Title="x86"><Files><File Path="E:\WSUS\WsusContent\CA\89E273ACA612D15D588C4E18AF0FBF2F5172BDCA.cab" /></Files></Update><Update UpdateId="8444c7c7-ddc8-4120-bd14-04f58fd86412" RevisionNumber="200" Title="x64"><Files><File Path="E:\WSUS\WsusContent\21\10D1D227DACA78A0A9DBD84466E637DD5ECFA921.cab" /></Files></Update><Update UpdateId="1fa7fbe7-6f24-40c9-8759-9b989f9916a6" RevisionNumber="200" Title="Update for Japanese Microsoft IME Standard Dictionary - KB2880582 (Version 16.0.1065.1)"><Files /></Update><Update UpdateId="65d778dd-ed48-4a92-a7b1-c9c162ce187a" RevisionNumber="200" Title="ARM"><Files><File Path="E:\WSUS\WsusContent\0B\0E2BAC94A33ED92E48DFD3764A7D17CCF678C00B.cab" /></Files></Update><Update UpdateId="6092d6e0-e056-4d4c-a862-b231a15e3948" RevisionNumber="200" Title="Update for Japanese Microsoft IME Standard Dictionary - KB2880582 (Version 16.0.1065.1)"><Files /></Update><ExportError Message="Object reference not set to an instance of an object." /></ExportLog>

Answer: Found that PREVIEW updates were synced and not downloaded. After running the script it removed the PREVIEW updates and the export worked correctly.
Also if someone is using the Adam script for WSUS please be sure to check the section where you set $True & $False for Previews, IE7, IE8, IE9 and other builds. This can also lead to this error.


The effect of the treatment on a coefficient (coefficient difference between treatment and control)

Question: I have an experiment where my dependent variable is Choice. Choice is either 0 or 1, so I use a glm function ( family = binomial(link=logit)).
    ECOST Choice treatment
 1: 0.076      0         0
 2: 0.190      1         0
 3: 0.066      0         0
 4: 0.207      1         0
 5: 0.062      0         0
 6: 0.199      1         0
 7: 0.076      1         1
 8: 0.190      1         1
 9: 0.066      1         1
10: 0.207      1         1
11: 0.062      1         1
12: 0.199      1         1
13: 0.076      1         0
14: 0.190      1         0
15: 0.066      1         0
16: 0.207      1         0
17: 0.062      1         0
18: 0.199      1         0
19: 0.076      0         0
20: 0.190      0         0

I want to evaluate how the treatment, treatment==1, affects the coefficient of ECOST, when determining Choice.
More specifically, I want to evaluate whether the coefficient on ECOST is significantly different between the treatment and control group
Since the sample is a experiment (not a real world situation) I am more interested in significance of the difference than the magnitudes if that makes sense.
Somehow this confuses me a lot. There are a couple of options. I first ran:
glm(Choice~ECOST, data=DT, subset=(treatment==0))
glm(Choice~ECOST, data=DT, subset=(treatment==1))

Which is essentially what I want, but it does not inform me whether the difference is significant.
I could also do:
glm(Choice~ECOST:treatment, data=DT)

or
glm(Choice~ECOST*treatment, data=DT)

The first one does not feel right, because it appears to me that the coefficient incorporates the treatment effect as well. So should it be the second one?
I also tried the following and posted it on Stackoverflow:
DATA
I have data as follows:
DT <- structure(list(ECOST = c(0.0757999242, 0.190333143, 0.066333267,
0.2074664592, 0.0615332718, 0.1985331348, 0.0757999242, 0.190333143,
0.066333267, 0.2074664592, 0.0615332718, 0.1985331348, 0.0757999242,
0.190333143, 0.066333267, 0.2074664592, 0.0615332718, 0.1985331348,
0.0757999242, 0.190333143), Choice = c(0, 1, 0, 1, 0, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0), treatment = structure(c(0,
0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0), label = NA_character_, class = c("labelled",
"numeric"))), row.names = c(NA, -20L), class = c("data.table",
"data.frame"))

I want to test if there is a significant difference between ECOST for the treatment and non-treatment group.
    ECOST Choice treatment
 1: 0.076      0         0
 2: 0.190      1         0
 3: 0.066      0         0
 4: 0.207      1         0
 5: 0.062      0         0
 6: 0.199      1         0
 7: 0.076      1         1
 8: 0.190      1         1
 9: 0.066      1         1
10: 0.207      1         1
11: 0.062      1         1
12: 0.199      1         1
13: 0.076      1         0
14: 0.190      1         0
15: 0.066      1         0
16: 0.207      1         0
17: 0.062      1         0
18: 0.199      1         0
19: 0.076      0         0
20: 0.190      0         0

I want to apply this solution, but when I apply:
mm <- glm(Choice~ECOST*treatment,DT, family = binomial(link=logit))
interax <- c("ECOST:treatment")
printCoefmat(coef(summary(mm))[interax,])

I get the error:
Error in printCoefmat(coef(summary(mm))[interax, ]) :
  'x' must be coefficient matrix/data frame

I guess the problem is that in my case x is a single value. How do I do this properly?
EDIT:
summary(mm)

Call:
glm(formula = Choice ~ ECOST * treatment, family = binomial(link = logit),
    data = DT)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-1.9313  -0.2511   0.0001   0.5538   1.3606

Coefficients:
                Estimate Std. Error z value Pr(>|z|)
(Intercept)        -1.43       1.31   -1.09     0.27
ECOST              16.44      10.35    1.59     0.11
treatment          21.00    9924.86    0.00     1.00
ECOST:treatment   -16.44   66757.70    0.00     1.00

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 22.493  on 19  degrees of freedom
Residual deviance: 15.205  on 16  degrees of freedom
AIC: 23.21

Number of Fisher Scoring iterations: 18

Comment: This is mostly a programming question, so off-topic for CV. There is an kernel of statistical question about what the model should look like. Typically, you would include an intercept, treatment dummy, x, and a tretment-x interaction. If you can report the output of summary(mm), perhaps that will make the statistical problem plain.
Comment: @DimitriyV.Masterov Thank you for your comment. I added `summary(mm)`. Are you saying that the difference is simply the interaction effect on `ECOST:treatment` in `summary(mm)`?
Answer: Logit models (like virtually all GLMs) have coefficients that are not directly uninterpretable, and the marginal effects also depend on the values of the data. This means you cannot just look at the interaction coefficient to gauge the magnitude of the effect on the probability.
In your model the change in probability of choosing 1 depends on $x$: $$\Delta \Pr= \Pr(t=1, x_i) - \Pr(t=0, x_i)  = \lambda(-1.43 +16.44 \cdot x_i + 21-16.44 \cdot x_i) - \lambda(-1.43 +16.44 \cdot x_i) = f(x_i)$$
where $\lambda(.)$ is the inverse logit function. This is the difference in probability when treated minus the probability when not.
This effect curve looks like this:

So the effect of treatment in an increase of 0.8 on a [0,1] scale when x is near zero, but very quickly drops off to essentially zero by $x=0.5$. I have no idea if that range for $x$ is sensible in your data.
This is not the only way to present this model, but the most intuitive for me than something like multiplicative effects on odd-ratios (which just involve exponentiated coefficients).
You can find out how to calculate this kind of curve with a CI using the margins package in R here.
Comment: I don't think your interaction intuition from the linear model carries over to the nonlinear test. You can plot the CI or do tests on the effect at various values of $x$. You can also do a more formal hypothesis test comparing the effect at different levels of $x$. On the range question, you should plot the effect with a CI for the range of $x$ that you have. Going beyond involves extrapolating beyond the data, which is mathematically possible but should not be taken very seriously. I also suspect the effect will become insignificant before you get to 0.5.
Comment: If this was OLS, there is no link function. The coefficients will not be the same, but assuming they are just for the sake of the example, the ME of treatment would be $21-16.44 \cdot x$. This is also a function of $x$. But the change in the ME from $x$ is constant in OLS. It's just $-16.44$. In the logit, it varies depending on the value of $x$.
Comment: Thank you very much! I'm going to dig into this tomorrow morning.
Comment: I read through your answer a couple of times now. One thing to note about my question (I shall put this in an edit): Since my data is an experiment, the absolute values of the coefficients are not the main focus (as they have no true meaning anyway). The focus is more on comparison of coefficients and significance. I assume however that in order to test whether the coefficient on `x` or `ECOST` is significantly different for the treatment and control group, I still have to use the `CI` from the `margins` package right?
Comment: You also mention that the effect of the treatment is an increase of 0.8 when x/ECOST is near zero, but that it becomes zero, if the change is larger than 0.5. If I look at my data, x/ECOST is never near 0.5. Can I in that case just ignore that part of the curve (as it does not represent any data in my sample)?
Comment: Thank you very much, this is all very helpful (although a bit more than I was hoping to get myself into ;)). One last thing before I really want to stop bothering you. If this is was a normal linear regression, would the answer just be the coefficient on the ECOST:treatment interaction in summary (mm) ? I know it is such a simple question (and I assumed this to be the case), but somehow when I think about it some more I always get confused. In any case, thank you for all your help and your time. I'm really grateful for it!


socket.io handshake fails on Google https load balancer

Question: We have the following setup for Google HTTPS load balancer.
Two Frontends:
1. HTTP traffic to static IP
2. HTTPS traffic to the same static IP(DNS configured to a domain name)
Host and Path rules
All going to backend
One Backend:
With HTTP protocol with session affinity set to client IP
The backend instance has a MEAN app running on port 3000.
From our client side application we are able to get through to backend app using loadbalancer domain name. But we also have a chat feature with socket.io
For socket connection we were not able to use loadbalancer domain name. It throws 400 error.
If we try to use the backend IP directly for socket connection, it works but the if the client is on HTTPS, it creates another problem because backend is http.
Google documentation says loadbalancer supports websockets by default. So not sure what is going on. All other examples I see are relatively old and not relevant I think. Any help is appreciated. Thanks.
Comment: Like I tried to explain, Google documentation clearly says HTTP(S) load balancing supports websockets without additional support. And I don't think there is a sticky option available on GCE. However there is session affinity and I tried that.
Comment: You apparently didn't understand my comment.  A socket.io connection starts with several http requests before it switches to a webSocket connection.  If those http requests aren't sticky and go to the same host every time, then the socket.io connection will fail.  You can force the client to connect directly with a webSocket as the transport to avoid that or you can configure the load balancer to be sticky.  You NEED one of those for a socket.io connection to work through a load balancer, even one that supports webSockets.  socket.io is NOT plain webSocket, it's got stuff on top of that.
Comment: Because socket.io starts out the connection with a couple http polling requests, the connection will regularly fail if you don't have sticky load balancing.  So, you can either enable sticky load balancing in the load balancer (if that's a supported option) or configure the socket.io client to connect directly with webSocket and not use http polling at the start of the connection.
Comment: See [Socket.io to use webSocket only](https://stackoverflow.com/questions/28238628/socket-io-1-x-use-websockets-only/28240802#28240802) for how to force webSocket transport from the beginning.
Comment: Further to above comment, please note that as per [GCP documentation](https://cloud.google.com/compute/docs/load-balancing/http/#websocket_proxy_support), If you have configured either client IP or generated cookie session affinity for your HTTP(S) LB, all WebSocket connections from a client are sent to the same backend instance, provided the instance continues to pass health checks.
Answer: For WebSockets over an HTTP(S) load balancer, the Backend Service (response) timeout is a connection lifetime limit (WebSockets connections are killed after the configured response timeout). Hence, the timeout should be set to the maximum amount of time a WebSocket connection will remain open. The appropriate response timeout value is dependent on the application you use.
You will need to do some experiments to find an appropriate response timeout to avoid the connection timeout closures (increase its value slightly and retry; for example, if 30 seconds is insufficient, try 40sec,50 sec etc.).
Found on StackOverflow.
Answer: Herro, I have struggled with debugging this issue for 2 weeks.
@jfriend00 's comment provided providence for my plebian mind.
On nodejs deployment endpoint I have to pass the order of transports in the following:
  app = express()
  server = require('http').Server(app)# {key: tlskey, cert: tlscert},app)
  io = require('socket.io')(server, { transports: ['websocket', 'polling'], cookie:true, secure: true })
  app.use bodyParser.urlencoded(extended: true)

What is happening? I specify to socket.io to explicitly use the websocket transport. If it fails, please fallback to polling. Because the HTTPS GCE Ingress sets some headers (does some header upgrades to wss), I need the secure:true flag in order to match them on my backend. Without the above an error 400 occurs on the client side.
The service runs as a NodePort, with a Generate_Cookie.
If it still fails, try just transports: ['polling'], this is the most basic protocol.
Here is the link for the socket.io doc


Validar domínio preg_replace

Question: A minha dúvida é a seguinte, tenho a seguinte função:
$site = preg_replace("/[^a-zA-Z0-9]/", "", $_POST['site']);

Mas ao utilizar na string  www.lostscavenge.com.br, essa expressão regular emite o seguinte retorno:
 wwwlostscavengecombr
Como faço para essa função permitir e não remover os pontos?
Comment: Como assim somente o uso do ponto?
Comment: Eu quero limpar a string, tirar todos os caracteres especiais, permitindo apenas o uso do ponto, por exemplo quando eu uso essa função e digito no formulário www.lostscavenge.com.br minha string fica assim:

wwwlostscavengecombr

Sendo que era pra ficar assim:
www.lostscavenge.com.br
Answer: Nomes de domínio atualmente podem podem ser unicode (utf8). Dependendo das regras do seu business model, caso necessite permitir domínios que possuam caracteres não ASCII, a rotina abaixo pode ser útil:
function validate_domain_name($str, $force_utf8 = true)
{
    $force_utf8 = $force_utf8? 'u': '';

    //Isso é ineficiente.
    //$re = '[^a-zA-Z0-9\.]';

    //Isso é ineficiente. Pois não valida normas básicas
    //$re = '^(http[s]?\:\/\/)?((\w+)\.)?(([\w-]+)?)(\.[\w-]+){1,2}$';

    //Esse é mais consistente
    $re = '^(?!\-)(?:[\w\d\-]{0,62}[\w\d]\.){1,126}(?!\d+)[\w\d]{1,63}$';

    if (preg_match('/'.$re.'/'.$force_utf8, $str, $rs) && isset($rs[0]) && !empty($rs[0])) {
        return $rs[0];
    } else {
        return null;
    }
}

$str = '000-.com';
$str = '-000.com';
$str = '000.com'; // válido
$str = 'foo-.com';
$str = '-foo.com';
$str = 'foo.com'; // válido
$str = 'foo.any'; // válido
$str = 'お名前0.com'; // válido
$str = 'お名前.コム'; // válido

echo 'domain: '.validate_domain_name($str);

Para desabilitar o unicode, defina o segundo parâmetro como booleano false.
A expressão regular original foi adaptada a partir dessa resposta: https://stackoverflow.com/a/16491074/1685571
As adaptações que fiz foi trocar a-zA-Z por \w e adicionar a opção para incluir a flag u, a qual permite caracteres non-ASCII.
Answer: Basta adicionar o ponto ao seu padrão:
$site = preg_replace("/[^a-zA-Z0-9\.]/", "", $_POST['site']);

É esse \. no fim do padrão. A \ é para escapar o ponto (.), porque em expressões regulares o . significa qualquer caractere
Comment: Opa, deu certo aqui porém eu não entendo de jeito nenhum essas expressões mas tem alguns sites que tem o traço também - então acho que não daria muito certo.. será que dá pra permitir o uso dele também?
Comment: Sim, basta adicionar o `-` no final. Ele não precisa ser escapado. Na verdade, dentro de colchetes não há necessidade de escapar nada, nem o ponto, mas eu gosto de fazer isso, é um hábito. Sua nova expressão ficaria: `$site = preg_replace("/[^a-zA-Z0-9\.\-]/", "", $_POST['site']);`
Comment: Obrigado, deu certo!
Comment: @ViniciusAquino segue uma referencia sobre as expressões regulares, para que possa compreende-las melhor :) http://www.devmedia.com.br/expressoes-regulares-em-php/25076
Comment: @leo_ap quanto está dentro de colchetes o ponto não é um meta caractere, logo sua regex está escapando a barra invertida também. O correto é`'/[^a-zA-Z0-9.]/'`
Comment: @gmsantos de forma alguma, se colocar a barra invertida causa um erro na expressão regular, para fazer o match dela deve-se usar \\ em qualquer situação, dentro ou fora de colchetes. O `\.` dentro de colchetes escapa corretamente o ponto.
Comment: @leo_ap http://regexr.com/3f2mn http://stackoverflow.com/a/15139411/2099835
Comment: [.] e [\.] irão fazer o match apenas do ponto. para fazer o match de uma barra invertida e de um ponto seria necessário: [\\.] (ou também [\\\.]). Compreenda que a barra invertida faz o escapamento do caractere seguido dela em qualquer situação.
Comment: Se usar uma string simples no PHP (com aspas simples) a barra invertida é considerada. Uma coisa é como a linguagem escapa os caracteres, outra coisa é a expressão regular em si.
Comment: @gmsantos Estou me referindo exatamente ao comportamento da expressão regular em si, o que estou a dizer é a forma como ela foi elaborada e concebida pelos seus idealizadores e pela grande maioria de seus implementadores. Usar uma barra invertida sozinha dentro de colchetes irá causar erro na maioria das implementações de expressão regular. Isso porque dentro de colchetes a barra invertida é considerada um metacaracter.

Validar domínio preg_replace


Next.js API URL problem on Docker container

Question: My problem is:
I made a simple web page with Next.js. I take some content from /pages/api/ endpoints with JSON format and show it in pages and components. Compiling locally (npm run dev or npm run start) is fine. When I run it on Docker on Windows 10, I don't have a problem again. And this is working on Heroku and Vercel. The point I'm having trouble with is: I gave the project to the Devops team and they ran it on Docker. They also directed a domain to this project. But the api endpoints are meaninglessly trying to access an ID URL. When I look from Chrome Devtools it looks like this:
http://013cfdde4910:3000/api/en/brands
I get the following errors as console message.
Mixed Content: The page at 'https://beta..com/technologies' was loaded over HTTPS, but requested an insecure resource 'http://013cfdde4910:3000/api/en/menu'. This request has been blocked; the content must be served over HTTPS.
Actually it should be http://localhost:3000/api/en/brands. I don't understand where 013cfdde4910 here is coming from and why.
I checked to see if it is among the codes. I looked at the Source of the project that is live, that is, published by the Devops team, from Google Devtools.
_next/static > chunk > pages > _app-eac17e226e00cc01a313.js
When I searched here, I found 013cfdde4910 String in 3 places. Why did it come here when it was built?
For example, the minified code continues as follows.
.... return(0,u.useEffect)((function(){fetch("".concat("http://013cfdde4910:3000","/api/").concat(t.locale,"/) brands")).....

I can see it as localhost in my local build and when I publish it in Windows 10 Docker and look there. So what is causing the localhost -> 013cfdde4910 conversion and how can I solve it?
Dockerfile I use:
FROM node:current-alpine as base
WORKDIR /app
COPY package.json ./
RUN npm install
COPY . .

FROM base AS build
ENV NODE_ENV=production
WORKDIR /build
COPY --from=base /app ./
RUN npm run build

FROM node:current-alpine AS production
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build /build/package*.json ./
COPY --from=build /build/.next ./.next
COPY --from=build /build/public ./public

RUN npm install

EXPOSE 3000
CMD npm run start

I use docker-compose.yml
version: "3"
services:
  ui:
    container_name: web
    restart: always
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "3000:3000"
    volumes:
      - ./:/app
      - /app/node_modules
      - /app/.next
    env_file:
      - .env

And this is next.config.js
module.exports = {
  webpackDevMiddleware: (config) => {
    config.watchOptions = {
      poll: 1000,
      aggregateTimeout: 300,
    };
    return config;
  },
  async headers() {
    return [
      {
        source: "/api/:path*",
        headers: [
          { key: "Access-Control-Allow-Credentials", value: "true" },
          { key: "Access-Control-Allow-Origin", value: "*" },
          {
            key: "Access-Control-Allow-Methods",
            value: "GET,OPTIONS,PATCH,DELETE,POST,PUT",
          },
          {
            key: "Access-Control-Allow-Headers",
            value:
              "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version",
          },
        ],
      },
    ];
  },
  reactStrictMode: true,
  generateEtags: false,
  i18n: {
    locales: ["en", "tr"],
    defaultLocale: "en",
    localeDetection: false,
  },
  env: {
    VERSION: process.env.VERSION,
    MODE: process.env.MODE,
    APP_NAME: process.env.APP_NAME,
    HOST: process.env.HOST,
    HOSTNAME: process.env.HOSTNAME,
    PORT: process.env.PORT,
    GA_TRACKING_ID: process.env.GA_TRACKING_ID,
  },
  generateBuildId: async () => {
    return new Date().toDateString();
  },
  eslint: {
    ignoreDuringBuilds: false,
  },
};

Comment: Can you post the contents of your `next.config.js` and `package.json` ?
Comment: I added @Ramakay
Answer: Thanks for posting the config, it appears the hostname is grabbed as the docker container ID - You do not post the actual fetch code but my guess is - this environment variable is used.
   `HOSTNAME: process.env.HOSTNAME`

It is either passed as a environment variable or interpreted to be the container ID, you need a way to create a domain:3000/api/brands which could be part of the Docker deploy, maybe a nginx proxy.
Comment: I removed the dependencies of process.env.HOST and process.env.HOSTNAME that I used in the project, so I tried it without using it, and the result is as I mentioned. So it's not used in the last Docker deployment.
Comment: Oh ok,  is there a chance to try without the i18n packages ?


What cleaning agent is safe to use for ping pong paddles?

Question: I just got a new ping pong paddle, and I want to be able to clean the rubbers without damaging them or affecting their tackiness.  On Amazon I see lots of expensive little spray bottles for cleaning paddles.  What substances are in those bottles?  Perhaps I can clean the paddle using stuff I have at home.  Would rubbing alcohol, or soapy water, or something else be safe to use to clean the rubbers?
Comment: Does this answer your question? [Cleaning table tennis rubbers](https://sports.stackexchange.com/questions/5533/cleaning-table-tennis-rubbers)
Comment: No it does not. That question is about what cloth to use to wipe off the cleaning agent.
Answer: When I was most active (decades ago), I used Butterfly's Tackiness Drive on my forehand and Sriver on my backhand.  What I used to clean both rubber sheets was simple window spray cleaner and paper towels.  In a pinch you can get by with just water, but Windex (or any other variant) does quite nicely.  I saw no adverse results from using it over a period of many years.


How to calculate $\arctan(\sqrt3-2)$ to be $-15°$ by hand?

Question: Not approximately, but precisely, and what does one need to know to be able to do that?
For instance, I know that $\tan(45°)$ gives the incline of a line which encloses $45°$ with the $x$-axis, namely $1$, therefore $\arctan(1)=45°$ or $\frac{\pi}{4}$. Is there a way to use this relation?
Regards
Comment: You've mixed up tan and arctan. It's $\tan(45°)=1$ and $\arctan(1)=45°$ (or, better, $\pi/4$).
Comment: $\tan\dfrac{\alpha}{2}=\dfrac{1-\cos\alpha}{\sin\alpha}$. Now let $\alpha=30^\circ$.
Answer: Take a 30-60-90 triangle, with sides $1,\sqrt{3},2$.   Extend the side of length $\sqrt{3}$ by an extra two units.  That gives a $15-75-90$ triangle whose short sides are 1 and $2+\sqrt{3}$
Comment: How did you derive that? Can it be done for arbitrary angles?
Comment: An isosceles triangle, with two sides equal to 2, and one angle equal to 150 degrees.
Answer: Well, you can go the other way. That's easier.
$\tan 30^{\circ} = \frac{1}{\sqrt 3}$
Let $t = \tan 15^{\circ}$.
So $\displaystyle \frac{2t}{1-t^2} = \frac{1}{\sqrt 3}$
Solving,
$t^2 + 2\sqrt 3 t - 1 = 0$
$\displaystyle t = -\frac{-2\sqrt 3 + \sqrt{12+4}}{2}$ (only admissible root)
$t = 2 -\sqrt 3$
(edited as the question seems to have been amended to ask for $\tan (-15^{\circ})$:
$\tan (-15^{\circ}) = -\tan 15^{\circ} = \sqrt 3 - 2$
Answer: You can use
$$
\tan(\alpha-\beta)=\frac{\tan\alpha-\tan\beta}{1+\tan\alpha\tan\beta}
$$
with $\alpha=45^\circ$ and $\beta=60^\circ$, so $\tan45^\circ=1$ and $\tan60^\circ=\sqrt{3}$:
$$
\tan(-15^\circ)=\frac{1-\sqrt{3}}{1+\sqrt{3}}=\frac{(1-\sqrt{3})^2}{1-3}
=\frac{1-2\sqrt{3}+3}{-2}=\sqrt{3}-2
$$
Answer: Here is yet another way.
$$2-\sqrt{3}=\frac{(\sqrt{3}-1)(\sqrt{3}-1)}{2}=\frac{\sqrt{3}-1}{1+\sqrt{3}}$$
Now we have
$$\arctan \left(\frac{a-b}{1+ab}\right)=\arctan a-\arctan b$$
So
$$\arctan 2-\sqrt{3}=\arctan \sqrt{3}-\arctan 1=60^{\circ}-45^{\circ}=15^{\circ}.$$
Answer: The angle occurs in the dodecagon, which is a composition of triangles and squares.  This gives you a coordinate system, from which ye find
sin(15) = (sqrt (3)+1)/sqrt(2)
cos(15) = (sqrt (3)-1)/sqrt(2)
Whence the ratio is (sqrt(3)-1)̃²/(sqrt(3)+1)(sqrt(3)-1) = 2-sqrt(3).
Answer: $$\sqrt3-2=\cot30^\circ-\csc30^\circ=\dfrac{\cos30^\circ-1}{\sin30^\circ}=\dfrac{-2\sin^215^\circ}{2\sin15^\circ\cos15^\circ}=-\tan15^\circ=\tan(-15^\circ)$$
Now use $-90^\circ<\arctan x<90^\circ$


django: trying to access my robots.txt: "TypeError at /robots.txt 'str' object is not callable"

Question: Exception Type: TypeError at /robots.txt
Exception Value: 'str' object is not callable
What gives?
Views:
ROBOTS_PATH = os.path.join(CURRENT_PATH, 'robots.txt')

def robots(request):
""" view for robots.txt file """
return HttpResponse(open(ROBOTS_PATH).read(), 'text/plain')

Settings:
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))

URLs:
(r'^robots\.txt$', 'robots'),

Comment: You can't seriously expect us to answer this question without any information about your code, can you? We need a traceback and probably a relevant excerpt of the program.
Comment: Added the code. been a long day. stupid neighbors had me up till 3am then woke me up in the morning.
Answer: Try:
from appname.views import robots
(r'^robots\.txt$', robots),

Or:
(r'^robots\.txt$', 'projectname.appname.views.robots'),

Django can't figure out where your 'robots' function is.


How to set Permission based on roles for Views Data Export

Question: Using views data export module, I set the permission for different roles in the Data Export in Views like:

But I can still see the Export button for all users in front page. However if the role doesn't have permission to export then after clicking it they are redirected to Access Denied Page
Is there any way I can hide the export button from all the user roles except the ones that have permission to export?
If it was a link defined in *.tpl.php then I could have done something like
<code><?php if (in_array('myRole', $user->roles)): ?>
// The export button
<?php endif; ?>
</code>
But I couldn't figure out how to do it with Views Data Export (without hacking the module)
Answer: This issue has been fixed in the 7.x-3.0-beta8 version. See the issue thread here.
Answer: Add a template for the view. Then by using css, hide the default export button coming with view. Then print the export link manually based on user role.


Associated primes of the square of a monomial ideal

Question: Consider the ideal $J=(xy,yz,zx)$ in $R=\mathbb C[x,y,z]$. How to show that $(x,y,z) \in \mathrm{Ass}_R (R/J^2)$ ?
Answer: A down-to-earth method is: find an element whose annihilator is $(x, y, z)$.
An element that seems to work here is $xyz+J^2$. It is nonzero in $R/J^2$, since $J^2$ consists only of polynomials whose terms of degree $\leq 3$ are $0$.
We have
\begin{align*}
x \cdot  xyz=x^2yz=(xy)(xz) \in J^2, \\
y \cdot  xyz=xy^2z=(xy)(yz) \in J^2, \\
z \cdot  xyz=xyz^2=(xz)(yz) \in J^2,
\end{align*}
showing that $(x, y, z) \subseteq \mathrm{Ann} (xyz + J^2)$. On the other hand, $(x, y, z)$ is a maximal ideal and $1 \notin \mathrm{Ann} (xyz + J^2)$, so we conclude equality.
Comment: Thanks ... is there a similar way to show $(x,y,z) \in Ass_R (R/J^n), \forall n \ge 3$ ? I know this is true by some high tech method, but I would really like to see an elementary proof ...
Comment: @uno: Sure, just take e.g. $(xy)^{n-2}\cdot(xyz)=x^{n-1}y^{n-1}z$. This is still not $0$ in $R/J^n$ by the same degree argument, but $(x, y, z)$ kills it by the very same computation as above (simply because $(xy)^{n-2} \in J^{n-2}$), so you can again conclude that the annihilator is precisely $(x, y, z)$.


Typescript - unexpected sequence with setTimeout in combination with async and await

Question: When I run this script, the output is different from what I expect: 1 through 4. Why is that?
const delay2 = async ( ms: number) => setTimeout( () => {
  console.log( '2 - timeout')
}, ms);

const mainAsync2 = async () => {
  console.log( '1 - before');
  await delay2( 2000);
  console.log( '3 - after');
}
mainAsync2()
.then( res => console.log( '4 - done'));

The output is:

1 - before
3 - after
4 - done
2 - timeout

Answer: setTimeout by itself does not return a promise, so awaiting it does nothing. It simply sets a timeout for ms milliseconds. Instead, you should make your delay2 return a promise that resolves after ms milliseconds, for example:
const delay2 = async (ms: number) =>
    new Promise(res => setTimeout(() => {
        console.log('2 - timeout');
        res();
    }, ms));


Autoregressive process with random walk perturbation (with drift)

Question: Suppose we have an autoregressive process,
$$y_t=\phi y_{t-1} +u_t$$ where $|\phi|<1$.
If $u_t$ is an i.i.d random variable this process is stationarity. What if $$u_t=u_{t-1}+g+\epsilon_t$$ where $\epsilon_t$ is white noise and $g$ is a constant?
I tried to use the lag operator to show that it's still stationary (due to the presence of $g$) , but I am having some issues. Is $y$ still stationary in that case?
Thanks in advance.
Answer: No, it is not. As you recognize, $u_t$ is nonstationary, and adding $g$ creates an additional drift, and certainly does not restore stationarity. By recursive substitution, you can write (assuming the process starts at 0)
$$
u_t=\sum_{s=1}^t\epsilon_s+g\cdot t,
$$
and using this process to drive $y_t$ "translates" the nonstationarity to $y_t$.
Illustration:
<code>n <- 100
g <- .2
eps <- rnorm(n)
u <- cumsum(eps) + g*(1:n)
y <- arima.sim(n=n, list(ar=0.5), innov = u)
plot(y)
</code>


What is the name of this geometric shape - A Cylinder with a Cone Atop?

Question: I've been unable to find the geometric name for the following shape, does one exist?
Comment: I would probably call it "a cylinder with a cone on top."
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/65405/discussion-on-question-by-james-what-is-the-name-of-this-geometric-shape-a-cyl).
Comment: If the cylinder were considerably longer, laypeople might call it a pencil, but that term is already [used for something else](https://en.wikipedia.org/wiki/Pencil_(mathematics)) in geometry.
Comment: Thanks for taking a go at it, MvG.
Answer: Can't find anything better than "Cylindro-conical shape". However, a pyramid on top of a prism is called "elongated pyramid". If we can apply similarity then this shape should be called "elongated cone".


What's $\lim_{x \to 0} \frac{\cos(\alpha+x) - \cos \alpha}{x}$?

Question: I want to calculate the above limit. Using sage math, I already know that the solution is going to be $-\sin(\alpha)$, however, I fail to see how to get to this conclusion.
My ideas
I've tried transforming the term in such a way that the limit is easier to find:
\begin{align}
    \frac{\cos(\alpha + x) - \cos(\alpha)}{x}
    &= \frac{\cos(x)\cos(\alpha)-\sin(x)\sin(\alpha)-\cos(\alpha)}{x} & (1) \\
    &= \frac{\cos(x)\cos(\alpha)-\cos(x)}{x} - \frac{\sin(x)\sin(\alpha)}{x} & (2) \\
    &= \frac{\cos(\alpha)(\cos(x)-1)}{x} - \sin(\alpha) & (3) \\
\end{align}
However, I'm not sure whether term $(3)$ is enough to solve the problem. Surely, for $x \to 0$, this evaluates to $\frac{0}{0} - \sin(\alpha)$, which is not enough to determine the limit.
Another try was to transform the term in such a way that I can use $\lim_{x \to 0} \frac{\sin x}{x} = 1$. For instance, I found that
$$
\frac{\cos(\alpha + x) - \cos(\alpha)}{x}  = \frac{\sin(\alpha - 90^° + x) - \sin(\alpha-90^°)}{x} \qquad (4)
$$
However, this only seems to lead to more complicated term manipulations that I did not manage to bring to a useful point.
What can I do to solve this problem?
Comment: This is the definition of the derivative
Answer: The derivation of the derivative of $\cos(x)$ from geometry goes the way you went, but now you need to provide some justification for the equality $\lim_{x \to 0} \frac{\cos(x)-1}{x}=0$, which can also be done using geometry.
Answer: Don't make things more complicated than they are. This quotient is the rate of variation of the function of $x$: $\cos(\alpha +x)$, hence its limit is the derivative of the function at $x=0$.
Answer: You are right and from here
$$ x\frac{\cos(\alpha)(\cos(x)-1)}{x^2} - \sin(\alpha) \to0\cdot \left(-\frac{\cos \alpha}2\right) -\sin(\alpha)=-\sin \alpha$$
indeed recall
$$\frac{\cos(x)-1}{x^2} \to -\frac12$$
As an alternative refer to derivative definition if you are allowed tu use that.
Answer: Use that $\cos(\alpha + x) - \cos(\alpha)=-2\sin(\alpha+\frac{x}{2})\sin(\frac{x}{2})$ to get $$\lim_{x \rightarrow 0} -\sin(\alpha+\frac{x}{2})\frac{\sin\frac{x}{2}}{\frac{x}{2}}$$


How to catch this exception in Python?

Question: If the user enters incorrect directory name which doesn't exists rsync generates this error. I am using subprocess.Popen with Python. How do I catch this error in Python?
rsync: link_stat "/fdsfsd" failed: No such file or directory (2)
    rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1637) [Receiver=3.1.0dev]
    rsync: [Receiver] write error: Broken pipe (32)

Comment: What code throws this exception?
Answer: That doesn't look like an exception but an error printed by rsync.  As such you can't catch it in Python.  What you can do is monitor the return code of the Popen object to see whether the process terminated successfully.  Read the documentation on returncode.
If you want to try to parse the error message I suppose you could try that with regular expressions, but it's probably not worth it.  When you call an external process there is no general-purpose way to know how its printed error messages map onto Python exception types.  The program could do anything and fail in any unknown way.  Your best bet is simply to look at the returncode and, if it is nonzero then raise an exception saying "the external process failed somehow".  This is basically what subprocess.check_call does for you.
Comment: How can I do that? Using Regular Expression?
Comment: @user1881957: No, using the return code.  See my edited answer.

How to catch this exception in Python?


Spring: exclude some properties files from context

Question: suppose we have some jars with properties files with the same key/values.
configA.jar:
log4j.A.properties
configB.jar:
log4j.B.properties
The problem: Spring mixes values from the both properties files. So, how to exclude log4j.A.properties from the context and process only log4j.B.properties?
UPDATE (added some stuff): there is a maven build which produces two jars mentioned above. Here in webapp (applicationContext.xml) following setup:
<util:properties id="propertyConfigurer" location="classpath:common.properties,classpath*:edrive.properties,classpath*:job.properties,classpath*:log4j.B.properties"/>

After the startup Spring mixes both jars and takes random (or the last one) jar and it's log4j.properties. But we need only the log4j.B.properties. How to do that?
Comment: why Spring would consider  `log4j.A.properties` or  `log4j.B.properties` as property placeholder ? Please give more context to understand what you do.
Comment: I've updated initial post, thanks.
Comment: https://stackoverflow.com/q/4113697/6309111 Does this answer your question ?
Comment: Unfortunately, no. This answer ideally fits the scenario with single-module maven structure. In my case those two jars with configs build before the actual build is started, so, there is no possibility to exclude both properties files during the final assembly.
Answer: try adding the config file to be used in your properties file
logging.config=log4j.B.properties

Comment: unfortunately, didn't help.
Answer: I resolved the issue by myself. I've upgraded logging facility to Log4j2 with following configuration:
log4j2.component.properties in classpath:
log4j.configurationFile=classpath:log4j2.web.xml

That's it.


A proper, lower semicontinuous, convex function with no subgradient?

Question: Let $X$ be a Banach space and $f:X\to \Bbb R \cup\{\infty\}$ is a proper, lower semicontinuous and convex function.

Is it possible that $\partial f(x)=\emptyset$ for all $x\in \text{dom} f$?

If $\text{ int dom} f\ne \emptyset$ then the above situation is not possible. However, I couldn't think of a counterexample for the case  $\text{ int dom} f = \emptyset$. Does anyone know if the above statement is true or false?
Answer: The domain of $\partial f$ is a dense subset of $\text{dom} f$, so it cannot be empty.
(See e.g. Barbu-Precupanu, Convexity and optimization in Banach spaces, Corollary 2.44.)


Como posso executar uma função que está noutro form?

Question: Tenho dois forms, num deles tenho:
namespace J13_Rouparia_CS
{
    public partial class frmMain : Form
    {
          public static int LocPesq;
          public static string peqNume;
          public static string peqArti;

          public void UpdatePesquisa()
          {
              switch (LocPesq)
              {
                 case 1:
                     txtSRnum.Text = peqNume;
                     txtSRartigo.Text = peqArti;
                     break;
                 case 2:
                     txtELnum.Text = peqNume;
                     txtELartigo.Text = peqArti;
                     break;
                 case 3:
                     txtSLnum.Text = peqNume;
                     txtSLartigo.Text = peqArti;
                     break;
              }
         }
    }
}

No outro eu gostaria de executar o UpdatePesquisa(), usando frmMain.UpdatePesquisa(), mas o método UpdatePesquisa não aparece na lista. Como posso resolver esta situação?
Answer: Precisa ter a variável do seu form instanciada no local que você está chamando o método UpdateProgress().
O seu form já está ativo? Caso contrário, você terá que instanciar a variável e chamar o método:
frmMain fMain = new frmMain();
fMain.UpdatePesquisa();

Se o seu formulário já está ativo, você tem duas opções:

Enviar o formulário principal como parêmetro no construtor da classe que você utilizará:
public partial class frmMain : Form {
   public frmMain(FormReferencia x) {…}
}

Utilizar a função Application.OpenForms["<nome da classe>"]:
Form1 f1 = (Form1)Application.OpenForms["Form1"];

Comment: Eu risquei a primeira frase da sua resposta porque está incorreta, na verdade o método só pode ser visualizado fora da classe se for público, mas não quis mudar sua resposta e deixei para você editar, OK? Eu também esqueci de alterar o nome do método de `UpdateProgress()` para `UpdatePesquisa()`, fiz uma segunda edição mas não sei se será aceita, então qualquer coisa depois você altera, por favor. Agora, sobre essa primeira sugestão que você deu com o form ativo, creio que seja difícil que o segundo form esteja aberto **antes** do `frmMain`, que, pelo nome, é o principal!
Comment: Pedro, Obrigado pela ajuda! Realmente ficou confusa a resposta. Sobre o nome do formulario, eu também acho que já está ativo, mas achei melhor informar a solução caso não esteja.
Comment: Esse trecho da sua resposta: "*Você não conseguirá visualizar o método porque ele é public*" está errado. O método ser público não é o motivo dele não poder ser visualizado, pelo contrário, se não fosse público, aí sim que não seria visualizado. Por isso eu tinha riscado essa parte, eu esperava que você excluísse ela! E tem outro `UpdateProgress()` errado no primeiro parágrafo.
Answer: Partindo do princípio que quer aceder ao form frmMain a partir de um outro evocado por esse mesmo Form, pode fazer da seguinte forma:
frmMain
///
/// Método localizado em "frmMain"
/// Criar uma nova instância do novo form
/// passando este como "Owner"
///
void AbrirNovoForm()
{
    frmNovoForm frmNovoForm = new frmNovoForm();
    frmNovoForm.Show(this);
}

frmNovoForm
///
/// Método localizado em "frmNovoForm"
/// Fazer cast do "Owner" para "frmMain" e evocar o método "UpdatePesquisa()"
///
void UpdatePesquisa() => (Owner as frmMain).UpdatePesquisa();

Answer: a melhor forma de se fazer, vai depender muito do propósito, mas se entendi bem, uma forma de compartilhar o código entre formulários que possuem os mesmos campos, seria criar um form Base, colocar nele tudo que é comum para os demais, e os novos forms passam a herdar desse form Base, exemplo:
form Base:
public class frmBase : Form
{
  public void UpdatePesquisa()
  {
    //faz alguma coisa
  }
}

Novo Form:
public class frmNovo : frmBase
{
  //executa o que está no base
  base.UpdatePesquisa();
}

obs: se você também pode usar a palavra virtual no método criado no form base com isso você além de conseguir utilizar poderá sobrescrever nos novos forms.
exemplo com virtural:
public virtual void UpdatePesquisa()
{
   //faz alguma coisa form base
}
//form Novo poderia sobrescrever metodo acima
public override void UpdatePesquisa()
{
  //faz algo diferente do base, ou mesmo faz o que tem no base mas alguma coisa
}


Buscar informações específicas no array do certificado digital

Question: Tenho um código pronto que encontrei na internet sobre informações de Certificado Digital de um determinado domínio, porém não sei como buscar informações específicas dentro deste array.
Gostaria apenas de encontrar informações como nome do certificado, host, data de expiração. Eis um exemplo do código abaixo:
 $url = "http://www.submarino.com.br";
 $orignal_parse = parse_url($url, PHP_URL_HOST);
 $get = stream_context_create(array("ssl" => array("capture_peer_cert" => TRUE)));
 $read = stream_socket_client("ssl://".$orignal_parse.":443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $get);
 $cert = stream_context_get_params($read);
 $certinfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']);
 // print_r($certinfo);
 echo "Nome do certificado: " . $certinfo['name'];

Usando o print_r na variable $certinfo deu os seguintes resultados, como que poderia "quebrar" alguns itens dentro do array?
Comment: O que você quer "quebrar" exatamente?
De um exemplo de algum resultado, e como vc gostaria que ele fosse quebrado.
Fica mais fácil pra tentar te ajudar.
Answer: Faz um tempo que não programo em PHP e com certeza os códigos abaixo não são os melhores, mas como o foco da questão é sobre os campos do certificado, achei que valia a pena uma resposta.

O "nome" do certificado a que você se refere, provavelmente é o campo Subject, que aparece desta forma ao usar print_r:
[subject] => Array
    (
        [C] => BR
        [ST] => Rio de Janeiro
        [L] => Rio de Janeiro
        [O] => B2W COMPANHIA DIGITAL
        [OU] => Tecnologia
        [CN] => b2wdigital.com
    )

No caso, você poderia pegar somente o CN, que contém o Common Name do certificado (no caso de certificados de servidor, contém a URL do site):
echo "Nome do certificado: " . $certinfo['subject']['CN'];

Neste caso, a saída é:

Nome do certificado: b2wdigital.com

Mas um certificado de servidor pode corresponder a mais de uma URL, cujos valores ficam na extensão Subject Alternative Name. O print_r mostra desta maneira:
[extensions] => Array
    (
        ... outras extensões
        [subjectAltName] => DNS:b2wdigital.com, DNS:www.submarino.com, ... (um monte de entradas DNS)

No teste que fiz, o certificado tinha 31 URLs.
Para obtê-las, basta quebrar a string (separa por vírgulas) e ver as entradas que são "DNS":
// os valores estão separados por vírgula e espaço
$names = explode(", ", $certinfo['extensions']['subjectAltName']);
$lista_urls = []; // lista que vai guardar as URLs
foreach ($names as $name) {
    $v = explode(":", $name); // DNS: url
    if ($v[0] === "DNS") {
        $lista_urls[] = $v[1];
    }
}
print_r($lista_urls);

Eu coloquei if ($v[0] === "DNS") porque esta extensão pode ter outros tipos de informações além de "DNS" (neste caso não tem, mas a definição desta extensão prevê vários tipos diferentes).
A lista de URLs é bem grande (de 0 a 30, omiti vários por questões de brevidade):
Array
(
    [0] => b2wdigital.com
    [1] => www.submarino.com
    [2] => *.thebestoff.com.br
    [3] => *.b2w.io
    [4] => www.soubarato.com
    [5] => *.americanas.com.br
    [6] => *.soubarato.io
    [7] => *.soubarato.com.br
    [8] => *.submarino.com.br
    ....

Aliás, um dos muitos nomes desta lista é da URL que você usou para obter o certificado:
*.submarino.com.br.

Para a data de validade, há dois campos:
[validTo] => 200204120000Z
[validTo_time_t] => 1580817600

O primeiro é a data e hora em UTC: 200204120000Z. Os 2 primeiros dígitos (20) são o ano (no caso, 20 equivale a 2020), depois vem o mês (02 -> fevereiro), o dia (04) e o horário (120000 -> 12:00:00 -> meio-dia). O Z no final indica que esta data/hora está em UTC.
O segundo valor (1580817600) é o timestamp - a quantidade de segundos desde o Unix Epoch, ou seja, 1580817600 segundos depois de 1970-01-01T00:00Z.
Ambos correspondem à mesma data/hora, então você pode escolher qualquer um para obter a data de validade:
// usando o valor do timestamp
$dt = new DateTime('@' . $certinfo['validTo_time_t']);
echo "Data de validade:". $dt->format('Y-m-d H:i:s P');

// usando a string 200204120000Z
$dt = DateTime::createFromFormat('ymdHisP', $certinfo['validTo']);
echo "Data de validade:". $dt->format('Y-m-d H:i:s P');

Ambos imprimem:

Data de validade:2020-02-04 12:00:00 +00:00

Outros campos
Para pegar mais campos, basta observar a saída de print_r.
A sua variável $certinfo nada mais é que um Array com várias entradas, uma para cada campo do certificado. Alguns são strings, como o name:
[name] => /C=BR/ST=Rio de Janeiro/L=Rio de Janeiro/O=B2W COMPANHIA DIGITAL/OU=Tecnologia/CN=b2wdigital.com

Outros podem ser Arrays, como o caso do subject que vimos acima. Basta fazer $certinfo['nome_do_campo'] e em seguida veja se esse campo é uma string, Array, etc e trate-o de acordo.
Além disso, name e subject na verdade são o mesmo campo, apenas em formatos diferentes (name tem uma string com todos os valores e subject tem esses valores devidamente quebrados em um Array).
Essa redundância também acontece com outros campos, como aconteceu com a data de validade acima (a mesma data em 2 formatos diferentes). Outro campo que tem isso é o Serial Number, que tem o mesmo valor em base decimal e hexadecimal:
[serialNumber] => 4187706408991266263283860591637795211
[serialNumberHex] => 032685DDE5C5A2AE141685650B49918B

Enfim, cada campo vai ter seu formato próprio. E cada certificado pode ou não ter determinados campos (nome, data de validade e serial number todos terão, mas DNS Names nem sempre, por exemplo). Infelizmente a documentação da função openssl_x509_parse não diz qual o formato do Array retornado:

The structure of the returned data is (deliberately) not yet documented, as it is still subject to change.
A estrutura dos dados retornados é (deliberadamente) não-documentada, pois está sujeita à mudanças.

Mas é possível saber o que cada campo pode ter, lendo a RFC 5280 (um documento chatíssimo, mas muito importante para entender a estrutura de um certificado e o tipo de dados que podem estar em cada campo).
E no caso de certificados emitidos no Brasil, você pode consultar a ICP-Brasil. Você pode ver a lista de Autoridades Certificadoras, e no site de cada uma deve ter (geralmente tem) um link para as respectivas políticas de certificado. Geralmente é um documento PDF detalhando quais campos são obrigatórios e opcionais e o que pode ter em cada um. É um pouco mais específico que a RFC, já que esta define vários campos opcionais e/ou deixa em aberto os tipos de dados que podem ter. Já a política de certificado é mais específica (para eCPF, por exemplo, define qual campo vai ter o CPF etc).
Geralmente os certificados possuem o link para o site da Autoridade Certificadora que contém as políticas de certificado. No caso do certificado em questão, a URL está na extensão certificatePolicies:
    [extensions] => Array
        (
            .....
            [certificatePolicies] => Policy: 2.16.840.1.114412.1.1
  CPS: https://www.digicert.com/CPS
Policy: 184.108.40.206.2.2

Então basta pegar a URL que está depois de "CPS:"
// cada valor está em uma linha, então eu separo por \n
$policies = explode("\n", $certinfo['extensions']['certificatePolicies']);
foreach($policies as $p) {
    // limitar o array $v a no máximo 2 elementos (para não quebrar o http://...)
    $v = explode(":", $p, 2);
    if (trim($v[0]) === "CPS") {
        echo trim($v[1]); // URL da Autoridade Certificadora
    }
}

No caso, a saída foi:

https://www.digicert.com/CPS

Entrando neste site, há vários links com o texto "DigiCert Certificate Policy (CP)", que aponta para um PDF contendo a política de certificado.
Cada link aponta para um documento diferente, pois depende da data em que o certificado foi emitido (as políticas de certificado podem mudar com o tempo). No caso do certificado em questão, a data de emissão está no campo validFrom:
[validFrom] => 181105000000Z

No caso, 5 de novembro de 2018. Procure o link correspondente a esta data e terá o PDF correto.
Também é um documento bem chato, e geralmente tem as definições de cada campo (mas às vezes pode ter somente definições "genéricas", ou dizer "conforme RFC5280" ou ainda apontar para outros documentos complementares - enfim, não é fácil...)
Veja também o documento de certificate profiles, que detalha os campos que são obrigatórios e opcionais.
Comment: @aleque_b Sobre a chave pública, [aqui](http://php.net/manual/en/function.openssl-pkey-get-public.php) tem um exemplo. Sobre a data, a variável `$dt` contém uma data, e vc pode pesquisar (aqui no site deve ter vários exemplos) como calcular diferença entre datas. Como já disse, faz tempo que não programo em PHP, desculpe não poder ajudar mais. De qualquer forma, se quiser usar a chave pública, aí acho que já é o caso de abrir outra pergunta, até para deixar o site mais organizado (evita-se fazer muitas perguntas de uma vez, mesmo que relacionadas; é melhor uma pergunta focada por tópico)
Comment: Muito bem, testarei isso mais tarde para ver se funciona, e a respeito da chave pública como pegaria? E calcular quanto tempo falta para expirar a partir da data de hoje?
Comment: Tranquilo, vou testar este código e darei meu feedback depois


Largest laplacian eigenvalue lower bound

Question: I'm currently dealing with a problem that I'm unsure how to start.
Let G be a graph with largest Laplacian eigenvalue $\lambda_1$ and maximum degree $\Delta > 0$. Show that $\lambda_1 \geq \Delta + 1 $.
I have tried using that the sum of the eigenvalues of the Laplacian is the trace of Laplacian, but that got me nowhere. Any tips appreciated!
Comment: Which laplacian?
Comment: @IgorRivin Presumably, it's the Laplacian that people refer to as "the Laplacian" without adding any adjectives like "normalized", "generalized", "signless", or whatever else you were thinking of.
Answer: The correct place to start, when it comes to interpreting the largest eigenvalue of any symmetric matrix, is almost always the following lemma:

If $A$ is a symmetric matrix, then its largest eigenvalue is the maximum value of $\frac{\mathbf x^{\mathsf T}\!A \mathbf x}{\mathbf x^{\mathsf T}\mathbf x}$, achieved when $\mathbf x$ is the corresponding eigenvector.

For the Laplacian matrix in particular, it's convenient to keep in mind that $\mathbf x^{\mathsf T}L \mathbf x = \sum_{ij \in E}(x_i -x_j)^2$, where the sum is over all edges of the graph.
Usually, the actual eigenvector is some complicated mess that's hard to interpret from the point of view of classical graph theory. However, we can try to find nice and simple vectors that seem like they'd be pretty good at maximizing the quantity above, and get a lower bound for the largest eigenvalue.
In particular, if your goal is to prove that $\lambda_1 \ge \Delta+1$, it's reasonable to try to use the existence of a degree-$\Delta$ vertex to find some $\mathbf x$ such that $\frac{\mathbf x^{\mathsf T}L \mathbf x}{\mathbf x^{\mathsf T}\mathbf x} \ge \Delta+1$.
My first try was to set $x_i = 1$ for a single vertex of degree $\Delta$, and $x_j = 0$ for all $j \ne i$. You can check that this only tells us $\lambda_1 \ge \Delta$. Instead, setting $x_i = \Delta$, $x_j = -1$ for all $\Delta$ vertices $j$ adjacent to $i$, and $x_k=0$ for the rest works.
(Why should this second vector work better? Well, we've made it more eigenvector-like. All eigenvectors of $L$ are orthogonal, and one of them is the all-ones eigenvector $\mathbf 1$. So we improve $\mathbf x$ by making sure that all its entries add up to $0$: that $\mathbf x^{\mathsf T} \mathbf 1 = 0$.)

There's a second way to think about this problem, which is derived from the first. If $H$ is a subgraph of $G$, then $\lambda_1(H) \le \lambda_1(G)$.
(The argument here is that whatever the eigenvector $\mathbf x$ corresponding to $\lambda_1(H)$ is, it does at least as well at maximizing $\frac{\mathbf x^{\mathsf T}L_G \mathbf x}{\mathbf x^{\mathsf T}\mathbf x}$ as it did at maximizing $\frac{\mathbf x^{\mathsf T}L_H \mathbf x}{\mathbf x^{\mathsf T}\mathbf x}$. Pad $\mathbf x$ by zeroes first if $H$ was missing some vertices of $G$.)
Saying "$G$ has maximum degree at least $\Delta$" is equivalent to saying "$G$ has a subgraph isomorphic to $K_{1,\Delta}$". So if we can show that $\lambda_1(K_{1,\Delta}) \ge \Delta+1$, we immediately get that for all other graphs with maximum degree at least $\Delta$.
Answer: Let $L$ be the Laplacian matrix of $G = (V, E)$.
The key idea is to consider the Rayleigh quotient (https://en.wikipedia.org/wiki/Rayleigh_quotient) which is frequently used to estimate the largest eigenvalue. For convenience, I copy the definition of Rayleigh quotient here:
$R(L) := \max\limits_{x \neq 0}\frac{x^TLx}{x^Tx} = \max\limits_{||x||=1}x^TLx = \lambda_1$.
Below is a critically important lemma for Laplacian matrix:
$\textbf{Lemma 1}:$
$x^TLx = \sum\limits_{(i, j) \in E}(x_i - x_j)^2$.
Proof to Lemma 1 could be found in almost every textbook on algebraic graph theory. You may check Lemma 3.6 in https://math.uchicago.edu/~may/REU2013/REUPapers/Marsden.pdf.
Here, we attempt to find a unit vector $x$ such that $\sum\limits_{(i, j) \in E}(x_i - x_j)^2 \geq \Delta + 1$. Instead of using complicated Lagrange method, we directly construct the vector $x$. Suppose vertex $v \in V$ has the largest degree and the index of $x$ is $i$.
Let $v_1,\,v_2,\,...,\,v_\Delta$ are $\Delta$ vertices connected to $v$ with indices $j_1, j_2, ..., j_\Delta$.
We set:
$\lambda \in \mathbb{R},\,0 < \lambda < \sqrt\frac{1}{\Delta}$.
$x_{j_1} = x_{j_2} = ... = x_{j_\Delta} = -\lambda$.
$x_i = \sqrt{1 - \Delta \lambda^2}$.
$x_k = 0$ if $x_k$ is not in the set $\{x_i, x_{j_1}, ..., \,x_{j_\Delta}\}$.
We want to find a $\lambda$ such that:
$\sum\limits_{k=1}^\Delta (x_i - x_{j_k})^2 = \Delta(\sqrt{1 - \Delta \lambda^2} + \lambda)^2\geq \Delta + 1$ (1).
Arrage Eq. 1 into a quadratic inequality:
$(\Delta+1)\lambda^2 - 2\sqrt{1+\frac{1}{\Delta}}\lambda + \frac{1}{\Delta} \leq 0$ (2).
The disciminant of the left hand side of Eq.2 is $0$. Therefore,
$\lambda = \frac{\sqrt{1+\frac{1}{\Delta}}}{\Delta+1}$ (3).
In this setting, $x$ is a unit vector and $\sum\limits_{(i, j) \in E}(x_i - x_j)^2 = \Delta + 1$. Hence, $\lambda_1 = \max\limits_{||x||=1}x^TLx = \max\limits_{||x||=1}\sum\limits_{(i, j) \in E}(x_i - x_j)^2 \geq \Delta + 1$.
We can easily prove that the bound is tight. Just consider a connected undirected graph with two vertices please.


Update - Firebird com Inner Join

Question: Preciso realizar um Update em vários registros ao mesmo tempo, estou tentando otimizar o processo!
SELECT tei.id_identificador, tes.uni_medida, tep.qtd_atual
FROM tb_estoque tes
INNER JOIN tb_est_tipo_item_sis tis ON tes.id_tipoitem = tis.id_tipoitem
INNER JOIN tb_est_identificador tei ON tes.id_estoque = tei.id_estoque
INNER JOIN tb_est_produto tep ON tei.id_identificador = tep.id_identificador;

Com o Select acima obtive os dados, porem ao tentar realizar o Update retorna erro!
Estou tentando com a seguinte instrução:
update tb_estoque, tb_est_produto
inner join tb_est_tipo_item_sis on tb_estoque.id_tipoitem = tb_est_tipo_item_sis.id_tipoitem
inner join tb_est_identificador on tb_estoque.id_estoque = tb_est_identificador.id_estoque
left join tb_est_produto on tb_est_identificador.id_identificador = tb_est_produto.id_identificador
set
    tb_estoque.uni_medida = [valor_pretendido],
    tb_est_produto.qtd_atual = [valor_pretendido]
where
    tb_est_identificador.id_identificador = [condicao_pretendida];

Erro:

"Invalid token. Dynamic SQL Error. SQL error code = -104. Token
  unknown - line 1, column 18. ,."
Comment: você esta executando isso no firebird, mysql, ou ambos?
Comment: @ErickLuz Estou utilizando o IBEXPERT, Firebird!
Answer: No Firebird você não consegue realizar esta façanha.
A sintaxe do do update dele é:
update NOME_TABELA set
NOME_CAMPO = VALOR
where xyz = xyz

O JOIN tera que ser com sub-select após o WHERE
Fonte
Comment: Pode aplicar um exemplo com base na tabela que coloquei na imagem?

Update - Firebird com Inner Join


Using other log4net logging levels than the usual ones

Question: I've realised that there is more levels than all, debug, info, warn, error and fatal, they are listed in the log4net.Core.Level class.
But how can I use them? I mean, in the ILog interface you have methods to use the usual ones, but what if you want to use "Fine" or "Emergency", etc?
Cheers.
Answer: In the following example Log is of type ILog.
Log.Logger.Log(null, log4net.Core.Level.Emergency, "Help!", null);

For each level you check their Value in order to know when they are disabled.
For log4net version 18.104.22.168 you have the following levels and associated cut off values:
OFF: 2147483647
EMERGENCY: 120000
FATAL: 110000
ALERT: 100000
CRITICAL: 90000
SEVERE: 80000
ERROR: 70000
WARN: 60000
NOTICE: 50000
INFO: 40000
DEBUG: 30000
FINE: 30000
TRACE: 20000
FINER: 20000
VERBOSE: 10000
FINEST: 10000
ALL: -2147483648

Note that some levels share the same values so disabling one of them will also disable the other, like for example TRACE and FINER.
Comment: @vtortola, yes you can use those levels in the configuration.
Comment: @vtortola, you were not blind. All the nice amenities of the basic levels like IsXxxEnabled, Xxx, XxxFOrmat are not available for the other levels so when using the ILog interface it is easy to miss them. It also means that using the other levels in the code requires more work.
Comment: I must be blind or something, I didn't see that property haha.

And can I use those levels also in the configuration file writing them capitalized?

Cheers.
Answer: To extend on the good answer already provided:
You can also add the following extension method:
 static public void Notice( this ILog log, object message )
 {
     log.Logger.Log( null, log4net.Core.Level.Notice, message, null);
 }

Then use as:
Log.Notice("Take note!");

Where Log is of type ILog


How does a 32-bit machine support more than 4 GB of RAM?

Question: I have always wondered about this and never totally understood how 32 bit machines are addressing more than 4 GB of RAM. I mean, there are no more address lines left, correct?
I know even in our facility that we have Dell database servers with 8 GB of RAM addressable by the machine and a 32-bit version of SQL Server. Is it achieved similar to EMS memory of the 20 address line 8086, using a window of rotating memory?
Comment: What OS and SQL?
Answer: To support more than 4 GB memory Windows uses Physical Address Extension (PAE). It uses paging tables to map the memory greater than 4 GB. By doing this the physical address size is increased to 36 bits, or 64 GB. PAE is used in 64-bit OS'es as well; in this case the maximum size is doubled to 128 GB.
This method does mean that each process is still limited to a maximum of 4 GB of memory.
Comment: It doesn't. http://www.microsoft.com/windowsserver2008/en/us/compare-specs.aspx It's limited to 64 GB, just as Sam said.
Comment: Not just Windows. All operating system which support the *processor feature* PAE can do this. To find out if your processor supports PAE, check the output of "cat /proc/cpuinfo". No idea how to check in Windows though.
Comment: So explain how Windows Server Datacenter Edition x86 supports 128GB?
Comment: In the normal, default 32 bit Windows OS configuration, 2 GB of the virtual address space are allocated to the process' private use and the other 2 GB are allocated to shared and operating system use. Therefore only 2 GB can be used by a process in reality.(maybe 3 with the /3GB but never all of them from psychical RAM)

Only that portion of the address space that is actually referenced (used) by a process or the system is associated with a page frame in real memory, or in the pagefile.
Comment: Why would a 64-bit system need to use PAE?
Answer: It's called PAE. It works by changing the page table layout on the processor to support up to 64 GB of RAM. However, any one application can still only use 2-3 GB (depending on how the kernel is set up, usually 2 GB for Windows and 3 GB for Linux). Also, PAE tends to make the machine run slightly slower, because page table lookups have an extra level to go through.
It should be supported on any relatively recent processor.
Answer: There's an Intel feature called PAE which in effect enables the OS to utilize more than 4GB of memory. Each application can only use 2 (or 3) GB of memory space but as the OS now has more memory to spread stuff out over - there will be less sharing between processes and hence some possible performance benefits.
The real magic however begins when using the AWE API with which you can actually use more memory with a single 32bit application that is especially written for this. This is what SQL Server is doing.
Answer: Well, your server operating system might be 64-bit. SQL maybe only using 4 gigs of the 8, or some 32-bit programs spawn more processes (like video encoding software, in my experience) to take advantage of the ram.
Answer: An application on a 32 bit OS can access of 4GB of address space. But this is virtual address space and has absolutely nothing to with the size of physical RAM. Most modern 32 bit processors have sufficient address lines to address 64GB of RAM. Blocks of 4K bytes are mapped to a process's address space as needed.
It is PAE that allows access to more than 4GB of RAM. It is not a hack as often claimed but is quite efficient. PAE doesn't make any fundamental changes, it is only the details that are differnet. In fact, most modern system are using PAE by default. DEP relies on the PAE kernel.
Unfortunately, access to RAM beyond 4GB is limited to servers. A desktop may be using PAE but will ignore any RAM beyond 4GB. There are a number of technical and marketing reasons for this.


Tritone sub for a minor chord

Question: I was reading http://www.thejazzpianosite.com/jazz-piano-lessons/jazz-chords/passing-chords/
The article writes:

Tritone (of next chord)   | CMaj7 - A♭7 | Dm7 |

Is this a mistake? As far as I am concerned, it's not possible for a minor7 chord to contain an interval of six semitones. Because of that, you can't perform tritone substition on Dm7.
Comment: As JohnBelzaguy explains, there's no substitution happening because the Ab7 isn't replacing anything. The Ab7 is a passing chord, and that's the best way to think about it. It's not meant to replace the function of the Dmin. However, in jazz, it's not unheard of to perform tritone substitutions with minor chords. For example, over the progression | Dmin | G7 | CMaj |, we might hear | Dmin | Abmin | CMaj |. Chick Corea is a pro at this. It's still a tritone sub in the sense that Richard describes. But it's arguably still a *conventional* tritone sub with the form | G7sus | Db7sus | CMaj |.
Answer: This article is about passing chords, not tritone substitutions. The excerpt you showed,
Tritone (of next chord) | CMaj7 - A♭7 | Dm7 |
simply indicates that one option for inserting a passing chord between Cmaj7 and Dm7 is to insert a chord, Ab7, that is a tritone away from the next (or second) chord, Dm7.
Comment: Great answer. This progression is not a tritone substitution because the Ab7 isn't replacing anything. It's being added in as a passing/approach chord between two harmonically important chords (CMaj and Dmin).
Comment: The question is why one would choose a passing chord that is tritone away from the next chord. I think the reason is that it can indeed be heard as a tritone sub of D7 leading to (Dm7,G7), even if G7 never comes.
Comment: @MattL. I just answered the question at face value based on the article provided but I do not care for some of the passing chord recommendations in the article. You make a good point, by looking ahead the Ab7 is the sub V of the (G7) in C.
Comment: Yes, my intention was not at all to criticize your answer, which is indeed right to the point. I just thought it interesting to see if there's some reason why such a passing chord actually works. The cookbook recipe "a tritone away from the target chord" doesn't really make much sense to me.
Comment: @MattL. No worries, I didn't get that impression at all, just adding my point of view and even gave your answer a +1 because I thought it was insightul
Answer: The current use of the term "tritone substitution" is really a conflation of two separate ideas: one in which two chords share a tritone, and another in which two chords have roots that are a tritone apart.
When we're dealing with chords like dominant sevenths, both definitions apply: a C7 chord has the tritone E/B♭, which happens to be the same tritone involved in the chord built on the root a tritone away, G♭7 (which has B♭ and F♭). But when we're dealing with something like a minor triad, only the latter definition applies, because there is no tritone in the chord.
So in an instance like this one with a minor seventh chord, since there's no tritone in the chord, we just build a chord a tritone away. Since we're looking at Dm7, that tritone away is A♭7.
(See also Must a tritone substitution use a dominant functioning seventh chord?)
Comment: I would take issue with the definition you've provided of tritone substitution, but only because it leaves out the element of 'substitution.' Simply having two chords a tritone apart isn't enough to qualify as a substitution, and the progression in question (CMaj - Ab7 - Dmin) is a good example of this. Before any modification, the original progression is | CMaj | Dmin |. The Ab7 isn't a substitution because it's not replacing anything. It's simply a passing chord/approach chord that we add in, which a tritone away from the target chord (Dmin).
Comment: @jdjazz For what it's worth, I agree with you 100%. But my experience is that people are using this term more and more in the "root distance" sense, which is at odds with its original intention.
Comment: Yes, and I'm guilty of that. If playing Dmin-G7-CMaj as Dmin-Abmin-CMaj, I'll call the change a tritone sub, even though Abmin doesn't contain a tritone interval. But there's no doubt it's a substitution, because I'm replacing G7 with Abmin--the G7 goes away and we substitute Abmin in its place. In the progression | CMaj Ab7 | Dmin |, there's no substitution happening because the Ab7 isn't replacing anything. It would be a tritone sub if the original progression were | CMaj D7 | Dmin |. But if the original progression is just CMaj-Dmin, then squeezing in Ab7 isn't a substitution/replacement.
Comment: In other words, if we wanted to come up with a term for this scenario (which isn't really necessary, but could be instructive), it might be called something like "tritone approach chord" or "tritone passing chord" instead of "tritone substitution." I think you've got a great explanation for what the term 'tritone' means in this context, but I think any answer to this question needs to clarify to the asker that this situation doesn't qualify as a substitution.
Answer: I would like to add to the existing answers a possible motivation for the chord Ab7 as a "passing chord" between Cmaj7 and Dm7. The "reason" that it is a tritone away from the target chord doesn't really explain anything, at least not to me. What I hear is indeed a tritone substitution, but of course not of Dm7 (because that chord isn't substituted), but of D7. That D7 chord is a secondary dominant of G7, and G7 could follow that Dm7 chord to make it a full II-V in C major. However, even if G7 doesn't follow, the Dm7 as a first part of that standard II-V unit can represent that unit a certain way because our ears are so used to hearing it. Note that Dm7 could also be heard as a G7sus4 sound (without root). So when listening to that progression I do hear Ab7 as a tritone sub leading to the II-V unit Dm7-G7, even if G7 never comes, and that why it works well, at least for me.
Answer:
Tritone (of next chord) | CMaj7 - A♭7 | Dm7 |

First look at the plain progression...
Original Chord Progression | CMaj7 | Dm7 ||
...to that the passing chord is added (generically I call it "?")
Original Chord Progression | CMaj7 ? | Dm7 ||
...so A♭7 fills in the ? as the passing chord. It's root A♭ is a tritone away from the target chord Dm7. (This is not a case of tritone substitution, another jazz harmony idea, the similar naming could be confusing.)

The author is coy about the voicing of the passing chords...

Note: That both the chord and the bass-line movement are important when transitioning between chords. You want both to be smooth. I will have more to say about this in future lessons.

A very quick review of the chart shows all the passing chords can be voiced so that the bass will either be a common tone with one of the two chords of the simple two chord progression or a chromatic half step between them. All other voices should move the minimal distance.
All the basses probably should be:

C C D
C C# D
C Db D♮

Except for...
Approach #1 (diatonic) | CMaj7 - Em7 | Dm7 ||
...where the bass should probably be C D D
I'm taking an approach the bass of the passing chord should not anticipate (be the same tone) as the bass of the target chord.
Comment: -1 because, to me, it seems like everything in your answer above "the author is coy..." is already explained by the other two answers. In my mind, multiple answers that repeat the same info tends to clutter the page and make it harder to find the correct info. Small clarifications that don't change the meaning of an existing answer are best posted as comments to an existing answer, I think. I suggest starting your answer with: "One addition to the other answers: the author is being coy..." But the info about bass movement doesn't by itself answer the Q, which is why I downvoted.
Comment: I guided the OP through how to read the article, and follow through with the implied voicing aspect. I was addressing how to read the article. But, you can downvote whatever why you want.
Comment: In my view, the guidance directs the asker's attention to the same facts/considerations as the other answers describe.

Tritone sub for a minor chord


Non-zero fixed point of some linear action on any finite group

Question: Let $G$ be a group , $F$ be a field , $n$ be a positive integer , a map $h:G \times F^n \to F^n$ is called a linear action if there is a group homomorphism $f:G \to GL(n,F)$ such that $h(g,v)=f(g)v,\forall g\in G , v \in F^n $ ; then is it true that for any finite group $G$ and field $F$ , there is a positive integer $n$ , a linear action $h$ and a non-zero vector $v \in F^n$ such that $h(g,v)=v , \forall g \in G$ ?
I tried as follows : Let $|G|=n$ , then we can embed $G$ in $S_n$ which we can embed in $GL(n,F)$ by
$\sigma \in S_n \to (e_{\sigma(1)} .... e_{\sigma(n)})\in GL(n,F)$ ; so we have an injective group homomorphism $f:G \to GL(n,F)$ , now is this the required homomorphism which induces the action ? If so then what is my non-zero vector $v$ ?
Please help . Thanks in advance
EDIT : From  leibnewtz 's comment below , we can always have the trivial action ; but I am looking for a non-trivial action ..
Comment: Why can't you just let $G$ act trivially on $F$?
Comment: @leibnewtz : Ok , so you mean to consider the group homomorphism $h:G\to GL(n,F)$ to be $h(g)=I_n , \forall g \in G$ ? yeah I think that works .. I have edited my question accordingly , but please don't delete your comment
Answer: Your example works since you can take the non-zero vector $v := e_1 + e_2 + \dots + e_n$ which is fixed by all $g \in G \leq S_n$.
It works also (probably a little bit easier) if you simply take $G \hookrightarrow S_n \hookrightarrow S_{n+1}$, where $S_n$ is the subgroup of permutations which fix $n+1$. In the picture of your linear action (but now) onto $F^{n+1}$ this means fixing the (basis) vector $(0, \dots, 0, 1)$.


how to add field programmatically in Drupal 7 with dynamic content value?

Question: I have a function in my e-commerce website that allow users to create own stores, i need to add dynamic field (select list) contain the stores created by the logged user when he add new product to assign this product with store.
i try to add field on the content type 'product' but i found that drupal save the values in the database.
What is he best method that resolve my problem?
Answer: I'm not sure what you are trying to do. But if you are trying to add a new field programmatically, below is a code snippet that can get you started.
<code>    $myField_name = "my_new_field_name";
    if(!field_info_field($myField_name)) // check if the field already exists.
    {
        $field = array(
            'field_name'    => $myField_name,
            'type'          => 'image',
        );
        field_create_field($field);

        $field_instance = array(
            'field_name'    => $myField_name,
            'entity_type'   => 'node',
            'bundle'        => 'CONTENT_TYPE_NAME',
            'label'         => t('Select an image'),
            'description'   => t(''),
            'widget'        => array(
                'type'      => 'image_image',
                'weight'    => 10,
            ),
            'formatter'     => array(
                'label'     => t('label'),
                'format'    => 'image'
            ),
            'settings'      => array(
                'file_directory'        => 'photos', // save inside "public://photos"
                'max_filesize'          => '4M',
                'preview_image_style'   => 'thumbnail',
                'title_field'           => TRUE,
                'alt_field'             => FALSE,
            )
        );
        field_create_instance($field_instance);
        drupal_set_message("Field created successfully!");
    }
</code>
Hope that works
Muhammad.
Comment: Function name ?
Comment: My Problem is the field can't take different value for each user?
for example: i have a fiel for name "field_mystore" is select list type.
user1 show the field store contain his store list (user1 store1, user1 store2)

user2 show the field store contain his store list (user2 store1, user2 store2)

is it possible do code my idea?
Comment: Use any event you want. Bind it to hook_install() or bind it in any button click.


How to add multiple terms to a taxonomy reference field via feeds?

Question: I would like to import a node with multiple taxonomy terms referenced in one of node fields.
How can I do this with Feeds and Drupal 7 ?
Answer: Use the Feeds Tamper module to "explode" the comma-delimited list of taxonomy terms into individual references.

Feeds Tamper provides a small plugin architecture for Feeds to modify data before it gets saved. Several plugins are available by default and are described in the examples section below.
  Additional plugins can be added in separate modules or through the issue queue.
Comment: In my situation, the list is not a comma separated list. It is like
Answer: In my situation, the list is not a comma separated list. It is as follows:
<code><product>
    <category>Ship</category>
    <id>000032</id>
    <Description>The description comes here</Description>
    <list>
        <Destination>
            <DestinationName>Dest 1</DestinationName>
            <DestinationCountryISOAlpha3>US</DestinationCountryISOAlpha3>
        </Destination>
        <Destination>
            <DestinationName>Dest 2</DestinationName>
            <DestinationCountryISOAlpha3/>
        </Destination>
    <list>
</product>
</code>
I have a taxonomy called destinations and the list is already imported. Now how can I import Destinations list of a product as a term reference for the product node. I am using feed module, Feeds XPath Parser, and Feeds Tamper modules?
Answer: I'd like to suggest the Manage Multiple Terms module.

Manage Multiple Terms provides a simple mechanism to add, update, delete many terms in the same time easily and quickly.


How to call a function (requiring args) with string name - Clojurescript | d3

Question: I'm trying to do some refactoring on a function (set-attr) that calls a function (.attr) on a d3 object (node). I want to be able to decouple the object function (.attr) from set-attr.
But I keep getting this error Cannot read property 'each' of null.
I'm hoping someone has experience with d3 interop in Cljs and knows of something that can work, because it works fine on regular js objects.
Function that works
(defn set-attr [node [attr settr]]
  (.attr node attr settr))

What I think should work (but gives me the error)
(defn set-attr [node [attr settr]]
  ((aget node "attr") attr settr))

Works fine on a regular js object
((aget (clj->js {:foo (fn [x y] (str "hi" x y))}) "foo" ) "ryan" "lol")
;; => "hiryanlol"

Answer: d3 uses inheritance. Thus you cannot process this object as a mere hash-table. You have to reach to its prototype to get what you want, which is usually not a good idea: this would produce rather brittle code.


Is $2\pi /2\pi$ considered an indeterminate ratio for imaginary exponentiation?

Question: It seems that I can force any expression of the form $a^{bi}$ to become 1 by changing its base to the natural number and raising it to the power of one in the form of $\frac{2\pi}{2\pi}$ so that it instead reads as $(e^{2πi})^\frac{blna}{2π}$ or $1^c$, $a,b,c\in\mathbb{R}$.
Does this problem arise from the periodic similarity between $0$ and $2\pi$ in the trigonometric representation, meaning that in this context $\frac{2\pi}{2\pi}$ is akin to the indeterminate ratio $\frac{0}{0}$?  This kind of mistake can be put into any false proof, but I have never seen it come up without zeroes or infinities. If not is there some restrictions on the properties I've used that prevents them from behaving in the way I understand way for imaginary exponents?
Comment: In the complex, you may not use $(a^b)^c=a^{bc}$.
Comment: In general $(z^a)^b$ is not the same as $z^{ab}$. (The expressions may not even be uniquely determined.)
Comment: Remarkably simple, thank you.
Answer: When using powers of complex numbers you will have to be careful, because in general they are not uniquely defined.
This leads to the power laws are not valid in a unchanged form, that is $(z^u)^v$ is only equal to $z^{uv}$ in some restricted sense.
The definition of complex powers is reduced to the definition of the (natural) logarithm (which in turn is not uniquely determined). We have
$$a^b = e^{b \ln a}$$
so we have
$$z^{uv} = e^{uv \ln z}$$
while
$$(z^u)^v = e^{v \ln z^u} = e^{v \ln e^{u \ln z}}$$
now it would be tempting to just use that $e^{\ln w} = w$, but that's only true in the real case, in the complex case we would have to take into account the multi-valuedness of $\ln$ so $e^{\ln w} = w + 2n\pi i$ which gives:
$$(z^u)^v = e^{v \ln e^{u \ln z}} = e^{v (u\ln z + 2n\pi i)} = e^{uv\ln z + v2n\pi i} = z^{uv}e^{2vn\pi i}$$
So let's see where your approach gets you:
$$(e^{2\pi i})^{b\ln a/2\pi} = e^{ib\ln a}e^{inb\ln a} = e^{i(n+1)b\ln a}$$
Now it may seem to clear, if $n=-1$ you actually get this to be $1$, but that one need not be $a^{bi}$, it won't if $b\ne 0$.


apache ext filter not working

Question: following the docs at :http://httpd.apache.org/docs/2.0/mod/mod_ext_filter.html
Cant get a simple filter to replace text on the page...
ExtFilterDefine fixtext mode=input cmd="/bin/sed s/works/sorta/ig"
        AddOutputFilter fixtext htm html
        SetOutputFilter fixtext

        <Location />
                SetOutputFilter fixtext
        </Location>

        <Directory />
                ExtFilterOptions LogStderr DebugLevel=0
        </Directory>

Answer: Correct syntax:
ExtFilterDefine fixtext mode=output intype=text/html \
                cmd="/bin/sed s/works/asdf/ig"

        <Location />
                SetOutputFilter fixtext
        </Location>

If anyone is trying to apply ExtFilter rules to Reverse Proxy sites, there is a bug:
http://objectmix.com/apache/706472-proxypass-extfilter.html
Comment: guys, can anyone confirm?  this is bug: http://objectmix.com/apache/706472-proxypass-extfilter.html

apache ext filter not working