Pandas overwrite based on column

Question: I have the following dataframes:
df1
index  | colA  | colB
0          a       1
1          b       2
2          a       9

df2
index  | colA  | colB
5          a       3
8          c       4

I want to update df1 based on df2, meaning for all rows "i" such that
df1['ColA'].iloc[i] == df2['colB'].iloc[i]

The index do not match so .update() does not work here.
Desired output:
df1
index  | colA  | colB
0          a       3
1          b       2
2          a       3

Comment: Seems like you want a mapping by colA?
Comment: @YOBEN_S I don't think this is `merge`.
Answer: You can do with boolean indexing:
idx = df1['colA'].values == df2['colA'].values
df1.loc[idx, 'colB'] = df2.loc[idx,'colB'].values

Comment: Getting KeyError: False using the above
Comment: works with the sample data on my computer. make sure you have the correct column name.

Pandas overwrite based on column


Defining Show on an arbitrary recursive type in Haskell

Question: I'm trying to make a custom type an instance of Show.
Here's theType, it's just a basic Set type.
data Set a = Insert a (Set a) | EmptySet

I'd like something like
Insert 1 (Insert 2 (Insert 3 EmptySet))

to display like
{1, 2, 3}

How do I do this? I tried doing it with string concatenation, but it seems like doing string interpolation is considered bad form (Haskell doesn't seem to natively support this?) Also, how do I get the curly braces around the list? So far, all I was able to cook up was this, which basically does nothing...
instance (Show a) => Show (Set a) where
     show EmptySet = ""
     show (Insert a as) = show a ++ show as

Also, I tried to use Hoogle and Hayoo to find the List implementation so I could see how this was implemented on Lists. I couldn't find it. Does anyone have any pointers on this? I tried searching "show::[a]->String", "Data.Lists", "Lists" etc....
Comment: By the way, this is probably a bad idea. The result of `show` should be valid Haskell code that produces a value equal to the one passed to `show`. I suggest defining a `fromList` function and making `show` on the set {1, 2, 3} produce e.g. `fromList [1, 2, 3]`; this is the approach taken by the standard Data.Map and Data.Set libraries. Alternatively, you could define your own function that does this to be called instead of `show` to view sets in this notation.
Answer: That type of yours is still homomorphic to a list.  Wherever that Show instance is defined; you can still use it:
toList (Insert a b) = a:toList b
toList EmptySet = []

instance Show a => Show (Set a) where
    show = show . toList

Answer: Here's a solution with direct recursion:
instance Show a => Show (Set a) where
  show = ('{' :) . go
    where
      go EmptySet            = "}"
      go (Insert x EmptySet) = show x ++ "}"
      go (Insert x xs)       = show x ++ ", " ++ go xs

If you don't like the inefficient use of (++), you can of course use difference lists:
instance Show a => Show (Set a) where
  show = ('{' :) . ($ []) . go
    where
      go EmptySet            = ('}' :)
      go (Insert x EmptySet) = shows x . ('}' :)
      go (Insert x xs)       = shows x . (", " ++) . go xs

That should do it; so, let's test:
> show (Insert 2 (Insert 3 (Insert 5 EmptySet)))
"{2, 3, 5}"

Comment: If you don't like the inefficient use of `(++)` you should implement `showsPrec` instead of `show`.
Comment: @SjoerdVisscher: I agree, of course, but I wanted to demonstrate the delta with the first implementation.
Answer: The data type might be recursive, but that's no reason for the function to be recursive.
import Data.List (intercalate)

instance Show a => Show (Set a) where
  show x = "{" ++ intercalate ", " (toList x) ++ "}"

This assumes you have a function toList :: Set a -> [a]. The recursion is hidden in there.
The List implementation is done via the showList function from the Show typeclass (so that Strings, a.k.a. [Char]s, can be displayed differently).
Comment: The set as you've defined it also has to contain elements of the same type. In `Insert a (Set a)`, it's all `a`s. So there shouldn't be a problem.
Comment: I'm kind of a noob, but doesn't this break because a list has to contain elements of all the same type? If I feed a list of numbers into this function, won't it barf a type error?


How does one show that the multi-class hinge loss upper bounds the 1-0 loss?

Question: I was trying to understand the mathematical claim that:
$$ \mathbb{1}\{ \hat y \neq y \} \leq \max_{j \in \{1,...,K \} } \left( \mathbb{1}\{ i \neq y\} + W^T_jx  - W^T_y x \right) $$
I tried showing it was true but got stuck. The part I do understand is when $\hat y = y$. In that case its trivial to show the bound because one just notices that if $j=y$ then $\mathbb{1}\{ j \neq y\} + W^T_jx  - W^T_y x = \mathbb{1}\{ y \neq y\} + W^T_yx  - W^T_y x =0$. Since one of the terms in the maximaziation is zero then the other ones don't matter because if they are less than zero they won't be chosen (so they can't violate the inequality) but if they are larger than 0 then that great, they make the inequality "easier" to satisfy. There is a zero so the value must be at least 0 which shows its greater than the LHS.
But I have problems with $\hat y \neq y$. If $j=y$ we have zero again for the same reason as in the previous paragraph. But if $j \neq y$ then we have:
$$ \mathbb{1}\{ j \neq y\} + W^T_jx  - W^T_y x = 1 + W^T_jx  - W^T_y x $$
since $j \neq y$ then it means $W^T_jx  - W^T_y x \neq 0$ (most likely not zero at least). However, my worry is that for all the remaining $j$'s (not equal to y) that they are negative enough to make the RHS less than 1 which makes the claimed inequality not hold. What is it about the problem that makes this impossible? I assume the inequality is correct since they are mentioned in university notes here.
Also, what I find extremely strange is that the right hand side is suppose to be a loss function but never does it seem to be a function of $\hat y$ (our prediction), at least not explicitly. Why is that? How would an ML algorithm be driven to improve $\hat y$ if it doesn't explicitly appear on the RHS? I assume it must implicitly appear or something of that sort so that we go minimize it, but its unclear to me.

Some progress? I noticed that since the RHS is a max and there is always a zero in the max (because of the case $j=y$) then if the max chooses a value such that $j \neq y$ then we have:
$$ 1 + W^T_j x - W^T_y x \geq 0 $$
which still doesn't guarantee its greater than 1 but at least its a new insight...
Answer: Using the notation $$L(j):=I(j\ne y) + (W^T_jx - W^T_yx),\tag1$$
the assertion is that
$$I(\hat y \ne y) \le\max_{j\in\{1,\ldots,K\}} L(j).\tag2$$
You can prove this assertion in one go, without the need to consider cases, as follows. The RHS of (2) is at least as big as $L(\hat y)$, since $\hat y$ is one of the $j$'s. Plugging $j=\hat y$ into (1) yields
$$
L(\hat y) := I(\hat y\ne y) + (W_{\hat y}^Tx - W^T_yx).\tag3 $$
But $W^T_{\hat y}x \ge W^T_yx$ since $\hat y$ by definition is the maximizer of $W^T_i$ over all $i$. Thus the parenthesized term in (3) is non-negative. Summarizing:
$$
\max_{j\in\{1,\ldots,K\}} L(j)\ge L(\hat y)\ge I(\hat y\ne y).
$$
Comment: is this something you already knew? I feel a little dum for not realizing this XD
Comment: what seems very mysterious to me is where that loss function came from in the first place...


Would the data on the RAID Card Cache and Drive Cache be lost when a kernel panic happens?

Question: Is a BBU necessary when you have A+B power?
Would the data on the RAID Card Cache and Drive Cache be lost when a kernel panic happens and you are forced to do a cold reset?
Comment: What is "A+B power"? This is not a term I'm familiar with.
Comment: @EvanAnderson Datacenter-provided [discrete A and B power feeds](http://onr.com/wp-content/uploads/2013/03/Power-Infrastructure1.png) distributed along separate paths and delivered to the cabinet.
Answer: Some of this has been covered here before... and here, too. I can't think of any situation where you wouldn't want a battery-backed or flash-backed cache unit on your hardware RAID controller. It's what makes write caching possible.
See: BBWC: in theory a good idea but has one ever saved your data?
If your system panics suddenly, the question as to what happens to in-flight disk transitions depends a bit on the nature of the crash, when it happens, the filesystem in use and your storage subsystem. I've had data corruption in some cases and I've also had the RAID controller cache save the day.

Cache Status Details: The current array controller had valid data
  stored in its battery/capacitor backed write cache the last time it
  was reset or was powered up. This indicates that the system may not
  have been shut down gracefully. The array controller has automatically
  written, or has attempted to write, this data to the drives. This
  message will continue to be displayed until the next reset or
  power-cycle of the array controller.

With regard to A/B power feeds, it's nice that your datacenter or facility provide it, but it should have no bearing on your RAID controller caching decision.
Comment: I think the RAID card's software doesn't recognize if there is an OS crash so it won't force itself to write all the data in the cache to the disks. Instead, it'll keep the data like nothing happened to the OS and BBU will power the cache during a cold reboot and then after the reboot, the RAID card will write the data on the cache to the disks.
Comment: Which may or may not be successful... There's no promise that there won't be data loss or corruption. But that doesn't matter. It makes sense to have a flash or battery-backed cache on hardware RAID controllers, regardless of the datacenter power situation.
Comment: What about the drive cache, though? I think it's not safe to use drive caches.
Comment: @ispirto Don't use them.
Answer: A "real" hardware RAID controller (not a "fake" RAID that relies on the host CPU) is a freestanding computer separate from the host computer in which it's installed. A hardware RAID controller will handle reading/writing from the disks as the operating system makes requests, but it does not specifically rely on anything running inside the host computer operating system to function. The controller's operating system will continue running (and flushing cache, etc) even if the host computer's operating system crashes.
Edit:
I didn't mention the battery backed cache at all. I'm so used to RAID controllers like Dell's PERC series that disable write-back caching when there's no battery that I just consider a battery backup to be an integral part of any serious RAID controller.
re: the kernel panic scenario - It's worth noting that your RAID controller isn't going to save you at all if your operating system or applications aren't leaving the filesystem or their data files in a consistent state at the end of each write. If you're using a journaling filesystem or database applications that are ACID-compliant then your odds of losing data are a lot lower than if you're using filesystems or applications that are capable of leaving their on-disk data structures in an inconsistent state.
Comment: So if I understand correctly,

When a panic happens, if the filesystem finished the writes, some of the data that filesystem writes may be still on the RAID card's cache. So if we give the RAID card enough time before the cold reset, wouldn't it write the data on the cache to the disks?
Comment: It looks like there is no guarantees whether or not the RAID card will flush its cache to the disk. So, yeah a BBU is a must. Thank you.
Answer: Yes, redundant power, while reducing the need for a BBU, does not eliminate that need.
Consider the case where you wire up A/B power incorrectly, for example.
The additional cost for a BBU is usually worth it where your data matters e.g. storage node, DB, etc.
Comment: The machine's power distribution board or motherboard might also fail. Although personally I've seen more RAID card failures.


Is my RabbitMQ cluster Active Active or Active Passive?

Question: I have created a cluster consists of three RabbitMQ nodes using join_cluster command.
i.e.
<code>rabbitmqctl –n rabbit2@MYPC1 join_cluster rabbit2@MYPC1
</code>
(currently the cluster runs on a single computer)
Questions:
In the documents it says there is one implemetation for active passive and one for active active.

What did I configure?
How do I know?
How can it be changed?
Is there a big performance trade off between Active Active & Active Passive?
What is the best practice to interact with active/active?
i.e. install a load balancer? apache that will round robin
What is the best practice to interact with active/passive?
if I interact with only the active - this is a single point f failure

Thanks.
Answer: I have been doing some research into availability options with RabbitMQ and while I am still fairly new, I'll attempt to answer your questions with the knowledge I do have. Please understand that these answers are not intended to be comprehensive.
Before getting to the questions and answers, I think it's worth pointing out that I think using the terms Active/Active and Active/Passive in the context of a cluster running on a single computer does not really apply.  Active/Active and Active/Passive are typically terms used to describe highly available clusters where you have a system of more than one logical server (in your case, multiple RabbitMQ clusters), shared/redundant storage, network capabilities, power, etc.

What did I configure?
Without any load balancing for the nodes in your cluster or queue mirroring you have neither, meaning you do not have a highly available cluster.
How do I know?
RabbitMQ does not provide any connection management so traffic with a failed node will not automatically be passed on to a different node, which is required for an active/active cluster. Without queue mirroring you do not have fully redundant nodes in your cluster, which is required for active/passive.
How can it be changed?
Even if you implement load balancing and/or queue mirroring you are missing a number of requirements to offer a highly-available RabbitMQ cluster.  Primarily, with a RabbitMQ cluster you only have a single logical broker (at least two are required for an HA cluster).
Is there a big performance trade off between Active Active & Active Passive?
I think you will start seeing performance penalties as you start introducing data replication and/or redundancy, which would affect both Active/Active and Active/Passive. If you are using synchronous data replication then you will see a bigger performance hit than if you replicate data asynchronously. There's a lot more to it, but to me this feels like there may be a bigger performance hit by using Active/Active but this depends heavily on how fast all of the pieces are working together. In Active/Passive where you may be using asynchronous replication across servers your performance may appear better but in a failover situation you would need to wait for that replication to complete before you can switch to your secondary server.
What is the best practice to interact with active/active? i.e. install a load balancer? apache that will round robin
RabbitMQ recommends using a load balancer so that you do not have to leak details about the nodes in your cluster to the clients.
What is the best practice to interact with active/passive? if I interact with only the active - this is a single point of failure
It is a point of failure but with Active/Passive you can implement a failure strategy to retry the next available server or all remaining servers. With these strategies in place you can establish a scenario where the capabilities of your cluster are merely degraded while a failover is happening instead of totally unavailable. Also, you can interact with the passive side but the types of interactions may be very different (i.e. read-only access) since there may be fewer resources available on the passive side and there may be delays in data replication.

Here are some references used to gather this information:

High-Availability Cluster on Wikipedia
Clustering with RabbitMQ
Highly Available Queues in a RabbitMQ Cluster
High Availability in RabbitMQ


Menu responsivo usando Bootstrap

Question: Estou querendo fazer um menu fixo usando booststrap, de tal forma que seja responsivo; ou seja, quando diminuir a tela o menu vire um ícone.
Porém, quando eu diminuo a tela do viewport o ícone parece estar lá, mas não aparece visualmente.

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#menu" aria-controls="menu" aria-expanded="false" aria-label="Menu Colapso">

     </button>

             Item 1

             Item 2

             Item 3

             Item 4

             Item 5

             Item 6

             Item 7

             Item 8

Código CSS:
.navegacao {
            height: 50px;
            background-color: black;
            box-shadow: 1px 2px #54542c;
            color: aliceblue;
            text-align: center;
}

.nav-menu > li {
            padding: 0 0 0 30px;
}

Comment: Provavelmente este seu Css está ocasionando o problema.
Comment: Eu já retirei todo meu css externo e ainda não aparece visualmente o ícone, mas quando passo com mouse em cima, vejo que está alí o ícone.
Comment: Qual versão do  bootstrap está usando?
Comment: Bootstrap v4.1.3
Answer: Como você pode ver no exemplo abaixo, o menu Hamburger está lá, acontece que o seu Css estava sobrescrevendo o do Bootstrap. Existem algumas classes que podem te ajudar a estilizar sem precisar mexer no Css, como navbar-dark por exemplo que seta a cor de fundo da barra de menu para um tom cinza escuro, como pode ver melhor aqui:

.navegacao {
  box-shadow: 1px 2px #54542c;
  text-align: center;
}

.nav-menu>li {
  padding: 0 0 0 30px;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#menu" aria-controls="menu" aria-expanded="false" aria-label="Menu Colapso">

     </button>

          Item 1

          Item 2

          Item 3

          Item 4

          Item 5

          Item 6

          Item 7

          Item 8

Comment: Boa, mas vc não precisa ficar preso nas cores do BS4 vou dar uma explicação tb :)
Comment: Boa Hugo, posta aí sim. Fiquei com medo de confundir ele.
Comment: hahaha, até pode ser mesmo... depois que terminei pode ser que os iniciantes tenham alguma dificuldade nos detalhes, mas tentei ser bem didático...
Answer: É o seguinte, vc deixou de usar as classes de cor originais do Bootstrap, tipo navbar-light ou navbar-dark, assim como o bg-light ou bg-dark etc, por isso o seu button não aparece, pois só aplica a cor nele caso tenha uma classe de cor na navbar
Uma forma de conseguir colocar uma cor no button sem ficar preso nas cores padrão do Bootstrap e colocar a cor manualmente criando uma classe custom.
.custom .navbar-toggler-icon {
  background-image: url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='rgba(255,0,0, 1)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 8h24M4 16h24M4 24h24'/%3E%3C/svg%3E");
}

.custom.navbar-toggler {
  border-color: rgba(255,0,0,1);
}

Se vc reparar vai ver que dentro do button tem um span. No button fica a cor da borda, e nesse span de dentro fica uma background-imagem um svg que vc pode trocar a cor para a cor que quiser no stroke.
Esse é o botão padrão do Bootstrap 4, ele assume a cor junto com as classes de cor

<button class="navbar-toggler custom" type="button" data-toggle="collapse" data-target="#menu" aria-controls="menu" aria-expanded="false" aria-label="Menu Colapso">

</button>

Veja esse exemplo para entender melhor.
OBS: vc tinha colocado um valor de height de 50px isso limita o funcionamento correto da navbar, então removi nesse exemplo.

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

        <button class="navbar-toggler custom" type="button" data-toggle="collapse" data-target="#menu"
            aria-controls="menu" aria-expanded="false" aria-label="Menu Colapso">

        </button>

                    Item 1

                    Item 2

                    Item 3

                    Item 4

                    Item 5

                    Item 6

                    Item 7

                    Item 8

Comment: Pq é o inverso. navbar-dark fica com o texto branco e navbar-light com o texto escuro ?
Comment: @GatodeSchrödinger não tem segredo, basta ler a resposta com calma, se o fundo eh preto o texto não pode ser preto tbm correto. Então se vc coloca uma classe de bg preto o texto tem que ser branco, a não ser que vc use um leitor de tela, ai nem precisa de CSS...
Comment: Ah, entendi. Ali vc está mencionando a cor do navbar e não do texto. Então automaticamente o bootstrap coloca a cor de texto que fica mais visível em relação a cor do navbar.

Menu responsivo usando Bootstrap


Fiz um calendário e as datas estão erradas

Question: Sou iniciante e estou aprendendo na marra, estou a uma semana quebrando a cabeça para resolver esse problema. Alguns meses do calendário estão certos outros com mais dias outros com menos. Alguém com mais experiencia consegue ver o que eu não vejo?

// Informações como Data e Hora
var data = new Date()
var ano = data.getFullYear()
var calendarioAno = ano
var meses = data.getMonth()
var NomesMeses = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro']

// Ligação com o HTML
var relogio = document.getElementById('horaRes')
var res = document.getElementById('ano')
var AnoNoCalendario = document.getElementById('AnoNoCalendario')
var mes = document.getElementById('mes')

// ligção com os dias da semana
var listaItens = [
    item0 = document.getElementById('item0'),
    item1 = document.getElementById('item1'),
    item2 = document.getElementById('item2'),
    item3 = document.getElementById('item3'),
    item4 = document.getElementById('item4'),
    item5 = document.getElementById('item5'),
    item6 = document.getElementById('item6'),
    item7 = document.getElementById('item7'),
    item8 = document.getElementById('item8'),
    item9 = document.getElementById('item9'),
    item10 = document.getElementById('item10'),
    item11 = document.getElementById('item11'),
    item12 = document.getElementById('item12'),
    item13 = document.getElementById('item13'),
    item14 = document.getElementById('item14'),
    item15 = document.getElementById('item15'),
    item16 = document.getElementById('item16'),
    item17 = document.getElementById('item17'),
    item18 = document.getElementById('item18'),
    item19 = document.getElementById('item19'),
    item20 = document.getElementById('item20'),
    item21 = document.getElementById('item21'),
    item22 = document.getElementById('item22'),
    item23 = document.getElementById('item23'),
    item24 = document.getElementById('item24'),
    item25 = document.getElementById('item25'),
    item26 = document.getElementById('item26'),
    item27 = document.getElementById('item27'),
    item28 = document.getElementById('item28'),
    item29 = document.getElementById('item29'),
    item30 = document.getElementById('item30'),
    item31 = document.getElementById('item31'),
    item32 = document.getElementById('item32'),
    item33 = document.getElementById('item33'),
    item34 = document.getElementById('item34'),
    item35 = document.getElementById('item35'),
    item36 = document.getElementById('item36'),
    item37 = document.getElementById('item37'),
    item38 = document.getElementById('item38'),
    item39 = document.getElementById('item39'),
    item40 = document.getElementById('item40'),
    item41 = document.getElementById('item41'),
]

// O que escreve no HTML
res.innerHTML += ` ${ano}`
AnoNoCalendario.innerHTML = `${calendarioAno}`
mes.innerHTML = `${NomesMeses[meses]}`

// Função do relogio
function HoraAtual(){
    hoje = new Date()
    hora = hoje.getHours()
    minutos = hoje.getMinutes()
    segundos = hoje.getSeconds()
    relogio.innerHTML = `${hora} horas ${minutos} minutos ${segundos} segundos`
    setTimeout('HoraAtual()', 500)

}

//Diminui os anos no calendário
function AnoAnterior(){
    calendarioAno -= 1
    AnoNoCalendario.innerHTML=`${calendarioAno}`
    escreverCal()
}
//Aumenta os anos no calendário
function AnoPosterior(){
    calendarioAno += 1
    AnoNoCalendario.innerHTML=`${calendarioAno}`
    escreverCal()
}

function botãoCima(){
    if (meses == 0){
        AnoAnterior()
        meses = 11
        mes.innerHTML = `${NomesMeses[meses]}`
    }else{
        meses -= 1
        mes.innerHTML = `${NomesMeses[meses]}`
    }
    escreverCal()
}

function botãoBaixo(){
    if (meses == 11){
        AnoPosterior()
        meses = 0
        mes.innerHTML = `${NomesMeses[meses]}`
    }else{
        meses += 1
        mes.innerHTML = `${NomesMeses[meses]}`
    }
    escreverCal()
}

function diasDoMes(mes, ano){
    return new Date(ano, mes, 0).getDate();
}

function diaDaSemana(mes, ano){
    return new Date(ano, mes).getDay();
}

function escreverCal() {
    var Dsemana = diaDaSemana(meses, calendarioAno);
    var Qmes = diasDoMes(meses, calendarioAno);
    for (var contador=0; contador < 41; contador++){
        listaItens[contador].innerText = ''
    }
    for (var c = Dsemana; c < (Qmes+Dsemana); c++) {
        listaItens[c].innerHTML += `${c - Dsemana +1 }`
    }
}
escreverCal()
body{
    background: rgb(32, 32, 32);
    font: normal 18pt Arial;
}

header{
    color: white;
    text-align: center;
}

section#relogio{
    text-align: center;
    color: white;
    background: rgb(14, 15, 29);
    border-radius: 15px;
    padding: 10px;
    width: 370px;
    margin: auto;
    box-shadow: 5px 5px 5px black;
}

section#calendario{
    background: rgb(241, 241, 241);
    border-radius: 10px;
    padding: 15px;
    width: 800px;
    margin: auto;
    box-shadow: 5px 5px 5px black;
    margin-top: 20px;
}

.conteiner{
    display: grid;
    grid-template-columns: repeat(7, auto);
    grid-gap: 20px;
    font: 16px;
    text-align: center;
    margin: auto;
}

div#selectAno{
    text-align: center;
    margin: auto;
}
button#botãoEsquerda{
    right: 10px;
    top: -3px; position: relative;
}
button#botãoDireita{
    left: 10px;
    top: -3px; position: relative;
}

button#botãoCima{
    float: right;
}
button#botãoBaixo{
    float: right;
}

footer{
    color: whitesmoke;
    text-align: center;
    margin-top: 10px;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calendário</title>
    <link rel="stylesheet" href="estilo.css">

Calendário

            <button id="botãoEsquerda" onclick="AnoAnterior()">←</button>

            <button id="botãoDireita" onclick="AnoPosterior()">→</button>

            <button id="botãoCima" onclick="botãoCima()">↑</button>
            <button id="botãoBaixo" onclick="botãoBaixo()">↓</button>

Domingo

Segunda

Terça

Quarta

Quinta

Sexta

Sabádo

    Instagram: @_danielgoulart

Answer: O problema está aqui:
function diasDoMes(mes, ano){
    return new Date(ano, mes, 0).getDate();
}

Em vez de teres (ano, mes, 0) deves ter (ano, mes + 1, 0), a razão é que 0 na posição do dia vai dar o último dia do mês anterior. Ora sendo que queres o ultimo dia do mês que foi passado no argumento da função deves somar + 1.

Nota: fiz uma biblioteca que faz isto à uns anos e é usada em produção em várias aplicações.
Se for útil usa. https://github.com/SergioCrisostomo/js-calendar

Versão corrigida:

// Informações como Data e Hora
var data = new Date()
var ano = data.getFullYear()
var calendarioAno = ano
var meses = data.getMonth()
var NomesMeses = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro']

// Ligação com o HTML
var relogio = document.getElementById('horaRes')
var res = document.getElementById('ano')
var AnoNoCalendario = document.getElementById('AnoNoCalendario')
var mes = document.getElementById('mes')

// ligção com os dias da semana
var listaItens = [
  item0 = document.getElementById('item0'),
  item1 = document.getElementById('item1'),
  item2 = document.getElementById('item2'),
  item3 = document.getElementById('item3'),
  item4 = document.getElementById('item4'),
  item5 = document.getElementById('item5'),
  item6 = document.getElementById('item6'),
  item7 = document.getElementById('item7'),
  item8 = document.getElementById('item8'),
  item9 = document.getElementById('item9'),
  item10 = document.getElementById('item10'),
  item11 = document.getElementById('item11'),
  item12 = document.getElementById('item12'),
  item13 = document.getElementById('item13'),
  item14 = document.getElementById('item14'),
  item15 = document.getElementById('item15'),
  item16 = document.getElementById('item16'),
  item17 = document.getElementById('item17'),
  item18 = document.getElementById('item18'),
  item19 = document.getElementById('item19'),
  item20 = document.getElementById('item20'),
  item21 = document.getElementById('item21'),
  item22 = document.getElementById('item22'),
  item23 = document.getElementById('item23'),
  item24 = document.getElementById('item24'),
  item25 = document.getElementById('item25'),
  item26 = document.getElementById('item26'),
  item27 = document.getElementById('item27'),
  item28 = document.getElementById('item28'),
  item29 = document.getElementById('item29'),
  item30 = document.getElementById('item30'),
  item31 = document.getElementById('item31'),
  item32 = document.getElementById('item32'),
  item33 = document.getElementById('item33'),
  item34 = document.getElementById('item34'),
  item35 = document.getElementById('item35'),
  item36 = document.getElementById('item36'),
  item37 = document.getElementById('item37'),
  item38 = document.getElementById('item38'),
  item39 = document.getElementById('item39'),
  item40 = document.getElementById('item40'),
  item41 = document.getElementById('item41'),
]

// O que escreve no HTML
res.innerHTML += ` ${ano}`
AnoNoCalendario.innerHTML = `${calendarioAno}`
mes.innerHTML = `${NomesMeses[meses]}`

// Função do relogio
function HoraAtual() {
  hoje = new Date()
  hora = hoje.getHours()
  minutos = hoje.getMinutes()
  segundos = hoje.getSeconds()
  relogio.innerHTML = `${hora} horas ${minutos} minutos ${segundos} segundos`
  setTimeout('HoraAtual()', 500)

}

//Diminui os anos no calendário
function AnoAnterior() {
  calendarioAno -= 1
  AnoNoCalendario.innerHTML = `${calendarioAno}`
  escreverCal()
}
//Aumenta os anos no calendário
function AnoPosterior() {
  calendarioAno += 1
  AnoNoCalendario.innerHTML = `${calendarioAno}`
  escreverCal()
}

function botãoCima() {
  if (meses == 0) {
    AnoAnterior()
    meses = 11
    mes.innerHTML = `${NomesMeses[meses]}`
  } else {
    meses -= 1
    mes.innerHTML = `${NomesMeses[meses]}`
  }
  escreverCal()
}

function botãoBaixo() {
  if (meses == 11) {
    AnoPosterior()
    meses = 0
    mes.innerHTML = `${NomesMeses[meses]}`
  } else {
    meses += 1
    mes.innerHTML = `${NomesMeses[meses]}`
  }
  escreverCal()
}

function diasDoMes(mes, ano) {
  return new Date(ano, mes + 1, 0).getDate();
}

function diaDaSemana(mes, ano) {
  return new Date(ano, mes).getDay();
}

function escreverCal() {
  var Dsemana = diaDaSemana(meses, calendarioAno);
  var Qmes = diasDoMes(meses, calendarioAno);
  for (var contador = 0; contador < 41; contador++) {
    listaItens[contador].innerText = ''
  }
  for (var c = Dsemana; c < (Qmes + Dsemana); c++) {
    listaItens[c].innerHTML += `${c - Dsemana +1 }`
  }
}
escreverCal()
body {
  background: rgb(32, 32, 32);
  font: normal 18pt Arial;
}

header {
  color: white;
  text-align: center;
}

section#relogio {
  text-align: center;
  color: white;
  background: rgb(14, 15, 29);
  border-radius: 15px;
  padding: 10px;
  width: 370px;
  margin: auto;
  box-shadow: 5px 5px 5px black;
}

section#calendario {
  background: rgb(241, 241, 241);
  border-radius: 10px;
  padding: 15px;
  width: 800px;
  margin: auto;
  box-shadow: 5px 5px 5px black;
  margin-top: 20px;
}

.conteiner {
  display: grid;
  grid-template-columns: repeat(7, auto);
  grid-gap: 20px;
  font: 16px;
  text-align: center;
  margin: auto;
}

div#selectAno {
  text-align: center;
  margin: auto;
}

button#botãoEsquerda {
  right: 10px;
  top: -3px;
  position: relative;
}

button#botãoDireita {
  left: 10px;
  top: -3px;
  position: relative;
}

button#botãoCima {
  float: right;
}

button#botãoBaixo {
  float: right;
}

footer {
  color: whitesmoke;
  text-align: center;
  margin-top: 10px;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Calendário</title>
  <link rel="stylesheet" href="estilo.css">

Calendário

      <button id="botãoEsquerda" onclick="AnoAnterior()">←</button>

      <button id="botãoDireita" onclick="AnoPosterior()">→</button>

      <button id="botãoCima" onclick="botãoCima()">↑</button>
      <button id="botãoBaixo" onclick="botãoBaixo()">↓</button>

Domingo

Segunda

Terça

Quarta

Quinta

Sexta

Sabádo

  Instagram: @_danielgoulart


Como retornar uma parte de uma string (um elemento html) em php?

Question: Estou fazendo um "recurso técnico" para poder retornar o status dos servidores da SEFAZ de emissão de notas fiscais utilizando PHP. Para isso, eu tenho até o momento o código abaixo:
function get_content($URL){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $URL);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

$d = get_content('http://www.nfe.fazenda.gov.br/portal/disponibilidade.aspx');
echo $d;

Este código me retorna a página que a receita disponibiliza sem precisar de certificado digital para ver o status dos servidores.
Preciso saber como eu posso fazer para pegar somente um elemento HTML existente dentro da variável $d (o elemento é o table.tabelaListagemDados) e a partir dos valores dele posso fazer tratamentos.
Sei que eu consigo fazer o tratamento dessa informação utilizando javascript (puro, com AngularJS ou com jQuery) mas se existir algum método através do PHP é melhor pois assim eu consigo retornar somente um JSON e não uma página inteira.
Alguém vê uma solução sobre como eu posso fazer para pegar somente esse elemento dentro da página?
Comment: Estes links devem ajudar: http://pt.stackoverflow.com/questions/44694/capturar-e-filtrar-resultado, http://pt.stackoverflow.com/questions/78621/como-extrair-dados-espec%C3%ADficos-de-um-arquivo-html-com-php
Comment: Com certeza @bfavaretto! Eles me ajudaram bastante! deu trabalho mas ta lá a biblioteca (se precisar o link ta na pergunta)
Answer: Veja se isso te ajuda:
$data = get_content('http://www.nfe.fazenda.gov.br/portal/disponibilidade.aspx');
$dom = new domDocument;
@$dom->loadHTML($data);
$dom->preserveWhiteSpace = false;
$tables = $dom->getElementsByTagName('table');
$rows = $tables->item(1)->getElementsByTagName('tr');

foreach ($rows as $row) {
        $cols = $row->getElementsByTagName('td');
        print_r($cols);
}

Comment: tks @Samir Braga
Comment: kra isso me ajuda sim mas não posso pegar somente os elementos tr dentro da table... lá na sefaz eles enfiaram uma tag caption que contém a hora do resultado de consulta, isso é interessante também
Comment: assim que tiver tudo certinho, retornando como JSON eu posto na wiki do stack
Answer: Fala galera, consegui resolver meu problema. Abaixo está o script que pega a página que mostra a disponibilidade dos webservices de envio de nota fiscal eletronica e transforma o conteúdo em um json.
https://github.com/leandroluk/wsDisponibilidadeSefaz/
Ta ai pra quem quiser usar, fiquem a vontade, mas por favor deixem os créditos rs.


Views filters on exposed block - Not working initially

Question: I have a view with exposed filters "status" already set default to "ready".
The view filters are exposed in a block.
When I first open the view page, the status "ready" is ignored and it only applies the filter when I click on the "Submit" button in the exposed form.
I want the status "ready" to be applied when I open the view page.
This works great if the filters are not in an exposed block... but I need them to be...
What can I do?
Comment: Did you find a solution to this? I have a similar issue. Apply/Reset does not work initially but it starts to work when I use the pagination. I typed this in console (`Drupal.views.instances`) and noticed that `exposedAjaxForm` is missing initially.
Answer: Download and enable Better Exposed Filters.
You should find a new setting under Exposed Form, in BEF Settings check "Autosubmit" and that might solve your problem.
Comment: Hi, thank you for your answer. Autosubmit is not a solution, I really need the submit button.


jquery not calling ajax handler

Question: This should be a really simple fix, but I am pulling my hair out.
This part of the site is really simple. I have a .js file that uses ajax to insert a post into the database when submit is clicked. I get the success part of the jquery, but nothing ever gets put into the database.
Here is the jquery in the $(document).ready(function():
<code>   //Button for profile post
        $('#submit_profile_post').click(function(){

            $.ajax({
                type: "POST",
                url: "includes/handlers/ajax_submit_profile_post.php",
                data: $('form.profile_post').serialize(),
                success: function(msg) {
                    $("#post_form").modal('hide');
                    location.reload();
               },
                error: function() {
                    alert('Failure');
                }
            });

        });
</code>
Here is the ajax handler:
<code><?php
require '../../config/config.php';
include("../classes/User.php");
include("../classes/Post.php");
include("../classes/Notification.php");
    if(isset($_POST['post_body'])) {
        $post = new Post($con, $_POST['user_from']);
        $post->submitPost($_POST['post_body'], $_POST['user_to']);
    }

    ?>
</code>
As I said, If I add an alert under the jquery success, I get it just fine but nothing happens after that.
Any help would be greatly appreciated!
Comment: you will need to include the content of the php scripts (removing credentials) as well as potentially test the php scripts with different js code to verify that they are working as expected.
Comment: try adding `contentType:'application/json', dataType: "text",`
Comment: is there a request triggered? or you don't get a response..  and which response are you expecting?
Comment: @GeorgeCampbell, PHP does not understand JSON content request bodies out of the box. You have to manually read the raw input in order to get it.
Comment: Is `$_POST['post_body']` set? Can you successfully echo `$_POST['user_from']` on your php page? Does your instantiation of `Post` accept the format in which `$_POST['user_from']` is (unlikely)? Finally, what does your PHP error log say.
Comment: im sure it is easier than you think https://www.w3schools.com/js/js_json_php.asp
Comment: @GeorgeCampbell I tried adding in the content type and nothing changed.
Comment: try to see what data your php file receives, maybe with ECHO ?
Comment: Tried that and it doesn't echo anything. I even tried to just add an echo saying something random to see if the ajax file is called and nothing. The crazy part is that I added an alert under the success part of the jQuery to make sure that I am getting a success and that works. It is almost as though the connection isn't happening.
Answer: Try using FormData

var fd = new FormData();
fd.append('field', value);

$.ajax({
    url: 'http://example.com/script.php',
    data: fd,
    processData: false,
    contentType: false,
    type: 'POST',
    `enter code here`
    success: function(data) {
        alert(data);
    }
});
Comment: did you debug to see the values reaching in your server side php?
Comment: Sorry. I am newer at this. How would I go about doing that? I have tried echoing out the info from the php file but nothing comes out

jquery not calling ajax handler


Redirect from "/mynode?language=de" to "/mynode" after storing the language in the cookie

Question: Is it possible to remove the "?language=de" query string after Drupal stores the current language in the session and/or the cookie?
I want this so that if someone who speaks French sends a link to someone who speaks German, they will by default send a link that shows in the target user's preferred language.
Answer: You want to send them the language code in the url with the link as http://mysite.com/de/my-url-path and then make sure that you've enabled both session and url as detection methods at admin/config/regional/language/configure
Comment: I assume this requires me to enable the URL language detector, the one that threatens to possibly break lots of public URLs? Such breakage would be unacceptable...


Como aplicar funções de "If" & "Else" para BigInteger?

Question: Tenho esse código em Long funcionando normalmente:
public static void main(String args[]){

  List<Long> lista = new ArrayList();

    for(long a = 1; a <= 100; a++){

    if(a%2==0) {}
            else if (a%3==0){}
            else {
             lista.add(a);
               }
         }
    System.out.println(lista);
   }
}

Fiz esse outro código em BigInteger para a mesma função, mas não funciona:
public static void main(String[] args) {

    List<BigInteger> lista = new ArrayList();

    BigInteger começo = new BigInteger("1");
    BigInteger fim = new BigInteger("100");
    BigInteger n0 = new BigInteger("0");
    BigInteger n2 = new BigInteger("2");
    BigInteger n3 = new BigInteger("3");

for (BigInteger a = começo; a.compareTo(fim) <= 0; a = a.add(BigInteger.ONE)) {

   if (a.divide(n2)==n0){}
   else if (a.divide(n3)==n0){}
   else {
       lista.add(a);
      }
    }
  System.out.println( lista );
  }
}

Answer: Você está apenas usando o método errado. No seu código original com long, você usava o % que é o resto da divisão. Já no seu código com BigInteger, você está usando divide, que faz divisão e não resto da divisão. Você deveria estar usando o método remainder ao invés disso.
Ainda há um outro problema. Você deveria usar o equals ao invés do ==. O motivo é o mesmo pelo qual não se deve comparar Strings com ==, ou seja, o == compara se dois objetos estão na mesma posição de memória, e não se têm conteúdos iguais.
Além disso, você também pode usar o método valueOf(long) que é bem mais prático do que o construtor que recebe uma String. Também é recomendado o uso das constantes BigInteger.ZERO, BigInteger.ONE e BigInteger.TEN.
Por fim, não é necessário ter cláusulas ifs e else ifs vazias, você sempre pode reorganizar a expressão booleana correspondente.
Eis o seu código resultante:
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

class Divisao {
    public static void main(String[] args) {
        List<BigInteger> lista = new ArrayList<>();

        BigInteger começo = BigInteger.ONE;
        BigInteger fim = BigInteger.valueOf(100);
        BigInteger n0 = BigInteger.ZERO;
        BigInteger n2 = BigInteger.valueOf(2);
        BigInteger n3 = BigInteger.valueOf(3);

        for (BigInteger a = começo; a.compareTo(fim) <= 0; a = a.add(BigInteger.ONE)) {
            if (!a.remainder(n2).equals(n0) && !a.remainder(n3).equals(n0)) {
                lista.add(a);
            }
        }
        System.out.println(lista);
    }
}

Eis a saída dele:
[1, 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 41, 43, 47, 49, 53, 55, 59, 61, 65, 67, 71, 73, 77, 79, 83, 85, 89, 91, 95, 97]

Veja aqui funcionando no ideone.
Comment: Obrigado Amigo, como faço o mesmo em vez de ser BigInteger em BigDecimal?
Comment: @Rafael Quase isso. A diferença é que o `equals(Object)` pode não ser o suficiente, uma vez que no `BigDecimal`, ele considera que os valores `123.456` e `123.4560` são diferentes porque os zeros à esquerda são considerados. Neste caso você usa o `compareTo(BigDecimal)` ou o `signum()`.


Como executar um código só depois de terminar outro?

Question: Preciso executar a busca das cidades só depois de terminar de carregar os estados dentro do select e capturar a ID. Estou pegando essa ID para enviar outro Ajax que vai popular as cidades deste estado dentro de um outro select.
O que está acontecendo é que antes do primeiro script popular os estados, a continuação do código acaba capturando o estado selecionado anteriormente e fazendo a busca para este estado e não para o que acaba de ser escolhido.

O que eu preciso é que o código espere o script popular os estados.

Sem saber para o que serve realmente, tentei usar o done achando que ele ia disparar a continuação do script só quando o outro script terminasse de popular os estados.
    $.ajax({
        url: 'http://cep.republicavirtual.com.br/web_cep.php',
        type: 'get',
        dataType: 'json',
        crossDomain: true,
        data:{
            cep: $('#cep').val(),
            formato:'json'
        },
        success: function(res){

            // Seleciona tipo de logradouro e logradouro do CEP.
            $('input[name=endereco]').val(res.tipo_logradouro+' '+res.logradouro);

            // Seleciona bairro do CEP.
            $('input[name=bairro]').val(res.bairro);

            // Seleciona o estado conforme valor recebido no json ...
            // Dispara um trigger para carregar as cidades do estado ...
            $("#estado option").each(function() {

                $(this).prop('selected', false);
                if ($(this).data("sigla") == res.uf) {

                    $(this).prop('selected', true);
                    $("#estado").trigger("change");
                }

            });

        }

    }).done(function(res){

        $(this).prop('selected', false);
        $("#cidade option").each(function() {

            console.log($(this).data("cityname"));

            if ($(this).data("cityname") == res.cidade) {

                $(this).prop('selected', true);
            }

        });

    });

Comment: Você precisa mover o código que está dentro do bloco `done` para o bloco `success`. O bloco `success` é executado quando chegar o retorna da chamada ajax, que é onde você quer executar a outra parte do código.
Answer: Você pode usar a opção async do ajax como false, leia mais aqui:
http://api.jquery.com/jquery.ajax/
Dessa forma o script espera todo o processo acabar pra dar continuidade ao código abaixo.
Exemplo do código com async:
$.ajax({
    url: 'http://cep.republicavirtual.com.br/web_cep.php',
    type: 'get',
    async: false,
    ...

Answer: Se o que você precisa fazer não é diretamente ligado ao resultado da chamada AJAX o ideal seria colocar em uma função a parte :
success: function(res){

           // Faça o que tem que fazer

            minhaFuncao();
            });

        }

// fora da função que fez a chamada

function minhaFuncao(){
  // Faça o que quiser depois que acabou
}

Comment: É diretamente ligado. A segunda etapa depende de informações da primeira.
Comment: então você coloca o código junto do restante no `sucess`


Sliding Popup in Drupal 6

Question: Im trying to create a sliding popup using jQuery in my drupal module .
Referring the code from:
http://karlagius.com/2009/02/08/creating-a-sitepoint-like-sliding-popup-in-jquery/
My popup window, defined in the module, is a html string (using divs, a, img etc) .
How do I pass this html string to .js file. It gets used there in .get(url, function(data)).
Tried using drupal_to_js and drupal_json, both returns the value 0, not the string.
Need some suggestion on how to proceed.
Answer: You need

a hook_menu() implementation that will provide you with the url:
a page callback funtion that does print() or echo on the html snippet, then exit(). So no drupal_to_js() or drupal_json().
Answer: You can pass it using drupal_add_js
Example
  // This will add variables in the Drupal.settings object
  drupal_add_js(array('my_module' => array('my_setting' => 'this_value')), 'setting');

You can access this variable like Drupal.settings.my_module.my_setting

Sliding Popup in Drupal 6


Statistical significance test with 1x2 data and faked 2x2 contingency table

Question: Medical scientists love p-values and in a publication, I found the following patient statistics table. I stumbled over the Number of patients line.

They divided their subject group into two subgroups TAV and BAV and I asked how they calculated the p-value, because you only have one characteristic BAV/TAV. If you look for instance at the Male row, you see that you can use a 2x2 contingency table consisting of 2 characteristics BAV/TAV and Male/Female and make e.g. a Fisher test.
What was done in the Number of patients row was to fake a 2x2 contingency table repeating and reversing the numbers:
$$\begin{array}{c|c}
347&32\\\hline
32&347
\end{array}
$$
From the viewpoint that they want to express how similar the number of patients are in the BAV and TAV group, this kind of makes sense because it gives a p-value of 1 (two tailed Fisher) when BAV and TAV have the same number of patients. However, I have never seen this and I cannot find any reference to such an approach.
Question: Can someone tell me whether it is correct what they did?
Comment: Do you mean 2x2 table???
Comment: In the title of the question, I really meant 1x2 because basically we have only 1x2 data. But I see your point that it might be confusing. Maybe we find a different title for the question that describes the problem better. Any suggestions?
Comment: No need. If you mean 1x2, let it be.
Answer: The only "right" way I can think of to analyze that type of patient row is to test whether the proportions are equal.  This can be done with a one way chi-square test, which is, indeed, a 1x2 table.
I've never seen the sort of procedure you mention - did they say in the article that that is what they did, or are you guessing/figuring out that that is what they did?
The next question is whether the two methods give the same results.  The table you  show doesn't give much, so let's test:
type <- c(TAV = 347, BAV = 32)
chisq.test(type)

and
x <- matrix(c(347,32,32,347),ncol = 2)
chisq.test(x)

give identical p values. The first is what I suggested, the second is what you said.
Comment: Thanks for pointing this out. I really know what they did because I asked. +1
Comment: Note, these are giving different p-values, it's just hard to tell since the p-value is so small.  If you change 347 to 50, you'll see different p-values.  I think this should be a one proportion z-test, please see my response
Comment: @pdeli If you have missing data, that is a different question. Feel free to ask your own question.
Comment: I tried your solution on my data, however I got an error "all entries of 'x' must be nonnegative and finite". I guess it is because I have missing values/data. Would you be so kind and complete your answer for cases with missing values/data?
Answer: The p-value calculations are a little confusing.  The p-values are trying to test whether the percentages are similar for the two subgroups.  For the first row "Number of patients" the % in TAV has to be 1-% in BAV.  Therefore, one should test whether p=0.5 for one proportion:
prop.test(221, 244, p=0.5, alternative="two.sided")

For the "Male Gender" row, the % of males in TAV does not have to be 1-% of males in BAV, so we have a different test.  You can actually fill out the table:
       Male   Female  Total
TAV    221     126     347
BAV    23      9       32
Total  244     135

This can be tested using Fisher's exact test (although Barnard's exact test is superior) giving the p-value reported.
> data<-matrix(c(221,126,23,9),ncol=2,byrow=TRUE)
> fisher.test(data,alternative="two.sided")

    Fisher's Exact Test for Count Data

data:  data
p-value = 0.4418
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
 0.2710563 1.5995457
sample estimates:
odds ratio
  0.686984


On Error not triggering on Rundeck from a Kubernetes app

Question: I'm running a Kubernetes/Docker job on Rundeck 2.11.5-1.  My job looks like:
Job
  Sub Job 1
    Remote Command (kubectl run command)
    On error
      Sub Job
  Sub Job 2
    Remote Command (kubectl run command)
    On error
      Sub Job

The problem I'm having is that if Sub Job 1 fails, its "On Error" does not trigger and Sub Job 2 runs as if all was well.
Is there something that kubectl needs to return to indicate there was an error?
What are some things I should look for/do to cause my job to stop on error.
Answer: I found the solution.  Add --restart=Never to the kubectl statement and the Rundeck job now correctly terminates on an apps failure.


In what game did Luis Suárez (seemingly) try to bite his own teammate?

Question: Here's a short clip showing Suárez apparently trying to bite his own Liverpool teammate, who was celebrating after a goal. When did this happen? Do we know any additional context that would explain what Suárez was doing and why he was trying to do it?

EDIT: I think @Ben is right. Suárez is trying to slide on his knees and failing. Momentum keeps his upper body moving forward even when his lower body has ground to a halt. His mouth is probably open because he's yelling (happily).
Comment: I don't think Suárez is trying to bite anyone here, I think he's just failing miserably at the sliding celebration maneuver.
Answer: This is Steven Gerrard of Liverpool (current Captain of the English national team and Liverpool) celebrating after the second goal of a game vs. Manchester United played on March 16, 2014 (the final score of that games was 3-0 for Liverpool). Gerrard scored on a penalty kick and the GIF above is the celebration after that goal.


An exercise in an introduction to the theory of groups

Question: 4.4 Let $G$ be a finite p-group; show that if $H$ is a normal subgroup of G having order $p$, then $H$ is a subgroup of $Z(G)$.
$Z(G)=\left\{x\in G| xy=yx, \forall y\in G \right\}.$
Can you help me solve it and explain in detail? Thank you very much. Good health!
Comment: Not following.  You start by assuming that $H$ is a normal subgroup of $G$ and then you want to show that $H$ is a subgroup of $G$?
Comment: *"show that if  is a normal subgroup of G having order , then  is a subgroup of "*. What do you mean ? If $H$ is a normal subgroup of $G$, then $H$ is a subgroup...
Comment: You must have mixed words: to prove that normal **subgroup** is a subgroup is pretty trivial...
Comment: sorry, prove $H$ is a subgroup of $Z(G)$.
Comment: $Z(G)=\left\{x\in G| xy=yx, \forall y\in G \right\}.$
Comment: Look up group center
Answer: Use the previous exercise (4.3), which states that $K\cap Z(G)\ne 1$ whenever $K\lhd G$. Now $H\cap Z(G)\ne 1$, and so $H\cap Z(G)$ has order $p$. So $H\cap Z(G) = H$.
Hint of Exercise 4.3: $K\lhd G$ implies that $K$ is a union of some conjugacy classes of $G$.
Comment: $H\cap Z(G)$ is a subgroup of $H$, and $H$ is a group of order $p$. Thus either $H\cap Z(G) = 1$ or $H\cap Z(G) = H$. In this case it cannot be $1$, so it is $H$. It's a typo.
Comment: Sorry, the question seems very stupid. Can you explain why there is this line $H\cap Z(G)=Z(G)$?
Comment: Thank you very much. I wish you good luck as you move on to new and different challenges.


Fermi - Walker coordinate system

Question: In which "differential geometry" book I can find the proof of the following statement?
Let $M$ be a lorentzian manifold. Given a timelike geodesic $γ$ and a point $p∈γ$, there is a neighborhood $U∋p$ equipped with coordinates, $x_0,x_1,x_2,x_3$ such that in the portion of $γ$ included in $U$, exactly along $γ$, the derivatives of the metric vanish in the said coordinates.
Many thanks!
Comment: Neither the fact nor it's proof is not specific to timelike geodesics in Lorentzian manifolds. Your search will be easier if you look for this kind of statement in general (Riemannian or Semi-Riemannian) manifolds with a metric tensor.
Answer: It's probably easier to give a sketch of proof for this than to search for a reference. Assume the geodesic $\gamma: (-a, a) \rightarrow M$ is given and $E_1(t) = \gamma^\prime(t) $ is the tangent vector field along $\gamma$. Assume in addition $\gamma(t)$ is parametrized by arclength, i.e. $g(E_1, E_1) = 1$ ($=-1$ in case of a timelike geodesic in a Lorentz manifold).
Let $E_i, 2\le i \le n$ an orthonormal extension of $E_1$ to a basis of $T_{\gamma(0)}M$ and let $E_i(t) $ the parallel transport of $E_i$ along $\gamma$. Since the connection is compatible with the metric, the frame $E_i(t)$ remains orthonormal along $\gamma$.
Now define the coordinate system in some neighbourhood of $0$ by
$x: \mathbb{R}^n \rightarrow M$ by
$$(x^1, \ldots, x^n) \mapsto \exp_{\gamma(x^1)}(\sum_{i=2}^n(x^i E_i(\gamma(x^1)))$$
It has to be shown that this is in fact a coordinate system and that it has the desired properties.
Note first, that the image of the $x^1$ -axis is just a portion of the geodesic near the origin, since $(t, 0,\ldots,0)$ maps to $\exp_{\gamma(t)}(0) = \gamma(t)$
Also note that, along $\gamma$, the tangent vector $\frac{\partial}{\partial x^i}$ is just $E_i$, since the differential of the exponential map in $0$ (this is $0_{\gamma(x^1)}$) is just the identity. So the differential of the map has full rank along $\gamma$, and so, by the implicit function theorem, is a local diffeomorphism in a neighbourhood of the $x^1$-axis, in other words it's coordinate system.
The metric tensor along $\gamma$ is given by $g_{ij} = g(E_i, E_j) = \delta_{ij}$ by construction.
To see that it's derivatives vanish along $\gamma$ note that
 $$(*)\quad E_k g(E_i, E_j) = g(\nabla_{E_k}E_i, E_j) + g(E_i, \nabla_{ E_k} E_j) $$
This is $=0$ for $k=1$ since the $E_i$ are parallel along $\gamma$ (including $E_1$, since $\gamma $ is a geodesic).
For $k\ge 2$ consider first $i=k$. Since the curves
$$t\mapsto \exp_{\gamma(x^1)}(tE_k)$$
are normal geodesics to $\gamma$, $\nabla_{E_k}E_k=0$ along $\gamma$.
Similarly, for $i, j>1$ , $$t\mapsto \exp_{\gamma(x^1)}(t(E_i + E_j))$$
is a geodesic normal to $\gamma$, so
$$\nabla_{E_i+E_j}(E_i+E_j)=\nabla_{E_i}E_i+ \nabla_{E_i}E_j+\nabla_{E_j}E_i+ \nabla_{E_j}E_j=\nabla_{E_i}E_j+\nabla_{E_j}E_i=0$$
so $\nabla_{E_i} E_j = -\nabla_{E_j} E_i$. On the other hand, since the $E_i$ are coordinate vector fields, $[E_i,E_j]=\nabla_{E_i} E_j  -\nabla_{E_j} E_i=0$. Combining these identities we get $\nabla_{E_i} E_j=-\nabla_{E_j} E_i$, so this has to be $=0$ as well. This implies that the left hand side in $(*)$ is $=0$ if $i,j, k >1$
Still missing is the case
$$E_kg(E_1, E_i) = g(\nabla_{E_k}E_1,E_i)+g(E_1,\nabla_{E_k} E_i) $$
with $k>1$
If $i\neq 1$ then the second term on the right hand side vanishes according to the previous results, so only the first remains. Using again $[E_1, E_k]=0$ we see that $\nabla_{E_k}E_1=\nabla_{E_1}E_k=0$ since $E_k$ is parallel along $\gamma$ by construction. Incidentally this then also cover the case $i=1$.
(A proof in a textbook is, e.g.,  found in Klingenbergs Riemannian Geometry, Proposition 1.12.1 , but you will very likely have difficulties to find your way through the notation you'll find there).
(The 'classical' case of a Riemannian Normal coordinate system where you have the desired properties in one given point can be found in most books on Differential Geometry by searching for said term 'Riemannian Normal coordinates', e.g. in Spivaks' Comprehensive Introduction to Differential Geometry, vol 2 (2nd edition), page 159. The proof has to go through essentially the same steps, the main difference is that the distinction $k=1$ vs $k>1$ is not necessary).

Fermi - Walker coordinate system


General formula for n-Simplex root?

Question: Given a number $k$, is it possible to find which term in the $n$-Simplex sequence it corresponds to? I've only been able to find formulae for the triangular root.
Examples:
For $k = 10$ in the triangular (2-Simplex) number sequence, the triangular root would be 4, since the fourth triangular number is 10.
For $k = 210$ in the polytope (4-Simplex) number sequence, the pentatonic root would be 7, since the seventh pentatope number is 210.
Answer: In order to do this in general, you would have to find the inverse function of the map
$$
n \mapsto \binom{n+k-1}{k}
$$
for fixed $k$. For small $k$, you got a nice little polynomial, and you may succeed. For large $k$, if you succeed, you've done better than these guys:
https://mathoverflow.net/questions/143332/is-there-an-asymptotic-formula-for-an-inverse-function-of-the-binomial-coefficie

General formula for n-Simplex root?


View comments in admin area before approval

Question: How can I view posted comments in admin area before approval?
I mean previewing comment INSIDE admin area not node's page.
Answer: Default comment administration page does not show you the entire comment. But it shows author and some other helpful information that should be helpful for most users to decide anther delete it or not.
You can replicate this form using Views and Views Bulk Operations module.
Just install both modules and create a new View on comment entity.
You can add a new page with a path like admin/content/comment2 (so you are not overriding the default page - if you want to do so, enter same path as core comment admin page).
Add necessary fields and set style as table. You can add a VBO checkbox and actions by adding a checkbox field.
There is an action "delete comment" that you can use to delete comments via VBO.
hooks will work without a problem.


spacy.matcher.PhraseMatcher object has no attribute "remove"

Question: I studied spacy at link https://spacy.io/api/phrasematcher#remove. I copy it to jupyter like this
import spacy
nlp = spacy.load('en_core_web_sm')
from spacy import displacy
from spacy.matcher import PhraseMatcher
phraseMatcher = PhraseMatcher(nlp.vocab)
phraseMatcher.add("OBAMA", [nlp("Barack Obama")])
assert "OBAMA" in phraseMatcher
phraseMatcher.remove("OBAMA")
assert "OBAMA" not in phraseMatcher

But I got the error
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-25-a5e1de7c4514> in <module>
      2 phraseMatcher.add("OBAMA", [nlp("Barack Obama")])
      3 assert "OBAMA" in phraseMatcher
----> 4 phraseMatcher.remove("OBAMA")
      5 assert "OBAMA" not in phraseMatcher

AttributeError: 'spacy.matcher.PhraseMatcher' object has no attribute 'remove'

I searched but didn't get any ideas why, anyone can show where my mistakes :(
This is my screen shoot:
Answer: PhraseMatcher.remove was added in spacy v2.2 (https://v2.spacy.io/api/phrasematcher#remove). Maybe you are using an older version?


Code not printing parent process statements

Question: I am running the following code:
// A C program to demonstrate Zombie Process.
// Child becomes Zombie as parent is sleeping
// when child process exits.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
    // Fork returns process id
    // in parent process
    pid_t child_pid = fork();

    // Parent process
    if (child_pid > 0)
        {printf("in parent process");
        sleep(50);
        }

    // Child process
    else
        {   printf("in child process");
            exit(0);
        }

    return 0;
}

And get following output:
$main
in child process

I am running the code here: http://tpcg.io/6ZccnX
Why is the statement "in parent process" not printing?
Comment: You might want to use `printf("in parent process\n");`, or `printf("in parent process"); fflush(stdout);`.
Comment: Because you `sleep(50);`. The unit is second, it's a long time. Change to `sleep(1);` everything is ok.
Comment: Output to standard output is usually buffered until a newline occurs.  Put the newline at the end of the outputs you want to see.  (Even then, if you pipe the output to another program or redirect to a file, just a newline won't necessarily force the output; you might need to use `fflush(stdout)` as well — or instead, but the newlines are a good idea in general).
Answer: the stdout is usually not flushed until a new line has occured
I've tested the following and both options work as expected:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
    // Fork returns process id
    // in parent process
    pid_t child_pid = fork();

    // Parent process
    if (child_pid > 0)
    {
        /*option one: put '\n' at the end of the print to flush it */
        printf("in parent process\n");
        /*option two: flush all the available streams after print*/
//      printf("in parent process");
//      fflush(NULL);
        sleep(50);
    }

    // Child process
    else
    {   printf("in child process");
        exit(0);
    }

    return 0;
}


How to set the user must login as member before purchase?

Question: How do I set the user must login as member before purchase?
I'm using Drupal version 7, with Drupal Commerce.
Comment: You can revoke permissions for anonymous user to Access Checkout in permissions page
Answer: Use the Commerce Checkout Redirect for implementing this:

This module redirects anonymous users to a page where they can login or create a new account when they try to checkout.


Minimum no. of observations required for statistical distribution fitting!

Question: I have one conceptual (but sort of vague) question regarding distribution fitting.
How many observations one would need to best fit any statistical distribution to given data. Like I am dealing with loss data and in one situation, I had only three observations still I could fit Normal distribution, which in reality I think is absurd. One more data and the scenario may change.
Hence, is there any thumb rule for minimum number of observations in order to have reasonably stable distribution fitting?
Comment: Such rules will only really be feasible if you fairly precisely define 'reasonably stable' - and even so it will depend on the distributions.
Answer: Well, in the special case of loss data I think most appropriate is the second source, but I give you some others too:

http://imash.leeds.ac.uk/dicode/wp4/Stats2-Forum/view_topic.php?id=10079

http://www.mathwave.com/articles/distribution-fitting-preliminary.html
a pdf:
http://www.vanbelle.org/chapters/webchapter2.pdf
and see this related question:
How many data points to fit an ex-Gaussian distribution?
I can tell you from my research, that in case of loss returns from stocks you need quite a lot of values to estimate an appropriate distribution correctly. Loss distributions are often leptokurtic and skewed, therefore the assumption of normality can be rejected. Especially if you are interested in Risk Management you focus on the tails. Therefore you will need at least 200 observations from my knowledge to get a basic idea of the distributions of extreme values. If you really want to do extreme value theory for risk management you will have to consider way more observations, since these are values which occur mostly with a small probability, so in case of, let's say 5% you have just 0,05*200=10 extreme values.
Please note, you say "stable distribution". This is not really convenient in this context, since stable distributions are a different topic, e.g. the Cauchy distribution is stable. I think it is more appropriate to say, that the estimators should have a small variance, so they do not vary to much, if you do a reestimation with another sample. This will lead to another statistical topic.


One Dependent variable and five independent variable? Is GLM appropriate?

Question: The aim of this study was to compare body condition using a scaled mass index (SMI) between seven skink sub-populations between time, habitat type, sex and between age class. We predict that skinks living in areas of degraded forest habitat will have a lower SMI than those in less disturbed coastal habitats and that SMI may have changed over time as habitats have become more degraded and disturbed. Additionally, body condition was compared between sex and age classes at each site, which may indicate more vulnerable individuals within the population.
My question:- is it appropriate to use GLM. As my independent variable is body condition and independent variables are seven skink sub-populations, time, habitat type, sex, age class.
Answer: From your description, I assume body condition is a continuous variable? In this case you would normally start with a linear regression, not a glm.
Comment: Can you guide me more as there are more than two independent variables? More specifically can you guide me about SPSS procedure to do so?
Comment: http://lmgtfy.com/?q=multiple+regression+spss ;)


Integral right and isosceles triangles with equal area and perimeter

Question: There are many different tasks in pictures on the Internet. I found one picture and it interested me.

And two questions. The first. Did I write this system correctly? That is, to reformulate the problem in the form of two right triangles.
$$
\left\{\!\begin{aligned}
&  X^2+Y^2=Z^2  \\
&  A^2+B^2=C^2  \\
&  2XY=AB \\
&  2Y+2Z=A+B+C
\end{aligned}\right.
$$
And the second question... these are some ideas for solving such systems? Not numerical, but rather parametrization of solutions.
Answer: Where did you find this meme/problem?
The problem is asking for a right triangle and an isoceles triangle with the same area and permimeter.
This was asked and solved only recently by Hirakawa and Matsumura, see https://arxiv.org/abs/1809.09936. They showed using quite advanced techniques that there is a unique solution.
They give the equations they use there, which are different to yours but could be equivalent.
See also the video abstract: https://www.youtube.com/watch?v=iln_m7zymtw
Comment: @individ I don't understand what you mean by parameterization of solutions. If you are looking for integer solutions, there is only 1 solution (up to rescaling), so there is nothing to parameterize.
Comment: I know about this job. But there is no parameterization of solutions. There, the curves are set and then the whole points are searched for on these curves. And I am interested in the parameterization of solutions.
Comment: If there are infinitely many solutions. Then there must be a parameterization of the solutions. The formula itself is probably long, but it should be. And here is the task to find it.
Comment: Okay. I'll think about it later and write my opinion here.


Why is there a kurtosis condition for joint distributions to be elliptical?

Question: I read that if x1, x2 are 2 random variables with different excess kurtosis, their joint distribution cant be elliptical. Is there an intuition or proof of that? It is not very clear to me.
Edit- in light of comment by Thomas Lumley below,
Let x1 and x2 be two random variable such that

$E[x_1]$ = $E[x_2]$ = 0
$E[x_1^2]$ = $E[x_2^2]$ = 1
$E[x_1^3]$ = $E[x_2^3]$ = 0
$E[x_1^4]$ <> $E[x_2^4]$
$E[x_1 *x_2] = \rho $

The statement says that there can't be a set of linear combinations that have equal kurtosis either
i.e there is no POSITIVE DEFINITE Matrix
$W = \begin{bmatrix}a_1 & a_2\\b_1 & b_2\end{bmatrix}$
$ y_1 = a_1 * x_1 + a_2 * x_2$
$  y_2 = b_1 * x_1 + b_2 * x_2$
such that
$ \frac{E[y_1^4]}{[E[y_1^2]]^2} = \frac{E[y_2^4]}{[E[y_2^2]]^2}$
Is there any intuition or proof of it?
Answer: If a distribution is elliptical, it can be rescaled to be spherically symmetric.  That means there is a positive definite matrix $A$ with entries $a_{ij}$ such that $a_{11}X_1+a_{12}X_2$ and $a_{21}X_1+a_{22}X_2$ are uncorrelated and have the same distribution. But they can't have the same distribution, because they have different excess kurtosis, so no elliptical symmetry.
Comment: +1.  To be explicit, your readers need to understand that univariate rescaling cannot change the excess kurtosis.
Comment: Thanks @ThomasLumley. However it is not very clear why a11X1+a12X2 and a21X1+a22X2 can't have same kurtosis/ distribution
Comment: The spherical rescaling can't be done if the variables are correlated?
Answer:
I read that if $X_1, X_2$ are 2 random variables with different excess
kurtosis, their joint distribution cant be elliptical. Is there an
intuition or proof of that? It is not very clear to me.

In my opinion the best intuition is the follow. Elliptical distributions deal with some stylized facts in finance returns, like: fat tails and tail dependence. However, in multivariate case, there is a restriction about the form of the marginals. Especially about the heaviness of the tails.
The most useful example in my opinion is the t-Student distribution: https://en.wikipedia.org/wiki/Multivariate_t-distribution
Given location vector $\mu$ and scale matrix $\Sigma$ we focus on the tail index $v$ (real positive number). Now, the point is that location and scale are free but the tail index must be common to any marginal.
So, under the hypothesis that $v>4$, the excess kurtosis is $6/(v-4)$ for any marginal. Similar conditions hold for all Elliptical distributions.
Moreover, it seems me that from this example emerge that the widespread use of kurtosis for addrees fat tails problem is not a good practice. Indeed, precisely from fat tails, the existence of fourth moments is questionable and instability of their estimator is related. Focus on something like the tail index is much better.
This article give some insight about Elliptical distribution: https://www.researchgate.net/publication/237633988_Tail_Conditional_Expectations_for_Elliptical_Distributions


Show that an integral is more than $\frac{\left(\frac{\pi}{2}\right)^{r+1}}{r+2}$

Question:
Q. Consider the function $$f(r)=\int_0^{\frac{\pi}{2}}x^r\sin(x)dx.$$ Show that $f(r)>\frac{\left(\frac{\pi}{2}\right)^{r+1}}{r+2}.$

I do not know how to even begin. Actually, the first part of this question was to show that $f(r)<\frac{\left(\frac{\pi}{2}\right)^{r+1}}{r+1}.$ I was able to do this by noting that for $x\in\left(0,\frac{\pi}{2}\right), x^r\sin(x)<x^r.$ But I do not know how to show that $f(r)>\frac{\left(\frac{\pi}{2}\right)^{r+1}}{r+2}.$
Comment: You can try to show that $$\frac{1}{\pi/2}x^{r+1}<x^{r}\sin\left(x\right)<x^{r}$$ for $x \in (0,\pi/2)$
Comment: Note that $f(0)= 1$
Answer: Consider the function $f(x)=x\ cos x -\sin x$. For $x \in (0, \frac{\pi}{2})$, $f'(x)=-x \sin x < 0$. Hence, $f(x)$ is decreasing for $x \in (0, \frac{\pi}{2})$, and as a result, $f(x)< f(0)=0$.
Now, consider the function $g(x)=\frac{\sin x}{x}$. We have:
$$g'(x)=\frac{x \cos x -\sin x}{x^2}=\frac{f(x)}{x^2}< 0;$$
as a result, $g(x)$ is decreasing if $x \in (0, \frac{\pi}{2}).$ Therefore:
$$g(x)=\frac{\sin x}{x} > g(\frac{\pi}{2})=\frac{2}{\pi}. $$
Finally,
$$\frac{2}{\pi}x^{r+1}<x^r \sin x < x^r.$$
The rest is easy.

PS: There is a post containing the very same inequality at this link.
Answer: Hint: Find a simple lower bound for $\dfrac{\sin x}x$ in the interval of interest...


Is it common practice to audition new musicians one-on-one before rehearsing with the entire band?

Question: I used to audition new musicians one-on-one, for a soul music band. After that, if I really liked them, I invited the new musician to rehearse with the rest of the band. Is that a common practice?
Some of them argued that it is hard to try anything with only voice and one instrument, or it's not fun to try with a backtrack. However, I want first to see what kind of people they are before joining the rest of the band.
What's the common practice? Do usually band audition with the entire band or one-on-one?
Answer: Playing without the rest of the band? I'd walk away from it. It's a two way thing. While you want to know how the prospective player works, they also want to know how the rest of the band works. All very well trying out someone on a one to one basis, where they have little to blend in with or work off, but see it from their side too.
Some of the bands I've 'joined' and gigged with, there's not even been a rehearsal, let alone an audition. but they're reading bands, so the situation is maybe far different from yours. Others have had numerous rehearsals, including the introductory one - with the full band. Sometimes there's been a list of stuff a week before, sometimes I don't know until the practice.
And why do you think your view matters more than the other players? 'Cos it's your band? That's all very well, but may backfire when the drummer or another member decides he doesn't get on with the new member, either musically or personality wise. Then it's look for a new drummer time!
There are, as Carl indicates, no 'normal' practice with prospective new members, mainly as there are so many different types of bands, groups, orchestras, etc, with huge differences in how and what they play, and how they rehearse. Although for a mainstream soul band, with maybe 8 or so players, I'd always go for a full band first play - horn players would need to have the others playing at the same time anyway.
Answer: You might be interested to know how auditions go for positions in symphony orchestras.  In most, but not all, cases, applicants perform solo or with a piano accompanist for a couple rounds. If they are selected, they are on a "trial" basis for a year or so before being granted the equivalent of tenure.
There are cases where an orchestra may be courting a specific player, and they go straight to playing full-orchestra rehearsals to see how the sounds and styles blend.
There is no common practice for any group of any size.  If you know a player well (either personally or by attending their performances), you might consider whether a solo audition will tell you anything.


adding appengine eclipse plugin to ADT eclipse

Question: I download the eclipse bundle for android. Now I want to add the Appengine plugin to eclipse. Should I download a separate instance of eclipse for Appengine or may I add GAE(Google App Engine) to the ADT eclipse?
Answer: I have to answer you based on intuition here, but I think you should be able to add GAE plugin to Eclipse you have (With ADT). Just install the plugin from local directory and try doing some basic GAE operations like deploying an app and it should be clear if it works!
Answer: You can install the GAE plugin to ADT Eclipse following the instructions below:
https://developers.google.com/eclipse/docs/download


PPTPd: 'initial packet length 4930 outside (0 - 220)'

Question: I got home today and was greeted by a pile of emails from logcheck, informing that pptpd was upset.  Here is a snippet:

Jun 26 20:02:37 lazarus pptpd[3060]: MGR: initial packet length 4930 outside (0 - 220)
Jun 26 20:02:43 lazarus pptpd[3060]: MGR: initial packet length 4930 outside (0 - 220)
Jun 26 20:03:52 lazarus pptpd[3060]: MGR: initial packet length 4930 outside (0 - 220)
Jun 26 20:04:04 lazarus pptpd[3060]: MGR: initial packet length 22415 outside (0 - 220)

It seems to have been happening about twice a minute for the last couple of hours.
Any clues what it might be?
I've started a tcpdump, and with any luck that will turn something up...
Answer: It turns out that a bunch of BitTorrent clients in Germany got it in their heads that they might be able to handshake with my pptpd... Why they wanted to do that I can only guess, but that explains the crazy packets.
Answer: You should re-consider if you really want to be running PPTP in 2009 as the encryption is known to be fairly weak.
OpenVPN seems to be general choice of simple VPN options (or just using SSL with select services)


Abstract Algebra Benedict Gross

Question: I am currently watching Harvard's Benedict Gross' lectures on Abstract Algebra available for free on internet. However, I don't have access to Artin's Book. Is there any way that I could find problem sets that go along with the course. I would like to follow the weekly/day to day problem pattern only if possible.
Thank you for your help and time.
Answer: The problem sets are available under the Gross' lecture site. You can find Artin's book in every mathematical library, if you have access to it. Otherwise in an Internet shop like Amazon, since there is no legal e-book available.

Abstract Algebra Benedict Gross


Stream's capacity vs length

Question: When I write some stream into a new memory stream, the length and capacity of the memory stream are both set to 0 at first, and grow along with the write process. but at some point the capacity grows faster than the length.
After the write operation is done I get the correct length (Same as the original input stream's length), but with MUCH bigger capacity.
Is it correct?
Shouldn't they be the same?
I couldn't find any info about it
Comment: If you hit this searching for info on `List` Capacity vs. Count - see http://stackoverflow.com/questions/2485139/list-capacity-returns-more-items-than-added
Answer:
Shouldn't they be the same?

No - or at least, not necessarily. This is basically the same as a List<T>'s capacity vs its count (or StringBuilder for that matter). The idea is that in order to minimize the number of times you make a copy, when you need to increase your capacity, you increase it significantly - not just by one byte at a time. So for example, one strategy would be "Minimum of 16 bytes, and double the capacity when you need to."
After you've done some write operations, how is the stream meant to know that you're finished? And would you really want it to have to copy the entire contents in order to perform a write of one more byte?
Basically the trade-off is memory vs speed: the larger you make the capacity, the more writing you can do quickly between copies.
Comment: My buffer size is 8192, so after each "Write" inside the while loop length becomes 8192, then 16384, and so on. the capacity first goes 8192, 16384, etc, but in some point they stop growing at the same rate
Comment: Thanks for the explanation. So do I need to set it in advance or just keep it this way?
Comment: @user990635: Well yes - I wouldn't be surprised if the capacity doubled each time you went over the capacity. So after 3 writes you might have a length of 24K and a capacity of 32K. Then the fourth write doesn't require any more capacity, so it's quicker and you end up with a length of 32K and a capacity of 32K. Then the *fifth* write needs more capacity, so it might double - giving a length of 40K and a capacity of 64K. You've then got three more writes which don't require the copy.
Comment: @user990635: If you know how much data you're going to write, make that the initial capacity. If you don't, just let it manage it itself - that will be less efficient in both space and time, but it should still *work*.
Comment: I know the length of the input stream (that I'm copying) so this will go well as capacity, right?
Comment: @user990635: Yes, exactly. That way the capacity and the length of your `MemoryStream` *should* be the same at the end.

Stream's capacity vs length


Why did China and some other communist countries boycott the 1980 Summer Olympics?

Question: The 1980 Summer Olympics was held in Moscow, Soviet Union.
Many countries boycotted the games initiated by the United States for Soviet Union's invasion of Afghanistan.
But there were some communist countries in the boycotting countries such as People's Republic of China, Albania and some else.
What was the reason for communist countries to boycott the 1980 games?
Answer: The 1980 boycott wasn't specifically a capitalist vs communist boycott - it was to protest at the 1979 invasion of Afghanistan by the Soviet Union.
With particular regards to China, China and the Soviet Union had very divergent views of the "correct" interpretation of communism throughout the 1960s to 1980s; details of that are probably better in a Politics SE answer than a Sports SE one, but the long and short is that they were not allies who were going to unconditionally (or in some cases, even conditionally) support each other against the Western countries. Similarly, Albania was not an unconditional ally of the Soviet Union, having withdrawn from the Warsaw Pact in 1968 and to some extent allied itself with China.
Comment: I wish I could give a second upvote for the part of this answer that says this is better for Politics SE.


Network storage is not mounted to the SUSE Linux Enterprise Server 10

Question: command
<code>mount XXX.XXX.XXX.XXX:/store/ /mnt/test
</code>
Error
<code>    mount server reported tcp not available, falling back to udp mount: RPC:
Remote system error - Network is unreachable
</code>
The server has successfully received the IP address.
Any ideas?
Answer: Check your firewall  Yast -> Security and Users -> Firewall. Make sure NFS services is enabled.
Comment: I solved the problem. Files with the routes were broken.


How to create Texture2D with CreateExternalTexture and a pointer passed from C++ library?

Question: I am trying to understand how to establish communication between C++ DirectX11 code and Unity Engine.
What I am trying to do is create a very simple ID3D11Texture2D in C++ and then pass it to Unity, creating its Texture2D by the means of CreateExternalTexture method.
So, I have a C++ DLL VS Project where I have this one function:
ID3D11ShaderResourceView* GetTexture()
{
    ofstream myfile;
    myfile.open("GetTexture.log");

    const int width = 640;
    const int height = 480;

    unsigned char* pixels = new unsigned char[width * height * 4];
    unsigned char* pixelsP = pixels;

    int numPixels = (int)(width * height);

    ID3D11Texture2D* tex = nullptr;
    ID3D11ShaderResourceView* shaderView = nullptr;

    ID3D11Device* device = CreateDX11device();

    if (!device)
    {
        myfile << "Cannot create DX11 device" << endl;
        myfile.close();
        return 0;
    }
    else
    {
        myfile << "Successfully created DX11 device" << endl;
    }

    for (int i = 0; i < numPixels; i++)
    {
        *(pixelsP) = 255;
        *(pixelsP + 1) = 0;
        *(pixelsP + 2) = 0;
        *(pixelsP + 3) = 122;
        pixelsP += 4;
    }

    D3D11_SUBRESOURCE_DATA initData = { 0 };
    initData.pSysMem = (const void*)pixels;
    initData.SysMemPitch = width * 4;
    initData.SysMemSlicePitch = width * height * 4;

    D3D11_TEXTURE2D_DESC desc = {};
    desc.Width = width;
    desc.Height = height;
    desc.MipLevels = 1;
    desc.ArraySize = 1;
    desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    desc.SampleDesc.Count = 1;
    desc.Usage = D3D11_USAGE_DYNAMIC;//D3D11_USAGE_IMMUTABLE;
    desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;// | D3D11_BIND_RENDER_TARGET;//D3D11_BIND_SHADER_RESOURCE;
    desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;

    HRESULT hr = device->CreateTexture2D(&desc, &initData, &tex);

    if (FAILED(hr))
    {
        myfile << "FAILED TO CREATE DX TEXTURE" << endl;
        myfile << hr << endl;
        myfile.close();
        return nullptr;
    }
    else
    {
        myfile << "Successfully Created DX Texture" << endl;
    }

    myfile.close();

    D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc;
    ZeroMemory(&shaderResourceViewDesc, sizeof(shaderResourceViewDesc));

    shaderResourceViewDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
    shaderResourceViewDesc.Texture2D.MostDetailedMip = 0;
    shaderResourceViewDesc.Texture2D.MipLevels = 1;

    device->CreateShaderResourceView(tex, &shaderResourceViewDesc, &shaderView);

    return shaderView;
}

And here is how I create my DX11 device:
ID3D11Device* CreateDX11device()
{
    ID3D11Device* device = nullptr;
    HRESULT hr = S_OK;
    UINT createDeviceFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_DEBUG;

    D3D_DRIVER_TYPE driverTypes[] = {
        D3D_DRIVER_TYPE_HARDWARE,
        D3D_DRIVER_TYPE_WARP,
        D3D_DRIVER_TYPE_REFERENCE,
    };

    UINT numDriverTypes = ARRAYSIZE(driverTypes);

    D3D_FEATURE_LEVEL featureLevels[] = {
        D3D_FEATURE_LEVEL_11_0,
        D3D_FEATURE_LEVEL_10_1,
        D3D_FEATURE_LEVEL_10_0,
        D3D_FEATURE_LEVEL_9_3,
        D3D_FEATURE_LEVEL_9_1
    };

    ID3D11DeviceContext* context = nullptr;

    UINT numFeatureLevels = ARRAYSIZE(featureLevels);

    hr = D3D11CreateDevice(nullptr,
        D3D_DRIVER_TYPE_HARDWARE,
        nullptr,
        createDeviceFlags,
        featureLevels,
        numFeatureLevels,
        D3D11_SDK_VERSION,
        &device,
        nullptr,
        &context);

    if (FAILED(hr)) {
        cout << "Could not create DX11 device" << endl;
        return nullptr;
    }

    cout << "DX Device Created" << endl;

    return device;
}

Now, the function GetTexture is simply called from C# code in Unity and the result is treated as IntPtr. I then start creating the Texture2D and setting the texture to view the result in Unity:
[DllImport("TestDX11.dll", CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr GetTexture();

void Start()
{
    IntPtr ptr = GetTexture();

    Texture2D texture = Texture2D.CreateExternalTexture(640, 480, TextureFormat.RGBA32, false, false, ptr);
    GetComponent<RawImage>().texture = texture;
}

The problem is that I am expecting to see a red image in Unity app but I see nothing, the texture is blank, as if I was not putting anything in it. And to be sure I tried outputting the received pointer from the DLL and it is non-null, so I do actually get a pointer at the Texture. I feel quite lost at this point as I tried playing around with different flags during texture creation, but nothing really helped.
I also tried to send ID3D11Texture2D* instead of ID3D11ResourceShaderView* as this link points out, but it crashes Unity when CreateExternalTexture method is called for some reason.
I would appreciate any help!
Comment: Seems you are creating your texture using your own device, you need to use the one provided by unity under the hood (as textures created by different devices are not "shareable"
Comment: @catflier thanks! That's an interesting suggestion. How would I get the device used by Unity?
Answer: In your case you are creating a Texture using a device created by D3D11CreateDevice.
This is a different device than the one used by Unity, so when you call Texture2D.CreateExternalTexture, either Unity or The device used by Unity will detect it doesn't own this resource, so it can't use it.
In order to have this texture accessible by Unity, you need to create the texture with the device used by Unity itself.
To do this, you need to use Unity's Low-level native plug-in interface
You need to declare a few specific functions in your dll so Unity can detect them and then call.
In your case, you can use UnityPluginLoad "callback, and retrieve the device from there (for simplicity, the below code does not handle cases as per Unity using Direct3D12 or another graphics API).
extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API
UnityPluginLoad(IUnityInterfaces* interfaces)
{
    ID3D11Device* dxDevice;
    ID3D11DeviceContext* dxDeviceContext;
    dxDevice = interfaces->Get<IUnityGraphicsD3D11>()->GetDevice();
    dxDevice ->GetImmediateContext(&dxDeviceContext);
}

Any texture created with this device will be accessible from Texture2D.CreateExternalTexture
Note : Since Unity Direct3D11 device (at the time I did some project in Unity, which was some years ago, I'm not sure about latest versions) , was using D3D11_CREATE_DEVICE_FLAG::D3D11_CREATE_DEVICE_SINGLETHREADED), you need to create your textures in the standard Unity thread, otherwise you might (will) have potential crashes (in our case we had to start unity and our app with a custom commandline to disable this flag).
Comment: You are absolutely right. Thank you for help!


Retrieving hardware info for Windows and Linux

Question: I have a dual boot (Ubuntu and Win7) machine and I need retrieve some hardware info. In this first moment, I'll list the following:

Processor ID or Serial Number;
Motherboard Serial Number;
Hard-disk Serial Number;
Graphical card Serial Number.

Is there any way to get those information, with same data, from both OS, using native programs (non-downloaded programs)?
PS: I'm developing in Java, so any command line or other libraries are accepted.
Thanks in advance.
Comment: For linux: `grep -R . /sys/class/dmi`
Comment: Also for linux (depending on distro):  /usr/sbin/hwinfo  (this command has options to get just specific info items)
Comment: Executing `grep -R . /sys/class/dmi` I have to use sudo to execute its fully functionality. But for example, some serials come filled by a huge "BLANK" value.
Answer: For Windows 7, you can use WMIC and Get-WmiObject in PowerShell to get processor and GPU serials, e.g.,
<code>> Get-WmiObject Win32_Processor
> WMIC PATH Win32_VideoController GET Description,PNPDeviceID
</code>
See also this thread.


Diminuir tabelas para caber em uma página

Question: Tenho uma página que apresenta quatro tabelas e um botão para que o usuário possa imprimi-las.
O problema é que essas tabelas tem uma grande quantidade de colunas e quando vou tentar imprimir, elas são cortadas.
Gostaria de poder diminuir o tamanho das tabelas para que elas coubessem na página de impressão. Alguém sabe como fazer isso?

Aqui já dá pra ver que a tabela não está sendo mostrada inteira na página já que a última coluna mostrada é OUT_PREV e a última coluna realm é Dez_REAL

E na página de impressão mesmo em modo paisagem a última coluna que está sendo mostrada é AGO_PREV e a última coluna que deveria ser mostrada é DEZ_REAL.
Comment: poste o código da tabela pra ver se conseguiremos ajudar, mas de antemão, se resolve com css...
Answer: Já vou avisando que não é a solução mais "elegante", mas em último casso pode quebrar seu galho.
Com esse CSS vc vai diminuir a escala da sua tabela em 20% com scale(0.8), ou seja 80% do tamanho original. E mudando o tamanho da fonte, no caso eu coloquei font-size:9px, apenas na hora da impressão. OBS: O scale() afeta esse font-size, então será 9px - 20% do tamanho devido ao scale 0.8, mas vc pode fazer uns testes até encaixar os valores ideias para sua tabela fica com uma leiturabilidade legal.

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
@media print {
    table {
        transform: scale(0.8); /* diminui em 20% o tamanho total da tabela na impressão */
        font-size: 9px; /* diminua um pouco a fonte na hora da impressão */
    }
}
@page {
    size: landscape; /* muda a orientação da página para landscape na hora da impressão */
}

                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                item
                last

                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                Lorem, ipsum.
                último ítem

Como fica na impressão:

Dica:
Vc também pode habilitar a "visualização de impressão" pelo Chrome no Dev Tools conforme essa imagem. Ai fica mais fácil para vc ir ajustando seu CSS apenas no formato Print
Comment: Ah, realmente! Era só diminuir a escala no navegador também. Obrigada, sua resposta ajudou muito!
Comment: Então, a tabela na página diminiu e ficou certinha, mas quando eu vou imprimir, o tamanho da tabela não mudou. :/
Comment: @MarianaFerreira aqui eu não tenho uma impressora física para imprimir no papel de fato. Mas quando salvei como PDF vei normal com a configuração do CSS direitinho.
Comment: Tranquilo @MarianaFerreira que bom que resolvei ai :)


How to use custom routes in CakePHP?

Question: I want to implement custom routes in CakePHP. I am following the docs
http://book.cakephp.org/2.0/en/development/routing.html#custom-route-classes
My custom route in app/Routing/Route
<?php

App::uses('CakeRoute', 'lib/Cake/Routing/Route');

class CategoryRoute extends CakeRoute
{
    public function parse($url)
    {
        $params = parent::parse($url);
        if (empty($params)) {
            return false;
        }

        return true;
    }
}

app/Config/routes.php
App::uses('CategoryRoute', 'Routing/Route');
Router::connect('/mypage/*', array('controller' => 'mycontroller', 'action' => 'view'), ['routeClass' => 'CategoryRoute']);

but I get
Missing Controller

Error: Controller could not be found.

Error: Create the class Controller below in file: app/Controller/Controller.php

When I remove ['routeClass' => 'CategoryRoute'], rerouting just works fine.
Answer: Have a closer look at the API documenation: API > CakeRoute::parse()
The parse() method is supposed to return an array of parsed parameters (ie $params) on success, or false on failure.

How to use custom routes in CakePHP?