why is calibration of my logistic regression s shaped?

Question: I am simulating data to compare real and predicted probabilities from logistic regression like this:
set.seed(2)
library(simstudy)
def <- defData(varname = "x1", dist = "uniform", formula="0.01;0.99")
def <- defData(def, varname='x1.small', dist='nonrandom', formula='x1<0.15')
def <- defData(def, varname='biomarker', dist='binary',
               formula='x1.small/2', link='log')
def <- defData(def, varname='real_risk', dist='nonrandom',
               formula='x1 + biomarker/4')
def <- defData(def, varname = "y", dist = "binary",
               formula='x1 + biomarker/4', link='identity')
data <- genData(1000, def)
test_data <-genData(200, def)

predictions <- predict(glm(y ~ x1 + biomarker, data=data,
                           family='binomial'), test_data, type='response')
plot(predictions, test_data$real_risk, xlab='predicted_probability',
     ylab='real_probability')

however when I plot real vs. predicted probabilities, the relationship is not linear, but S-shaped. I think I assume linearity somewhere where I shouldn't. Why is this relationship s-shaped, and how can I get data where it is linear?
Comment: Don't compare probabilities: compare log odds (the logistic of the probabilities).  That's the whole point of the `type` argument to the `predict` function!
Comment: No, you should compare log odds to log odds.  BTW, because your question relies on details of what the user-written function `defData` does, it's not comprehensible: could you at least explain what that function is intended to do?
Comment: so I should compare real probabilities to log odds of predicted probabilities? This is linear, but how can I get something on a same scale?
Comment: But wouldn't you still want samples with predicted probability of 0.4 have the predicted target outcome 40 percent of times? Also, what's the difference between log odds vs log odds or probabilities cs probabilities? If one is linear shouldn't the other be linear as well?
Comment: The defdata function comes from lybrary simstudy that should help to simulate data. I create some input variables which are then used to create a random outcome variable according to the relationship specified in formula and link keywords
Answer: I was simulating my data incorrectly. The identity link is not creating the data according to assumptions of logistic regression, although I can't tell what is going on exactly in that library. The correct thing to use is logit link but instead of raw probabilities, give it log odds of your probabilities like this:
def <- defData(varname = "x1", dist = "uniform", formula="-5;5")
def <- defData(def, varname = "y", dist = "binary",
           formula='x1', link='logit')

Then to plot the calibration on probability scale and not log odds, simply let glm predict probability and transform your log odds using logistic like this:
predictions1 <- predict(glm(y ~ x1, data=data, family = 'binomial'),
                        test_data, type='response')
plot(predictions1, logistic(test_data$x1)); abline(0,1)

but I am curious why is the link='identity' misbehaving, but documentation seems to be terse in this aspect


Safari Favorites/Bookmark Icon not displaying

Question: This pertains to Safari Bookmark and Favorites Icons
No matter what I do, I cannot get my bookmark icon/favorites icon to appear. I've tried the following:
 <link rel="icon" href="/images/favicon.png" type="image/x-icon">

Waited for days, cleared my cache, and nothing. Then I added:
 <link rel="icon" type="image/png" href="https://mywebsite.com/images/favicon-96x96.png" sizes="96x96">
 <link rel="icon" type="image/png" href="https://mywebsite.com/images/favicon-144x144.png" sizes="144x144">

And it still doesn't work. I also added an apple-touch-icon.png in my root directory, and this works, but only for adding my website to the homescreen. For bookmarks and favorites, it still shows just the first letter of my website.
I've researched everywhere and nothing seems to work, have things changed? Help is much appreciated, thank you!
Answer: The most commonly accepted way is to have a favicon.ico file in your site's root directory. You can generate a favicon file here.
To set icons explicitly you can look here, but this is complementary.
Comment: does it have to be .ico? And does the size matter?
Comment: Updated the answer with a link to a favicon generator website
Comment: I checked it out thanks. Does it take time for everything to appear? I followed all the instructions, cleared my cache and it still won't show up
Comment: Nevermind, I had to do some more thorough cache clearing for it to finally appear. Thank you so much for the link!
Comment: Great to hear! Cheers
Comment: Tell us what you did to get it to work! Did you just go into Settings and "Clear History & Website Data"? Did you do more?
Answer: With iOS 11.4 you have to close the Safari app first and then clear the cached data.


CSS percentage width not working

Question: I've been trying to edit the CSS for my website's navbar in order to transform it from having fixed width and height values into percentage values (in order for it to become responsive and work better with different screen sizes). However, when I converted the values, the individual divs didn't correctly size.
There is probably something very simple that I've missed here (seeing as I am a self taught amateur in CSS and HTML), but I couldn't find any solutions here.
This is a JSfiddle of my naviation bar using px, working properly
This is a JSfiddle of it after conversion to percentage values for width.
Relevant code (post conversion):
HTML:

<h class="navbartext">one</h>

<h class="navbartext">two</h>

<h class="navbartext">three</h>

<h class="navbartext">four</h>

<h class="navbartext">five</h>

<h class="navbartext">six</h>

CSS:
#container {
    width:100%;
    height:25px;
    margin:0 auto;
    background:#fff;
}

#menuwrap {
    height:25px;
    width:100%
    position:relative;
    top:25px;
    background:#fff;
}

ul#menu {
    height:25px;
    float:right;
    margin:0;
    padding:0;
    list-style-type:none;
    background:#44546A;
}

ul#menu li {
    float:left;
}

ul#menu li a {
    display: block;
    width: auto;
    height:25px;
    overflow:hidden;
    text-indent:10px;
    background:#000;
    color:#000;
}

ul#menu li#one a {
    width:16.6%;
    text-align:center;
    vertical-align: middle;
}

ul#menu li#two a {
    width:16.6%;
    text-align:center;
    vertical-align: middle;
}

ul#menu li#three a {
    width:16.6%;
    text-align:center;
    vertical-align: middle;
}

ul#menu li#four a {
    width:16.6%;
    text-align:center;
    vertical-align: middle;
}

ul#menu li#five a {
    width:16.6%;
    text-align:center;
    vertical-align: middle;
}

ul#menu li#six a {
    width:17%;
    text-align:center;
    vertical-align: middle;
}

ul#menu li#seven a {
    width: 49px;
    height: 49px;
    -webkit-border-radius: 25px;
    -moz-border-radius: 25px;
    border-radius: 25px;
    background-color:#000;
    border-style: solid;
    border-width: 1px;
    border-color: #fff;
    position:relative;
    top: -17.5px;
    left:88%;
    z-index:2;
}

ul#menu li class.a
{
width:208px;
margin:0px;
}

Answer: Add width: 100%; to ul#menu.
Check it out here: https://jsfiddle.net/vjhz7o8y/5/.
Also, avoid using the same id for multiple elements, use class instead.
ul#menu {
    height:25px;
    width:100%;
    float:right;
    margin:0;
    padding:0;
    list-style-type:none;
    background:#44546A;
}

Comment: Adding this doesn't completely fix my problem, as the links on the navigation bar are still not expanding to their correct portions (approximately (100/6)% each).
Also, which elements have I used id in place of class?
Thanks.
Comment: You used four circles with the same id `circle`. Do you want the circle to be displayed to the far left side?
Answer: My web-design book, Murach's HTML5 and CSS3 3rd edition says to use slickNav for a responsive menu. It is a Javascript plugin. Also, I have just fixed my problem sort of. I was attempting to size the blocked  elements when I should have been sizing their containers. Here is some sample code
nav {width:100%;}

nav #nav_menu {
    list-style-type: none;
    padding: 0%;
    margin: 0%;
}

 #nav_menu > li {
    float: left;
    width:20%;
    max-width: 190px;
}

Hope this helps.

CSS percentage width not working


background Content of div occurs in navbar

Question: I am using creative bootsrap theme where the background image occurs in navbar and it changes only when i scroll.
i dont want the navbar to change when scrolled it should be default with white background which occurs when i scroll.
here is the link for the template
https://startbootstrap.com/template-overviews/creative/This is by default
I want my navbar to be like this throughout and not only when i scroll
Answer: This will fix your problem
The white background-color is adding from js .
With one step you can get this header by adding navbar-shrink this class to here  .
OR
You can change your css like this.
background-color and border-color
#mainNav {
    border-color: transparent; /* need to change */
    background-color: transparent; /* need to change */
}

#mainNav {
    border-color: 1px solid #22262a;
    background-color: #fff;
}

Logo Color(nav-brand)
#mainNav .navbar-brand {
    color: rgba(255,255,255,.7); /* need to change */
}
#mainNav .navbar-brand {
    color: #f05f40;
}

Link Color(a)
#mainNav .navbar-nav>li.nav-item>a.nav-link, #mainNav .navbar-nav>li.nav-item>a.nav-link:focus {
    color: rgba(255,255,255,.7); /* need to change */
}
#mainNav .navbar-nav>li.nav-item>a.nav-link, #mainNav .navbar-nav>li.nav-item>a.nav-link:focus {
    color: #212529;
}

Answer: You need to make it position fixed instead of relative by adding below code:
.navbar {
    position: fixed;
    z-index: 100;
    width: 100%;
}

Answer: This class applies the white and orange when you scroll down:
#mainNav.navbar-shrink
Just apply whatever navbar-shrink applies to your #mainNav,
// white background
#mainNav {
    border-bottom: 1px solid rgba(33,37,41,.1);
    background-color: #fff;
}
// orange branding title
#mainNav .navbar-brand {
    color: #f05f40;
}
// black navigation links
#mainNav .navbar-nav > li.nav-item > a.nav-link {
  color: #212529;
}

That should be enough, but if you want to clean up further remove the Javascript part that actually adds that navbar-shrink part,
the function should contain something like:
$("#mainNav").addClass("navbar-shrink");
You won't need it
Try not to use !important in your css selectors, your code will get messy
Comment: i have done this but now the navbar is white but the text are also white
Comment: HI, @BharatRathore, have you added this?
#mainNav .navbar-brand {
    color: #f05f40;
}
Make sure to remove the JS that adds the shrink class, you may also want to remove the .navbar-shrink from the CSS since you wont need it
Comment: Also, your nav items on the right side of the nav will need to be black right?
#mainNav .navbar-nav > li.nav-item > a.nav-link,
#mainNav .navbar-nav > li.nav-item > a.nav-link:focus {
    color: #212529;
}


CSS no Chrome não funciona corretamente

Question: Estou a programar em PHP, HTML e Javascript para criar uma loja on-line, integrada na plataforma Opencart. Está tudo já a funcionar corretamente, menos um pequeno pormenor com as CSS. Coloquei o efeito hover na imagem dos diferentes produtos simplesmente usando image a:hover. No entanto, apesar de funcionar em todos os browsers, em alguma páginas do site no Chrome, o efeito não é executado!

.box-product .image {
    /**display: inline-block;
    margin-bottom: 15px;
    margin-left: 20px;
    display: block;
    max-width: 100%;
    height: auto;**/
    margin-bottom: 22px;
    padding-bottom: 15px;
    display: block;
    text-align: center;
    background: white;
    /**box-shadow: 0px 0px 3px #AAA inset**/
    border: 0px solid white;
    -webkit-transition: all 0.3s ease-in-out;
    -moz-transition: all 0.3s ease-in-out;
    -o-transition: all 0.3s ease-in-out;
    -ms-transition: all 0.3s ease-in-out;
    transition: all 0.3s ease-in-out;
}

.box-product .image img {
    padding: 3px;
    border: 0px solid #E7E7E7;
    display: block;
    max-width: 100%;
    height: auto;
    margin:auto;

}

.box-product .image a:hover {
    opacity:0.5; filter:alpha(opacity=50);
}

Comment: http://jigsaw.w3.org/css-validator/
Comment: .box-product .image {
    /**display: inline-block;
    margin-bottom: 15px;
    margin-left: 20px;
    display: block;
    max-width: 100%;
    height: auto;**/
    margin-bottom: 22px;
    padding-bottom: 15px;
    display: block;
    text-align: center;
    background: white;/**box-shadow: 0px 0px 3px #AAA inset**/
border: 0px solid white;
-webkit-transition: all 0.3s ease-in-out;
-moz-transition: all 0.3s ease-in-out;-o-transition: all 0.3s ease-in-out;-ms-transition: all 0.3s ease-in-out;transition: all 0.3s ease-in-out;}.box-product .image a:hover {opacity:0.5; filter:alpha(opacity=50);}
Comment: Copiar este codigo no Validator do W3C vai dar a resposta (que tem a ver com a opacity)
Comment: Poderia postar o html? A imagem está, dentro da ancora ou fora?
Answer: Testei aqui e funcionou, porem podem ser erro relacionado ao seu html e não exatamente a seu css.
Outra possibilidade de nao funcionamente é que segundo a W3C, a propriedade css opacity só funciona apartir da versão 4 do google chrome. Veja https://www.w3schools.com/cssref/css3_pr_opacity.asp
Caso continue nao funcionando, poste seu código HTML.
De qualquer forma deixo o exemplo postado que funcionou aqui.

.box-product .image a:hover {
    opacity: 0.5;
    filter: Alpha(opacity=50); /* IE8 and earlier */
    }

CSS no Chrome não funciona corretamente


manipulating all the tables in an R group_split list

Question: Edited
I have a large table, which starts like this

Essentially, it's a table with multiple samples ("samp_id") showing the number ("least") of "taxon" present in each.
I want to transpose/pivot the table to look like this;

i.e. with "taxon" as the top row, with each of the 90 samples in "data" following as a row based on the "least" column, re-named with its "samp_id". So you see what each sample is, as well the value in "least" for each sample in the different "taxon" (which may not be identical across the 90 samples).
Previously, I have separated the data into multiple tibbles based on "samp_id", selected "taxon" and "least", re-named "least" with the "samp_id" then combined the individual tibbles based on "taxon" with full_join using something like the code below, then transposing the combined table
ACLOD_11 = data %>%
  filter(samp_id == "ACLOD_11") %>%
  select(taxon, least) %>%
  rename("ACLOD_11" = least)

ACLOD_12 = data ... #as above, but different samp_id

data_final = list(ACLOD_11, ACLOD_12, ...) %>%
  reduce(full_join, by = "taxon")

As I have more data tables to follow after this one with 90 samples, so I want to be able to do this without having to individually separate the data into 100s of tibbles and manually inputting the "samp_id" before joining.
I have currently split the data into 90 separate tibbles based on "samp_id" (there are 90 samples in "data")
data_split = data %>%
  group_split(samp_id)

but am unsure if this is the best way to do this, or what I should to next?
Comment: This sounds a bit like a "long to wide" problem. Have you thought about using something like `tidyr::pivot_wider()` on the columns "samp_id", "least", and "taxon"? If things are very large and you need some speed you could try `data.table::dcast()` for widening.
Comment: thanks for this, it's almost close; I've edited the question to (hopefully!) add more clarity, would appreciate your thoughs!
Comment: If you select just the three columns that are relevant to the problem (samp_id, least, taxon), does `tidyr::pivot_wider(data, names_from = "taxon", values_from = "least")` get you close? If you want folks to test things, try adding some data we can copy and paste instead of screenshots. :) Some ideas on how to do that [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example).
Comment: that worked, thanks for your help! - yes, I understand that it's better to provide an example data so that others can test the code out :)
Answer: We can use
library(dplyr)
library(purrr)
data %>%
     split(.$samp_id) %>%
     imap(~ .x %>%
              select(taxon, least) %>%
              rename(!!.y := least)) %>%
      reduce(full_join, by = 'taxon')

Comment: Thanks - I've tried this, but got the following error; is there a way around this? "Error: cannot allocate vector of size 1.0 Gb"
Comment: @Maho that is unrelated to the code.  It is memory you don't have.  Perhaps tyr on a new session or use a cluster with memory


Print List Of List. Go from list[x][y] to list[y][x]

Question: I am learning python and have been presented with the following practice problem. I am trying to take the following list and print it in a right-justified table.
tableData= [['apples', 'oranges', 'cherries' , 'banana'],
            ['Alice' , 'Bob' , 'Carol', 'David'],
            ['dogs' , 'cats' , 'moose', 'goose']]

And the output should look like this.
  apples Alice  dogs
 oranges   Bob  cats
cherries Carol moose
  banana David goose

Here is my code.
tableData= [['apples', 'oranges', 'cherries' , 'banana'],
            ['Alice' , 'Bob' , 'Carol', 'David'],
            ['dogs' , 'cats' , 'moose', 'goose']]

def printTable(lists):
    colWidths = [0] * len(lists)
    for x in range(0, len(lists[0])):
        for y in range(0, len(lists)):
            colWidths[y] = len(max(lists[y]))
            fillChar= 0
            fillChar = colWidths[x] - len(lists[y][x])
            print(lists[y][x].rjust(fillChar, ' ' ) + ' ' , end = '' )

print(colWidths)
printTable(tableData)

The output I keep getting is below.
apples Alice dogs
oranges Bob cats
cherries Carol moose
 Traceback (most recent call last):
  File "/Users/DakotaDickey/Documents/Python Projects /Examples/PrintTable.py", line 36, in <module>
    printTable(tableData)
  File "/Users/DakotaDickey/Documents/Python Projects /Examples/PrintTable.py", line 17, in printTable
    fillChar = colWidths[x] - len(lists[y][x])
IndexError: list index out of range

Thanks for all your help
Comment: Is your example output supposed to be right justified?
Comment: Yes it is supposed to be right justified.
Comment: Okay, it just doesn't look like cats and dogs lines up with moose or goose
Answer: This is straightforward:
for item1, item2, item3 in zip(*tableData):
    print(item1.rjust(10) +  item2.rjust(10) + item3.rjust(10))

That will take care of getting your items for you individually and formatting it into a table. Your entire program has been condensed to two lines :)
This is how it works:

zip(l1,l2) takes two lists l1 and l2 and returns a single list with the corresponding elements of l1 and l2 merged into a tuple.
zip(*tableData) goes one step further and unpacks tableData into its individual lists. It's equivalent to doing zip(tableData[0], tableData[1], tableData[2]) in this case.
rjust(width) right justifies strings by width.
Comment: while this works for the given list I need this to work regardless of the number of lists inside the larger list and the length of those inner lists.
Comment: This will work regardless of the number of lists inside the larger list. If you want it to work independent of the lengths of the inner lists, why not just append empty strings to inner lists until they are all the same length and then run this function?
Comment: See [this question](http://stackoverflow.com/questions/1277278/python-zip-like-function-that-pads-to-longest-length) for how to take care of inner lists with differing lengths using `zip`.
Answer: Just to follow up on the previous answer, this is a little more general ...
# Find the maximum length of the words ...
w = max([ max(map(len, m)) for m in tableData ]) + 1

# print the data ...
print '\n'.join([''.join(map(lambda x: str(x).rjust(w), m)) for m in zip(*tableData)])

Answer: list = [['apples', 'oranges', 'cherries', 'banana'],
        ['Alice', 'Bob', 'Carol', 'David'],
        ['dogs', 'cats', 'moose', 'goose']]

def swaplist(list):
    result_list = []
    for index in range(0, len(list[0])):
        temp_list = []
        for i in list:
            temp_list.append(i[index])
        result_list.append(temp_list)
    return result_list

print swaplist(list)

it is just print
list = [['apples', 'oranges', 'cherries', 'banana'],
        ['Alice', 'Bob', 'Carol', 'David'],
        ['dogs', 'cats', 'moose', 'goose']]

def swaplist(list):
    for index in range(0, len(list[0])):
        temp_list = []
        for i in list:
            temp_list.append(i[index])
        print " ".join(temp_list)

swaplist(list)

Comment: This helps a lot. How would you go about printing with the rjust() method to ensure that the items are right justified the same amout?


Armazenar retorno de XML

Question: Eu tenho um retorno de um XML que é um loop(pois é único jeito que sei chamar retorno) porem no XML eu tenho dois det, det nItem="1" e det nItem="2" que sao 2 produtos, dentro deles se encontra a tag cEAN que é a que eu preciso separadas em variaveis diferentes para poder usar individualmente cada cEAN.
A minha chamada
import xml.etree.ElementTree as ET
tree = ET.parse("C:\\Users\\Expedição\\Videos\\XML\\xml_teste2.xml")
root = tree.getroot()

ns = {'nfe': 'http://www.portalfiscal.inf.br/nfe'}

for det in root.findall('.//nfe:det', ns):
    quantidade = det.find('.//nfe:qCom', ns).text
    EAN = det.find('.//nfe:cEAN', ns).text
    print (EAN.split())

O XML usado:
<nfeProc xmlns="http://www.portalfiscal.inf.br/nfe" versao="4.00">
<NFe xmlns="http://www.portalfiscal.inf.br/nfe">
<infNFe Id="NFe35200811625533000185550010000043291000219014" versao="4.00">
<ide>
...
</ide>
<emit>
...
</emit>
<dest>
<CNPJ>33737452000100</CNPJ>
<xNome>GP CAVALCANTE COMERCIO, IMPORTACAO E EXPORTACAO DE PECAS AUT</xNome>
<enderDest>
...
</enderDest>
<indIEDest>1</indIEDest>
<IE>799164503118</IE>
<email>firstname.lastname@example.com; email@example.com</email>
</dest>
<det nItem="1">
<prod>
<cProd>ET-CAM 01</cProd>
<cEAN/>
<xProd>CAMERA ESTAC MISTA (FURADA + SUP. BORBOLETA)</xProd>
<NCM>85258029</NCM>
<CEST>2106300</CEST>
<CFOP>5405</CFOP>
<uCom>UNI</uCom>
<qCom>20.0000</qCom>
<vUnCom>22.0000</vUnCom>
<vProd>440.00</vProd>
<cEANTrib/>
<uTrib>UNI</uTrib>
<qTrib>20.0000</qTrib>
<vUnTrib>22.0000</vUnTrib>
<indTot>1</indTot>
</prod>
<imposto>
...
</imposto>
</det>
<det nItem="2">
<prod>
<cProd>ET-CAM 02</cProd>
<cEAN>7898622140258</cEAN>
<xProd>CAMERA ESTAC DIANTEIRA</xProd>
<NCM>85258029</NCM>
<CEST>2106300</CEST>
<CFOP>5405</CFOP>
<uCom>UNI</uCom>
<qCom>10.0000</qCom>
<vUnCom>26.9000</vUnCom>
<vProd>269.00</vProd>
<cEANTrib>7898622140258</cEANTrib>
<uTrib>UNI</uTrib>
<qTrib>10.0000</qTrib>
<vUnTrib>26.9000</vUnTrib>
<indTot>1</indTot>
</prod>

Answer: Se quer processar cada valor individualmente, ainda é possível fazer dentro do loop. Basta verificar o valor do atributo nItem (assumindo que todas as tags det possuem este atributo). Algo assim:
for det in root.findall('.//nfe:det', ns):
    nItem = det.attrib['nItem']
    EAN = det.find('.//nfe:cEAN', ns).text
    if nItem == '1':
        # cEAN é do nItem 1, fazer o que precisa aqui
    elif nItem == '2':
        # cEAN é do nItem 2, fazer o que precisa aqui

Mas se quiser muito ter uma variável para cada, você pode buscar individualmente por cada det:
# busca por <det nItem="1">
det = root.find('.//nfe:det[@nItem="1"]', ns)
if det:
    cean1 = det.find('.//nfe:cEAN', ns).text

# busca por <det nItem="2">
det = root.find('.//nfe:det[@nItem="2"]', ns)
if det:
    cean2 = det.find('.//nfe:cEAN', ns).text

Aí depois você usa cada variável (cean1 e cean2) como bem entender.
Mas se a ideia é processar várias tags de uma vez (com uma quantidade que pode variar), eu ainda acho melhor fazer o loop e dentro dele decidir o que fazer (digo isso, claro, sem saber todo o contexto do seu problema).
Comment: muito obrigado pela ajuda.

Armazenar retorno de XML


Proof concerning Stirling numbers of the first kind

Question: How do I show that
$${ n\brack 2} = \frac{n!}{2} \sum_{m=1}^{n-1} \frac{1}{m(n-m)}$$
using a combinatorial argument?
My definition of ${n \brack 2}$ is "the number of elements of $S_n$ which can be decomposed as the product of exactly $2$ disjoint cycles".
Answer: The (standard) combinatorial interpreation of $\begin{bmatrix}n\\ i\end{bmatrix}$ is as permutations of $n$ into $i$ (disjoint) cycles;  we are interested in the case $i=2$.
Consider a permutation of $n$ into two cycles of length $\color{red}{m}$ and $\color{blue}{n-m}$
\begin{eqnarray*}
\color{red}{(a_1 a_2 \cdots a_m)} \color{blue}{(b_1 b_2 \cdots b_{n-m})}.
\end{eqnarray*}
The set $n$ can be partitioned into two (disjoint) sets of size $\color{red}{m}$ and $\color{blue}{n-m}$ in $\binom{n}{m}$ ways, the elements in the first cycle can be arranged in $\color{red}{(m-1)!}$ ways & the elements in the second cycle can be arranged in $\color{blue}{(n-m-1)!}$ ways, as $m$ ranges from $1$ to $n-1$  we will double count the possible configurations, thus
\begin{eqnarray*}
\begin{bmatrix}n\\ 2\end{bmatrix} = \frac{1}{2} \sum_{m=1}^{n-1} \binom{n}{m} \color{red}{(m-1)!} \color{blue}{(n-m-1)!} = \frac{n!}{2} \sum_{m=1}^{n-1} \frac{1}{\color{red}{m}\color{blue}{(n-m)}}.
\end{eqnarray*}
Answer: I am going to outline different proofs, related with different definitions of Stirling numbers of the first kind. An initial observation is that by partial fraction decomposition
$$ \sum_{m=1}^{n-1}\frac{1}{m(n-m)} = \frac{1}{n}\sum_{m=1}^{n-1}\left(\frac{1}{m}+\frac{1}{n-m}\right) = 2\,H_{n-1} $$
so the problem can be stated as "show that ${n \brack 2}=(n-1)! H_{n-1}$".
In terms of exponential generating functions, the problem of finding an explicit form for ${n\brack 2}$, defined as in OP's question above, boils down to finding the coefficients of the Taylor series of $\log^2(1-x)$. Since $-\log(1-x)=\sum_{n\geq 1}\frac{x^n}{n}$, by multiplying both sides by $\frac{1}{1-x}$ we get $\sum_{n\geq 1}H_n x^n = -\frac{\log(1-x)}{1-x}$ and by integrating both sides we get
$$ \log^2(1-x) = \sum_{n\geq 1}\frac{2\,H_n}{n+1}\,x^{n+1} = \sum_{n\geq 2}\frac{2\,H_{n-1}}{n}\,x^n. $$
An alternative definition of ${n\brack 2}$ is "the coefficient of $x^2$ in the polynomial $x^{(n)}=x(x+1)\cdots(x+n-1)$". With such a definition, ${n\brack 2}$ is the coefficient of $x$ in the polynomial $p(x) = (x+1)^{(n-1)}=(x+1)\cdots(x+n-1)$, i.e. $p'(0)$. Since $p(x)$ is given by a simple product, it is quite practical to express $p'$ in terms of the logarithmic derivative of $p$. We have
$$ p'(x) = p(x)\cdot\frac{d}{dx}\log p(x) = \left[\frac{1}{x+1}+\ldots+\frac{1}{x+n-1}\right](x+1)\cdots(x+n) $$
and by evaluating both sides at $x=0$ we get ${n\brack 2}=(n-1)! H_{n-1}$ as wanted.


$(function) gets called twice in Rails 3.2.1 App

Question: I've got a Rails 3.2.1 app that I'm trying to include some jquery in.
Here are the files:
states.js:
var grid;

var columns = [
 {id: "firstName", name: "FirstName", field: "FirstName"},
 {id: "lastName", name: "LastName", field: "LastName"}
]

var options = {
 enableCellNavigation: true,
 enableColumnReorder: false
};

$(function () {
 alert("hi");
 var state = $("#myGrid").data("state");
 $.getJSON(state, function(data){
    grid = new Slick.Grid("#myGrid", data, columns, options);
});
})

states_controller.rb:
class StatesController < ApplicationController
def index
  @states = SiteIndexPlayer.select("DISTINCT HometownState")
end

def name
  logger.debug(":name #{params[:name]}")
  @athletes = SiteIndexPlayer.select('FirstName, LastName').find_all_by_HometownState(params[:name])
  @state=params[:name]
  respond_to do |format|
    format.html
    format.json { render json: @athletes }
  end
end
end

I'm getting the "hi" popup twice on every page load.
Are there 2 requests going out for some reason?
Thanks
Problem
Turns out states.js is being loaded to the DOM twice.  I'm not precompiling the assets.  Any other ideas why the file is getting loaded twice?
Solution
ls app/assets/javascripts
application.js  lib     slick.core.js   slick.grid.js states.js.coffee  states.js

I'm guessing the states.js.coffee was loading the file as well as application.js.  As soon as I removed states.js.coffee, it worked fine.
Know where I might read up on *.coffee?
Edit
application.js:
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require_tree .

application.html.erb
<!DOCTYPE html>

  <title>CapApp</title>
  <%= stylesheet_link_tag    "application", :media => "all" %>
  <%= javascript_include_tag "application" %>
  <%= csrf_meta_tags %>

<%= yield %>

Comment: Any chance you precompiled your assets in development mode? This will cause all your files to be loaded twice (the precompiled version as well as the individual files)
Comment: possible duplicate of [My application.js docment.ready function is called twice](http://stackoverflow.com/questions/8672249/my-application-js-docment-ready-function-is-called-twice)
Comment: Where do you include your JS files? Please show your app/assets/application.js and app/views/layouts/ files.
Comment: Or perhaps: http://stackoverflow.com/questions/4107445/jquery-ready-function-is-called-twice
Comment: Have you accidentally included "states.js" twice? (I know that seems obvious, but it can't hurt to eliminate the obvious.)
Comment: Same problem for me, coffee scripts hadn't been deleted.
Answer: I'm guessing the states.js.coffee was loading the file as well as application.js. As soon as I removed states.js.coffee, it worked fine.
Answer: I found the same symptom with Rails 3.2.x, in my environments/staging.rb file I had made the setting
# Expands the lines which load the assets
config.assets.debug = true

yet Capistrano was configured to precompile assets, thus I had one copy in application.js and another in the controller-specific .coffee file.  Setting the value to false resolved the problem for me.
Answer: Did you "rake assets:procompile"? if y, please try "assets:clean" and run server


Why Jmenubar isn't visible in my Jframe even after adding setJMenubar() method?

Question: I am new to java swing class and was learning how to add menubars and menus in JFrame.
I have written a simple example but the JFrame is displayed empty and I don't know why because I have included setJMenuBar() method in my code then also menubar isn't visible.
Here is my code
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class jmenuexample extends JFrame //implements ActionListener
{
    JLabel title;
    JMenuBar menubar;
    JMenu menu, submenu;
    JMenuItem menuItem;
    jmenuexample()
    {
        setTitle("JMenu Example");
        setSize(750, 450);
        //setLayout(null);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        menubar = new JMenuBar();
        menu = new JMenu("File");
        menuItem = new JMenuItem("New\tCtrl+N");
        menu.add(menuItem);
        menuItem = new JMenuItem("Open\tCtrl+O");
        menu.add(menuItem);
        menuItem = new JMenuItem("Save\tCtrl+S");
        menu.add(menuItem);
        //menu.addSeparator();
        menuItem = new JMenuItem("Exit");
        menu.add(menuItem);
        menubar.add(menu);
        /*panel = new JPanel();
        panel.setLayout(new GridLayout());
        panel.setBounds(250,10, 400, 300);*/
        //add(menubar);
        //add(panel);
        this.setJMenuBar(menubar);
    }
    public static void main(String argv[])
    {
        new jmenuexample();
    }
}

And here is the output of this code.
Comment: Don't add "Ctrl_O" as part of the text of the menu item. Instead you need to use the `setAccelerator(...)` method of the `JMenuItem`. Read the section from the Swing tutorial on [How to Use Menus](http://docs.oracle.com/javase/tutorial/uiswing/components/menu.html) for more information and working examples. The tutorial will also help you better structure your class so your components are created on the `Event Dispatch Thread (EDT)`. Keep the tutorial link handy for all the Swing basics.
Comment: *"I am new to java swing"* So then start doing it right: Learn about [Java Naming conventions](http://www.oracle.com/technetwork/java/codeconventions-135099.html) and do not inherit from JFrame (http://stackoverflow.com/questions/15867148/why-do-we-need-to-extend-jframe-in-a-swing-application).
Answer: Because you are using setVisible(true); before you set
this.setJMenuBar(menubar);
so chnage the order and setVisible(true); in the end.
Your code should be like this:
....
menubar.add(menu);
/*panel = new JPanel();
 panel.setLayout(new GridLayout());
 panel.setBounds(250,10, 400, 300);*/
//add(menubar);
//add(panel);
this.setJMenuBar(menubar);
setVisible(true);
....

Hope this can help you.


Is p-value similar or equal to its reversed version?

Question: I'm going to check if:
$P(T(x)\geq t \mid H_0) = P(H_0\mid T(x)>t)$.
As a sidenote, it's a self-study post. I did my math courses a little while ago, so I do not remember exactly how it goes with probability calculus and kindly ask for help.
Actually I know there is no equation between these two conditional probabilities, so that's why we have bayesian branch of statistics, but I'd like to find out on my own.
Suppose I had $10$ coin flips and got $7$ heads.
Then, according to NHST, I state the null hypothesis that $H_0: \theta = 0.5$, where $\theta$ is a probability of obtaining heads.
The alternative hypothesis is $H_0: \theta > 0.5$ (for ease of calculations it's one-sided test).
$T(x)$ is my test statistics, is a ratio of heads in 10 coin flips, I got $7$ heads so $T(x)=\frac{7}{10}$.
The p-value is $P(T(x)\geq \frac{7}{10}\mid H_0) = P(T(x)\geq \frac{7}{10}\mid \theta=0.5) = 0.17$
A one-line code in R is:
pbinom(6,10,0.5, lower.tail = FALSE)

But I also want to check if reverse probability ($P(\theta=0.5\mid T(x)\geq\frac{7}{10})$) is similar or equal to $0.17$.
This time I need to use the Bayes' Theorem and define prior probability for $\theta$.
I need to evaluate $P(\theta=0.5\mid T(x)\geq\frac{7}{10})$.
Previously, I tried to break down the condition into summation, but as @Ian pointed in his answer - the conditional probability is not additive over the condition.
Doing this step-by-step I get:
$P(\theta=0.5\mid T(X)\geq 0.7)=\frac{P(\theta=0.5, T(x)>0.7)}{P(T(x)>0.7)}=\frac{P(T(x)>0.7\mid\theta=0.5)\cdot P(\theta=0.5)}{P(T(x)>0.7}$
Here, I have to assume some prior distribution for $\theta$, so I chose discrete uniform on set $\{0.1, 0.2, \ldots, 1\}$ (just to have some prior).
The numerator  $P(T(x)\geq 0.7, \theta=0.5)= P(T(x)=0.7\mid\theta=0.5)\cdot P(\theta=0.5) +
P(T(x)=0.8\mid\theta=0.5)\cdot P(\theta=0.5)+P(T(x)=0.9\mid\theta=0.5)\cdot P(\theta=0.5)+P(T(x)=1.0\mid\theta=0.5)\cdot P(\theta=0.5)
= {10\choose 3}\cdot 0.5^7\cdot 0.5^3\cdot \frac{1}{10}+{10\choose 2}\cdot 0.5^8\cdot 0.5^2\cdot \frac{1}{10}+
{10\choose 9}\cdot 0.5^9\cdot 0.5^1\cdot \frac{1}{10}+
{10\choose 10}\cdot 0.5^{10}\cdot 0.5^0\cdot \frac{1}{10}=0.017$
The denominator.
Probably, it's correct to rewrite the denominator:
$P(T(x)\geq0.7)=P(T(x)=0.7)+P(T(x)=0.8)+P(T(x)=0.9)+P(T(x)=1.0)$.
Now I have to calculate those terms, I do it by:
$P(T(x)=0.7)=\sum_{\theta\in\{0.1,0.2,\ldots 1\}} P(T(x)=0.7, \theta)\cdot f(\theta)= \sum_{\theta\in\{0.1,0.2,\ldots 1\}}{10\choose 3}\cdot\theta^7\cdot(1-\theta)^3\cdot\frac{1}{10} = \frac{1}{10}{10\choose 3}\sum_{\theta\in\{0.1,0.2,\ldots 1\}}\theta^7\cdot(1-\theta)^3$
It's far faster to use R in the calculations.
sum(0.1*choose(10,7)*\theta^7*(1-\theta)^3)

The result is $P(T(x)=0.7)=0.091$
Doing this for $P(T(x)=0.8)$, $P(T(x)=0.9)$, and $P(T(x)=1.0)$, I get (respectively) $0.0906, 0.0828$ and $0.149$. Then these four sums are again add up to get $P(T(x)\geq 0.7)=0.414$
Finally, the result is $P(\theta=0.5\mid T(x)\geq 0.7)= \frac{P(T(x)\geq 0.7|\theta=0.5)\cdot P(\theta=0.5)}{P(T(x)\geq 0.7)} = \frac{0.017}{0.414}=0.0.41\not=0.17$.
This proves that 'reversed' conditional probabilities, p-value and its reverse, are not equal, I'm really proud of the result.. but the thing that bothers me...
[Q] Is this all correct? Especially in terms of probability calculus and all conditional probabilities.
Answer:
I don't think you need all these calculations to see what's going on in this case. Whatever you choose for a discrete prior for $\theta$, the result of $P(\theta=0.5 \mid T \geq 0.7)$ will depend on what that prior actually was. In particular, if $\theta=0.5$ was impossible under your prior for whatever reason (maybe you're paranoid and assume every coin you find is biased), this conditional probability would be zero regardless of what data you got. That said, no, the conditional probability is not additive over the condition, only over the event whose probability is being measured. $P(A \cap B)$ is additive as a function of $B$, but you have to divide by $P(B)$ which breaks the additivity.
You're correct. In general you really want to look at the posterior distribution for $\theta$, which is again a continuous distribution, so you would want to measure the density of this posterior distribution at $0.5$.
Comment: My first question is a mathematical issue: if it's mathematically correct to break down condtioning. Is f(X|Y>a) equal to f(X| Y=a+1)+f(X|Y=a+2)+etc (if Y is discrete of course and can be a,a+1, a+2, etc).
Comment: @Lili No, it's not. I said that after an edit.


Como solucionar o erro: String data, right truncated: 1406

Question: Olá, segue a minha dúvida:

Estou tentando salvar os dados do Checklist Protocolo, mas está ocorrendo o seguinte erro:

SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'item' at row 1

Como solucionar este problema?
1. Segue a imagem do modal Checklist Protocolo:
É o formulário responsável por receber os dados inseridos pelo usuário.

2. Segue a imagem do erro, ao tentar cadastrar os dados:

3. Método de cadastroChecklistProtocolo da classe ProjetoController.php
Este método e responsável por cadastrar os dados do checklist protocolo no banco de dados.
   public function cadastroChecklistProtocolo(Request $request)

    {
        // Deletar a tabela de checklist_protocolo
       $checklistsProtocolos = ChecklistProtocolo::where('projeto_id', $request->projeto_id)->delete();

 $data = $request->all();
        $dataInsert = [];
            //Observe que eu tirei o push ($dataInsert[]) pois assim iria adicionar mais uma array no fim
            $dataInsert = [
                'projeto_id' => $data['projeto_id'],
                'item' => $data ['item'],
                'modelo_id' => $data['modelo_id'],
                'item_descricao_id' => $data ['item_descricao_id'],
                'sim_nao' => $data ['sim_nao'],
                'nao_atende' => $data ['nao_atende'],
                'dt_validade' => $data ['dt_validade'],
                'pagina_documento' => $data ['pagina_documento'],
                'observacao' => $data ['observacao'],

            ];

            //dd($dataInsert);
           $dados =  ChecklistProtocolo::create($dataInsert);

     $response= true;

        if($response)
        {
            return redirect()
                      ->route('projeto.edita', $request->projeto_id)
                      ->with('success',"Sucesso ao atualizar os Checklists do Protocolo");
        }else
        {
            return redirect()
                      ->back()
                      ->with('error',"Erro ao atualizar o Checklists do Protocolo");
        }
    }

4. Código do Modal ChecklistProtocolo:

<form id="checklistProtocolo" action="{{route('projeto.cadastroChecklistProtocolo')}}" method="POST">

                  {{ csrf_field() }}

                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                ×
                            </button>

Checklists do Protocolo

                             <input type="hidden" id="projeto_id" name="projeto_id" value="{{$projeto->id}}">
                             <input type="hidden" id="modelo_id"  name="modelo_id" value="{{$modeloProtocolo[0]['id']}}">
                             Modelo
                             <input type="text" class="form-control" name="modeloProcesso" value="{{$modeloProtocolo[0]['modelo']}}" disabled>

                                            Item
                                            Descrição
                                            Sim/Não
                                            Não Atende
                                            Data de Validade
                                            Página do Documento
                                            Observações

                            @foreach($checklistsProtocolos as $checklistProtocolo)

                                    <input type="text" class="form-control"  id="item" name="item[]" value="{{$checklistProtocolo->item}}"  size ="2">
                                    {{$checklistProtocolo->descricao_item}}
                                    <input type="hidden"          id="item_descricao_id"  name="item_descricao_id[]" value="{{$checklistProtocolo->item_descricao_id}}">
                                    <input type="checkbox"    id="sim_nao"            name="sim_nao[]"    {{$checklistProtocolo->sim_nao == null ? '' : 'checked'}}>
                                    <input type="checkbox"    id="nao_atende"         name="nao_atende[]" {{$checklistProtocolo->nao_atende == null ? '' : 'checked'}}>
                                    <input type="date"        id="dt_validade"        name="dt_validade[]" value="{{$checklistProtocolo->dt_validade}}">
                                    <input type="text"        id="pagina_documento"   name="pagina_documento[]" value="{{$checklistProtocolo->pagina_documento}}" size ="1">
                                    <input type="text"        id="observacao"         name="observacao[]" value="{{$checklistProtocolo->observacao}}" size ="1" style="width: 300px; height: 60px">

                            @endforeach

                        <button type="submit" class="btn btn-primary"  aria-hidden="true" style="width: 300px; height: 40px" > Salvar</button>

            </form>

5. Código do modelo ChecklistProtocolo.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DB;
use SoftDeletes;

class ChecklistProtocolo extends Model
{
    protected $table = "checklist_protocolo";

    protected $primaryKey =  ['projeto_id', 'modelo_id','itens_descricao_id'];

    public $incrementing = false;

    public $timestamps = false;

    protected  $fillable  = ['projeto_id', 'modelo_id','item','itens_descricao_id','sim_nao', 'nao_atende','dt_validade','pagina_documento','observacao'];

    protected $casts = [ 'item' => 'array', 'item_descricao_id'=> 'array','sim_nao' => 'array', 'dt_validade'=> 'array',
    'pagina_documento'=> 'array', 'observacao'=> 'array', 'nao_atende'=> 'array'];

    /*
    public function checklistProtocolo()
    {
         return $this->belongsTo(ChecklistProtocolo::class, 'projeto_id','modelo_id', 'itens_descricao_id');
    } */

    //Este método salva os dados do Checklist do Protocolo
    public function salvar(ChecklistProtocolo $checklistProtocolo) : Array
    {
       $checklistProtocolo = $this->save();

         if($checklistProtocolo){

            return[
                'success' => true,
                'message' => 'Sucesso ao cadastrar'
            ];
        }
        else{

            return[
                'success' => false,
                'message' => 'Falha ao cadastrar'
            ];
        }
    }

    //Este método remove os dados do Checklist do Protocolo
  public function deletar(checklistProtocolo $checklistProtocolo) : Array
  {
      $checklistProtocolo =  $this->delete();
      if($checklistProtocolo){

          return[
              'success' => true,
              'message' => 'Sucesso ao excluir'
          ];
      }
      else{

          return[
              'success' => false,
              'message' => 'Falha ao excluir'
          ];
      }
  }

//Este método atualiza os dados do  Checklist do Protocolo
public function alterar(checklistProtocolo $checklistProtocolo) : Array
{
  $checklistProtocolo = $this->save();
    if($checklistProtocolo){
        return[
            'success' => true,
            'message' => 'Sucesso ao atualizar'
        ];
    }
    else{
        return[
            'success' => false,
            'message' => 'Falha ao atualizar'
        ];
    }
}

}

6. Debug da variável "$request->all();"

7. Modelo ER"

8. Descrição da tabela do banco de dados
Comment: Seu `modelo_id` está diretamente dentro do `$request->all()` mas você tenta acessar ele dentro do loop
Comment: O correto seria `'projeto_id' => $data['projeto_id']` e o loop deveria ser feito apenas nos campos onde existe array: Item, item_descricao_id, sim_nao etc...
Comment: Obrigada pela resposta @edsonalves. Eu testei da forma que vc falou, mas ocorreu o seguinte erro: Illegal string offset 'item'.
Comment: É que o `item` também está no nivel 0 da array... Com "fazer o loop nos que são arrays" eu quis dizer algo como:  `foreach ($data['item'] as $items) {` e percorrer os valores dele... Mas vc não precisa fazer um loop direto em `$data` basta pegar os valores diretamente
Comment: Segue o método:  public function cadastroChecklistProtocolo(Request $request){
$data = $request->all();$dataInsert = []; $dataInsert['projeto_id'] =  $data['projeto_id']; $dataInsert['modelo_id'] =  $data['modelo_id'];
Comment: foreach ($data as $dataForm) {$dataInsert[] = ['item' => $dataForm['item'], 'item_descricao_id' => $dataForm['item_descricao_id'],'sim_nao' => $dataForm['sim_nao'],  'dt_validade' => $dataForm['dt_validade'],  'pagina_documento' => $dataForm['pagina_documento'],  'observacao' => $dataForm['observacao'], 'nao_atende' => $dataForm['nao_atende'],];
Comment: $dados =  ChecklistProtocolo::create($dataInsert);$dados->save(); }}
Comment: Atualiza sua pergunta com estes dados, não é legal colocar trechos tão grandes nos comentários
Comment: Olá @edson alves. A pergunta foi atualizada. Gostaria que você me demonstrasse um exemplo.
Answer: Conforme meu comentário, não é necessário realizar um loop nos dados do $data basta acessar diretamente:
Obs: Se eu Model não estiver preparado para aceitar arrays esta linha $dados =  ChecklistProtocolo::create($dataInsert); resultará em erro, já que dataInsert é um array de 2 níveis.
       $data = $request->all();
        $dataInsert = [];
            //Observe que eu tirei o push ($dataInsert[]) pois assim iria adicionar mais uma array no fim
            $dataInsert = [
                'projeto_id' => $data['projeto_id'],
                'modelo_id' => $data['modelo_id'],
                'item' => $data ['item'],
                'item_descricao_id' => $data ['item_descricao_id'],
                'sim_nao' => $data ['sim_nao'],
                'dt_validade' => $data ['dt_validade'],
                'pagina_documento' => $data ['pagina_documento'],
                'observacao' => $data ['observacao'],
                'nao_atende' => $data ['nao_atende'],
            ];
           $dados =  ChecklistProtocolo::create($dataInsert);
           $dados->save();

Update
O erro

SQLSTATE[22001]: String data, right truncated: 1406 Data too long for
  column 'item' at row 1
  Acontece pois sua coluna item (e outras) não tem espaço suficiente para salvar o dado, sendo apenas 10 caracteres.

Ao usar o cast, seu array será convertido em string para ser salvo, o que gera uma string bem maior que 10 caracteres.
Comment: Olá, @edson. Eu testei a sua solução, mas ocorreu o seguinte erro: Array to string conversion (SQL: insert into `checklist_protocolo` (`projeto_id`, `item`, `modelo_id`, `sim_nao`, `nao_atende`, `dt_validade`, `pagina_documento`, `observacao`) values (12, 0, 7, on, on, 2018-11-28, 1, tetes))
Comment: Como eu disse, "Se eu Model não estiver preparado para aceitar arrays esta linha $dados =  ChecklistProtocolo::create($dataInsert); resultará em erro, já que dataInsert é um array de 2 níveis.", você está tentando inserir um array no banco, você pode adicionar uma mutator no seu model para cada valor com array, exemplo `protected $casts = [
        'item' => 'array',
    ];`
Comment: Ficaria: `$casts = [ 'item' => 'array', 'item_descricao_id'=> 'array' [...]];` fazendo isto para cada um dos valores que são array... Existem outras formas de fazer, por exemplo separando em tabelas, mas assim acho que vai ser mais fácil
Comment: https://laravel.com/docs/5.7/eloquent-mutators#attribute-casting
Comment: Oi @edson alves. Eu inseri a variável $cast no modelo. Mas, ao salvar os dados ocorreu o seguinte erro: SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'item' at row 1.
Comment: A dúvida foi atualizada.
Comment: Parece que sua coluna não tem espaço suficiente para aceitar a string. Qual o tipo dela e o tamanho? Adiciona sua migration na pergunta.
Comment: A descrição da tabela foi inserida na dúvida.
Answer: Solução para o projeto em questão foi criar uma variável ($cont) para contar linha de cada array dentro do loop de repetição que será refletido na View.
Referência:
Salvar itens de um formulário checklist no banco - Laravel
Segue código:
for($i = 0; $i < count($dt_validade); $i++){

                   $dataInsert = array(
                         'sim_nao' => $sim_nao[$cont],
                         'dt_validade'=> $dt_validade[$cont],
                         'pagina_documento' =>$pagina_documento[$cont],
                         'observacao' =>$observacao[$cont]);

                         $checklistsProtocolos = checklistProtocolo::where('projeto_id', $projeto_id)
                         ->whereIn('item_descricao_id', (array)$item_descricao_id[$cont])  //atualiza linha por linha do array
                         ->update($dataInsert);
                         $cont++; //atualiza linha por linha do array
                  }


Problems with user's privileges, wordpress, phpmyadmin, my host provider and I hope that's all

Question: So I've been trying to install a new wordpress site beside an already working site. I want to have 2 different databases, so i created a new one, and I didn't go very far from that. I get the message "Can't select database" in /wp-admin/, and in the sql_error there is : "Access denied for user 'user'@'host' to database 'database'"

After creating the database, and went to phpmyadmin to create a new user and his privileges, but there's no privileges tab in phpmyadmin. I did empty cookies and all, but with no effect.
My host provider provides "mysql databases" tool. There is a drop list to make associations between schemas and users, so i did it, but there is no way to control that it's really taken into account
I installed chive, but i can't find the privileges tab neither
with sql queries, in phpmyadmin, i can't add any privileges, i get a "access denied to my_root_user on my_schema"
It's the same errors when i try with an old user on the new schema.

Does somebody have a clue on what to try next ? If that comes from my provider configuration, how can i get the proof ?
Comment: Check out the hosting provider's customer control panel. Plain web hosts (no VPS) usually don't allow direct permission access. In this case, you might be able to add a new account from your control panel. Also note, that your question might be more appropriate at http://webmasters.stackexchange.com (don't post a duplicate there, questions can be migrated). More details about your setup/host are appreciated.
Answer: Ok, meanwhile I've send a mail to the support.
They told me they deactivated the user management in phpmyadmin and that I have to go through the cpanel.
That, I already tried.
But he told me that if I have difficulties to add the privileges, I have to deselect one of the checkbox (the "trigger" grant), without using the "all privileges" checkbox.....
So either according the trigger privileges to a user in wordpress breaks it, or my provider have shitty management tools.


Serve behind a virtual network

Question: I want to run a http server from a computer that is inside a virtual network to the outside world. I don't have any access to the gateway so cannot configure that. I was thinking that there could be a server outside my network that would work as a proxy for my server. I would make an outbound connection from my computer to this server proxy, and once this connection made every request to the server proxy would be directed to some port in my computer.
Is there something that provides this service? There were several times that I have been in this sit
Comment: you might be able to do this with SSH tunnels
Answer: SSH has the ability to do what you want. From inside your "virtual" network, you could create an SSH tunnel to the publically-accessible server with a command line like:
ssh -R ':8080:localhost:80' server.example.com

For this to work, server.example.com needs to be running sshd, obviously. Also, the server's sshd_config needs to set GatewayPorts yes, otherwise any tunnel you create will bind only to the server's loopback address, which will be not accessible by remote clients. (The default setting for GatewayPorts is no.)
In the above example, connection attempts to TCP port 8080 on the server will be forwarded to port 80 on localhost.
Comment: That seem what I am looking for. But do rented web servers generally allow you to edit sshd_config?
Comment: @Bernardo Kyotoku: Any sane admin of shared hosting would almost certainly not want to enable the `GatewayPorts` setting. In fact, most of the ones providing ssh access probably disable port forwarding altogether (I would). I am assuming that `server.example.com` would be a server that you control.
Comment: That what I thought. That is why I specified if there is someone who specifically provides this kind of service. It is not the first time I find myself in this situation. This happens every time I am want to test my webapp in a coffee shop network.
Answer: You really need to talk to the Network and/or Host Server administrator about this. If for example you're in a corporate environment they might not be too happy with you if you did something like this.
That said, you could probably use an SSH Tunnel, though I don't know how practical that would end up being.

Serve behind a virtual network


É possível fazer isso com table td?

Question: Ok vejamos:
//PHONE

        COL 1
        COL 2

        COL 1
        COL 2

//TABLET E MAIORES
@media only screen and (max-width : 768px) { table>tr>td {...} }
@media only screen and (max-width : 1024px) { table>tr>td {...} }

        COL 1
        COL 2
        COL 3

        COL 1

É possível fazer isto? Quando estiver no celular uma tr com duas td, em tablets começam a ter uma tr com 3 td depois com 4 e assim por diante...
Answer: Podes usar o nth-child para esconder as colunas. Seria algo assim:
@media only screen and (max-width: 768px) {
    table td:nth-child(n+3) {
        display: none;
    }
}

@media only screen and (max-width: 1024px) {
    table td:nth-child(n+4) {
        display: none;
    }
}

Exemplo: http://jsfiddle.net/x6rckfsp/
Answer: @media não pode alterar a codificação HTML, apenas o estilo de cada elemento HTML.
Interessante seria vc usar div com porcentagens.
Comment: Concordo que não pode alterar o HTML mas pode esconder/mostrar certo?
Comment: Certo, mas esconder/mostrar não vai resolver seu problema. Certo seriam divs com porcentagens para cada dispositivo/tamanho de tela.
Comment: Sim verdade, mas com `table{ width: 100%;}` parece funcionar bem: http://jsfiddle.net/x6rckfsp/1/
Comment: Então. Pela dúvida dele, seria normal: width:50% e com as media query ficariam com width: 33%. A dúvida é posicionar as colunas, e não ocultá-las.

É possível fazer isso com table td?


TYPO3 Testing Framework - FunctionalTestCase not loading TCA overrides from extension

Question: How can I apply TCA overrides in a FunctionalTestCase class?
I am writing a TYPO3 functional test for an extension that extends the FrontendUser domain model and repository. The TYPO3 testing framework is used to run the test but it does not seem to  load the override TCAs from the Configuration/TCA/Overrides/fe_users.php file. Is there a Bootstrap function I am missing or perhaps extra setup? (Anything below in < > tags has been replaced for NDA purposes, such as internal extension keys)
This is the error:
   ┐
   ├ TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\SqlErrorException: Unknown column 'gender' in 'field list'
   │
   ╵ <extension-folder>/.Build/Web/typo3/sysext/extbase/Classes/Persistence/Generic/Storage/Typo3DbBackend.php:146
   ╵ <extension-folder>/.Build/Web/typo3/sysext/extbase/Classes/Persistence/Generic/Backend.php:634
   ╵ <extension-folder>/.Build/Web/typo3/sysext/extbase/Classes/Persistence/Generic/Backend.php:282
   ╵ <extension-folder>/.Build/Web/typo3/sysext/extbase/Classes/Persistence/Generic/Backend.php:269
   ╵ <extension-folder>/.Build/Web/typo3/sysext/extbase/Classes/Persistence/Generic/PersistenceManager.php:166
   ╵ <extension-folder>/Tests/Functional/Domain/Repository/FrontendUserRepositoryTest.php:96
   ┴

This is the functional test class:
class FrontendUserRepositoryTest extends FunctionalTestCase
{

    protected $testExtensionsToLoad = [
        'typo3conf/ext/<my-extension-key>'
    ];

    protected $coreExtensionsToLoad = [
        'typo3/sysext/extbase'
    ];

    /**
     * @var FrontendUserRepository
     */
    protected $frontendUserRepository;

    /**
     * @var PersistenceManager
     */
    protected $persistenceManager;

    /**
     * @var FrontendUser
     */
    protected $frontendUser;

    /**
     * @var string
     */
    protected $email;

    /**
     * @var string
     */
    protected $firstName;

    /**
     * @var string
     */
    protected $lastName;

    protected function setUp(): void
    {
        parent::setUp();

        Bootstrap::initializeBackendUser();
        $GLOBALS['BE_USER']->user['admin'] = 1;
        $GLOBALS['BE_USER']->user['uid'] = 1;
        $GLOBALS['BE_USER']->workspace = 0;
        Bootstrap::initializeLanguageObject();

        /** @var PersistenceManager $persistenceManager */
        $this->persistenceManager = GeneralUtility::makeInstance(PersistenceManager::class);

        $objectContainer = new Container($this->getContainer());
        $objectManager = new ObjectManager($this->getContainer(), $objectContainer);
        $this->frontendUserRepository = new FrontendUserRepository($objectManager);
        $this->frontendUserRepository->injectPersistenceManager($this->persistenceManager);

        $this->email = 'email@example.com';
        $this->firstName = 'Tester';
        $this->lastName = 'Man';

        $this->frontendUser = GeneralUtility::makeInstance(FrontendUser::class);
        $this->frontendUser->setEmail($this->email);
        $this->frontendUser->setFirstName($this->firstName);
        $this->frontendUser->setLastName($this->lastName);
    }

    /**
     * @test
     * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException
     */
    public function testRetrieveByEmailFromRepository()
    {
        $this->frontendUserRepository->add($this->frontendUser);
        $this->persistenceManager->persistAll();

        /** @var FrontendUser $frontendUser */
        $frontendUser = $this->frontendUserRepository->findUserByEmail($this->email)->getFirst();
        $this->assertEquals($this->email, $frontendUser->getEmail());
        $this->assertEquals($this->firstName, $frontendUser->getFirstName());
        $this->assertEquals($this->lastName, $frontendUser->getLastName());
    }

    /**
     * @test
     */
    public function checkIfTableExists()
    {
        $queryBuilder = $this->getConnectionPool()->getQueryBuilderForTable('INFORMATION_SCHEMA.COLUMNS');
        $queryBuilder->getRestrictions()->removeAll();
        $query = $queryBuilder->select('COLUMN_NAME')
            ->from('INFORMATION_SCHEMA.COLUMNS')
            ->where(
                $queryBuilder->expr()->eq('TABLE_NAME', $queryBuilder->createNamedParameter('fe_users'))
            )
            ->execute();

        /* Dumps the base fe_users table columns without the TCA overrides applied */
        var_dump($query->fetchAllAssociative());
    }

}

Answer: I solved this by defining the missing columns explicitly in the ext_tables.sql file, but this should not be neccessary since the extension was working without this defined:
CREATE TABLE fe_users (
    gender tinyint DEFAULT 0 NOT NULL,
    status tinyint DEFAULT 0 NOT NULL,
    privacy tinyint(1) DEFAULT false NOT NULL,
    --etc. etc.
);

If someone can tell me where the TCA overrides are persisted to the database table, that would be greatly appreciated.
Comment: TCA does not automatically create database columns if you meant that. You'll always need `ext_tables.sql` for new fields in order to have the DB compare tool add them to the the database.


To use or not Bernoulli trials

Question: I was asked to model the following experiment:
Consider the n-th toss of a fair coin, and the event
$E$ = '$k$-th toss results in heads'.
I find easier to model the experiment using n random variables each Bernoulli distributed. But there is no mention of independence. The other formulation is using finite sequences of length n, but for some reason the probability measures seem to coincide. Does this imply that the defined random variables are necessarily indenpendent?
Comment: Coin tosses are traditionally treated as independent with no additional specification.
Answer: Consider the $2^n$ possible sequences of heads and tails. If by definition these outcomes are equally likely then the model coincides with the one based on distinct events and assuming independence.
Saying that the possible sequences are equally likely is equivalent to the assumption of independence.
Most importantly: both assumptions are arbitrary. You cannot justify either of them. Mathematics can tell only that the two hypotheses are quivalent.
BTW: There is a similar question and some answers here.
Comment: thanks for the answer, and the link, I found it very useful
Answer: When you assert that you can equivalently formulate a set of $n$ Bernoulli variates as a finite sequence of length $n$ such that the probability of each possible sequence is equal, you have imposed conditions that do imply the independence of the $n$ Bernoulli variates.
On the other hand, suppose for example you take a space of sequences such that the probability of any sequence is proportional to the longest run of identical results.  For $n=3$ this would be distributed as
$$\begin{array}{cl}
TTT:& \frac{3}{16} \\
TTH:& \frac{2}{16}\\
THT:& \frac{1}{16}\\
THH:& \frac{2}{16}\\
HTT:& \frac{2}{16}\\
HTH:& \frac{1}{16}\\
HHT:& \frac{2}{16}\\
HHH:& \frac{3}{16}
\end{array}
$$
Now you will find that the individual Bernoulli variates are not independent; in particular, the likelihood that $b_n = b_n-1$ is $\frac{5}{8}$ even though the likelihood that $b_n$ is heads without knowing any other $b_k$ is $\frac12$.
Comment: thanks, the example is very illustrative

To use or not Bernoulli trials


What syntax exists for higher order logic?

Question: I know this is sort of a broad question, but I'm having trouble getting a handle on the syntax for higher order logic, when going from first order logic. Basically I want to be able to do resolution proofs in higher order logic since it works so well for first order logic.
The syntax of first order logic I understand as this:
A first order term is either a variable or a first order function of some arity. Functions of arity zero can be represented as constants. A first order function takes only terms as its arguments. There are an infinite number of first order element variables. There are an infinite number of free (constant) first order functions. Nothing else is a term.
A first order predicate takes only first order terms as arguments. Predicates that take no arguments can be represented as propositional constants.
A first order logical formula consists of predicates, and logical formula connected by logical connectives, including negation, conjunction, disjunction, and quantifiers. Quantifiers quantify element variables, either universal or existential. Logical connectives can connect to predicates or other logical formula. Nothing else is a logical formula.
Example first order statement: $\forall$x$\exists$y P(x,y) $\rightarrow$ Q(f(x), g(y))
Now, we can extend this to second order logic by allowing quantification of functions and predicates/relations. Now first order function constants and predicate constants are no longer required to be free constants, but may be bound variables. Other than that it's identical to first order logic. The semantics may be more complicated, because the completeness and compactness theorem no longer apply in full semantics, and higher order proof calculus may be more complicated because higher order Skolemization is more complicated and may require the axiom of choice, but the syntax isn't much different. But quantified functions and relations in second order logic still take first order terms and return first order terms and truth values respectively.
Using our first order example as quantified second order logic:
$\forall$P$\exists$Q$\forall$f$\exists$g$\forall$x$\exists$y P(x,y) $\rightarrow$ $Q(f(x), g(y))$
This seems pretty straightforward if I want to do resolution proofs in second order logic. I can use most of the same proof calculus as first order logic, with new rules for unifying function variables and predicate variables.
But when we go higher orders the syntax seems more muddy. Do we have second order terms as different types from first order terms? For instance I can have a third order function variable that takes a second order function variable as an argument... and have its domain be first order terms, or second order functions, of all sorts of different arities and signatures. Or a fourth order predicate that takes a third order function of a specific arity and a second order function, and a first order term. It looks to me like there's an explosion of syntactical complexity at third order logic and higher, but I haven't seen many explicit examples of third or higher order syntax.
In first and second order logic, as far as I understand, the only complexity of the signature of functions and relations is the arity; just how many arguments it takes. But it appears to me that the signature of higher order functions and relations is much more complicated, since higher order functions can take as arguments and have a domain more than just the first order terms.
I've heard higher order logic is similar to type theory, in that higher order terms are essentially different types, and higher order logic can be represented as many sorted first order logic. Can someone explain how higher order syntax is supposed to work? Or point me to a reference for formal syntax (or syntaxes?) for higher order logics?
Comment: Have a look at the documentation for the HOL4 system, particularly the Logic manual that you can find via http://hol.sourceforge.net/documentation.html
Comment: You should really make your question brief. I doubt you will find many peoples willing to read such a long post. Find a way to condense it.
Comment: Second order logic syntax is already defined in a number of texts... it's higher order syntax that is muddy, particularly how you handle third order terms (second order function and predicate variables) as different types, as a sort of multi-sorted logic that starts to encroach on type theory.
Answer: For syntax and semantics of higher-type classical logic, you can see : Part I : CLASSICAL LOGIC, of

Melvin Fitting, Types, Tableaus, and Gödel's God (2002).
Answer: For higher order logic (as in Church's type theory), a good reference is Andrews "An Introduction to Mathematical Logic and Type Theory: To Truth Through Proof".
The key is that it is based on lambda calculus (as a syntax for anonymous functions). A set is identified with its characteristic function $i \rightarrow o$, a predicate over sets is then of type $(i \rightarrow o) \rightarrow o$ and a predicate over predicates over sets is $((i \rightarrow o) \rightarrow o) \rightarrow o$ and so forth.
Here, then is an example, an axiom of extensionality for such third-order predicates:
$$\forall x:((i \rightarrow o) \rightarrow o) \rightarrow o. p~x = q~x \Rightarrow p = q $$
Function application is just written as juxtaposition here, e.g. $p~x$.


UDP packets iptables (possible DDoS)

Question: Debian 8 -
I've been aplying some rules to avoid UDP flood but i'm not sure if they will work, i have the log from my anti-DDoS and it's a very large attack (about 70gbs)
This are the rules i applied on the OS.
iptables -A INPUT -i eth0 -p udp --sport 123 -m limit --limit 1/s --limit-burst 1000 -j ACCEPT
iptables -A INPUT -i eth0 -p udp -m limit --limit 1/s --limit-burst 1000 -j ACCEPT

Anti-DDoS Log (There are like 200-300 ips more with same packets/length)
2019-01-21 02:01:21 UTC IP 220.127.116.11:123 > myhost:3866 UDP, length 1835036, packets 4096
2019-01-21 02:01:21 UTC IP 188.8.131.52:123 > myhost:59733 UDP, length 1835036, packets 4096
2019-01-21 02:01:21 UTC IP 18.104.22.168:123 > myhost:56048 UDP, length 1835036, packets 4096
2019-01-21 02:01:21 UTC IP 22.214.171.124:123 > myhost:59733 UDP, length 1835036, packets 4096
2019-01-21 02:01:21 UTC IP 184.108.40.206:123 > myhost:3866 UDP, length 1835036, packets 4096
2019-01-21 02:01:21 UTC IP 18.104.22.168:123 > myhost:59733 UDP, length 1835036, packets 4096
2019-01-21 02:01:21 UTC IP 188.8.131.52:123 > myhost:21180 UDP, length 1835036, packets 4096
2019-01-21 02:01:21 UTC IP 126.96.36.199:123 > myhost:59733 UDP, length 1835036, packets 4096

Any recommendation to avoid/block  this expecific UDP Flood attack?
I also blocked all the ports except the ones i'm using it but still the attack can go through.
Answer: When you block the UDP packets in the Netfilter filter table, the packets still trigger connection tracking entry creation in the box.
This causes extra resource consumption on the server.
In order to avoid connection tracking entry creation, you need to use the raw table to filter your packets.
iptables -t raw -A PREROUTING -i eth0 -p udp --sport 123 -m limit --limit 1/s --limit-burst 1000 -j ACCEPT
iptables -t raw -A PREROUTING -i eth0 -p udp -m limit --limit 1/s --limit-burst 1000 -j ACCEPT

However, this only helps if your server's processing capacity is the bottleneck.
If the DDoS fills your server's network connection capacity, there is nothing you can do on the actual server to protect yourself from the flood.
This is because the upstream router still sends all those packets to your server via the connection, capping the capacity of the link.
In this case, the only solution is to consult your upstream network provider for help in mitigating the DDoS.
Answer: You should always try to move your rules to higher chains to maximize the performance. For this specific purpose you can drop the packets before they get into connection tracking in raw table and PREROUTING chain. INPUT doesn't have any raw chain.
Comment: No, the accepted answer says: -t raw -A INPUT but there is no such a thing in iptables. The correct one is: iptables -t raw -A PREROUTING -i eth0 -p udp -m limit --limit 1/s --limit-burst 1000 -j ACCEPT     // anything after raw/PREROUTING will be tracked by the kernel in connection tracking.
Comment: right. Indeed it was just changed.

UDP packets iptables (possible DDoS)


how to display Angular innerHTML + content

Question: i need to display inner html plus content between div.
i need one message in innerHTML i.e notification.message and content as button between tag.button should be same for all dynamic message.which is close button.instead of repeating close button i need to change message dynamically and keep close button as it is.
please helpe me to do so...
i want to convert

<button>
 to

message <button>X</button>

when i am trying to conver below code i am not getting button close only content is getting rendered.
<ng-container *ngFor="let notification of src.notifications">

    <button class="close" (click)="src.destroy(notification)" data-e2e="notifier-close">

      </button>

  </ng-container>

Answer: If i am correct you want to render/show both your messege and button inside div. then
You can use interpolation here instead of innerHtml if you dont have any HTML code in notification.message. Please correct if i understand your query wrong.
<ng-container *ngFor="let notification of src.notifications">

    {{notification.message}}
    <button class="close" (click)="src.destroy(notification)" data-e2e="notifier-close">

      </button>

  </ng-container>

Answer: I don't think this is possible, at least not that i am aware of. Why don't you just use a span?
<ng-container *ngFor="let notification of src.notifications">

    <button class="close" (click)="src.destroy(notification)" data-e2e="notifier-close">

      </button>

  </ng-container>


ASP .NET MVC e JavaScript - Abrir modal com ID do objeto selecionado em uma lista

Question: PERGUNTA INICIAL
Estou trabalhando em um projeto ASP .NET MVC com bootstrap e preciso abrir um modal para edição e exclusão de registros de uma listagem.
A ideia é não deixar os botões ao lado de cada linha (como colunas da tabela), mas sim selecionar uma linha e depois clicar na opção Editar ou Excluir.
Layout:

Minha tabela na View está da seguinte forma:

Grau de Curso

                                Id
                                Nome
                                Ativo

                            @foreach (var item in Model)
                            {

                                    @item.GrauId
                                    @item.Nome
                                    @item.Ativo

                            }

                        <button type="submit" name="novo" id="novo" class="btn btn-w-m btn-primary" data-toggle="modal" data-target="#modal">Novo</button>
                        <button type="submit" name="editar" id="editar" class="btn btn-w-m btn-warning" data-toggle="#modal">Editar</button>
                        <button type="submit" name="excluir" id="excluir" class="btn btn-w-m btn-danger" data-toggle="modal">Excluir</button>

Ao clicar no botão Novo, consigo abrir normalmente o Modal. Segue código do Modal.

    @using (Html.BeginForm("InserirGrau", "Curso", FormMethod.Get))
    {

Cadastrar Grau de Curso

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

                            @Html.Label("Nome: ", new { @class = "col-lg-2 control-label", @for = "inputNome" })

                                @Html.TextBox("txtNome", null, new { @class = "form-control", @id = "inputNome", @autofocus = "" })

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                <button type="submit" id="salvar" name="salvar" class="btn btn-primary">Salvar</button>

    }

Para selecionar a linha na table e muda-la de cor estou usando o seguinte script:
            $('#myTable').on('click', '.clickable-row', function (event) {
            if ($(this).hasClass('active')) {
                $(this).removeClass('active');
            } else {
                $(this).addClass('active').siblings().removeClass('active');
            }
        });

Minhas dúvidas são as seguintes:
1) Como obter e repassar ao Script o ID do objeto selecionado?
2) Após obter este ID, como abrir o modal pelo botão Editar ou Excluir repassando os dados do Objeto.
Agradeço muito a atenção.
Arthur

COMPLEMENTO
Dúvida a partir da resposta do colega AL_Mauricio:

Criei um botão Detalhe na view Index para executar o script que abre o modal com os detalhes do objeto.
Coloquei o data-val="@item.GrauId" na table da view Index.
Criei uma Action no Controller chamada Detalhes que recebe o ID passado pelo Script e busca no Banco de dados o objeto, devolvendo para view Detalhes o objeto localizado.
Criei uma view chamada Detalhes sem layout, apenas com parte do Modal a ser exibido, que exibe os dados recebidos do objeto enviado pela Action.

O botão Detalhe está abrindo o modal, porém está passando o ID vazio para o Controller.
Aparentemente é um erro no meu Script, que não está pegando o id do data-val.
$('#myTable').on('click', '.clickable-row', function (event) {
        if ($(this).hasClass('active')) {
            $(this).removeClass('active');
        } else {
            $(this).addClass('active').siblings().removeClass('active');
        }

        $(".detalhe").click(function Detalhes() {
            var id = $('.clickable-row .active').attr('data-val');
            $("#modal").load("Detalhes?id=" + id, function () {
                $("#modal").modal();
            })
        });

    });

SOLUÇÃO
Após as respostas dos colegas AL_Mauricio e edCosta e pesquisas no StackOverflow cheguei a seguinte solução do Script para pegar o Id e repassar para a ActionResult.
$('#myTable').on('click', '.clickable-row', function (event) {
        if ($(this).hasClass('active')) {
            $(this).removeClass('active');
        } else {
            $(this).addClass('active').siblings().removeClass('active');
            var id = $(this).data('val');
        }

        $(".detalhe").click(function Detalhes() {
            $("#modal").load("Detalhes?id=" + id, function () {
                $("#modal").modal();
            })
        });
    });

ActionResult:
public ActionResult Detalhes(string id)
    {
        int num = int.Parse(id);

        //Busca do Objeto e retorno para View Detalhes (modal)
    }

Valeu!!
Answer: Você pode colocar um data-val na sua tr com o valor do id do objeto, assim ao clicar no botão você conseguirá pegar o id do elemento e enviar para sua função que exclui ou edita.
Exemplo

                                Id
                                Nome
                                Ativo

                            @foreach (var item in Model)
                            {

                                    @item.GrauId
                                    @item.Nome
                                    @item.Ativo

                            }

Para você pegar o valor depois basta usar o jquery e pegar o atributo data-val
function Excluir(){
var GrauIdSelected =$('.clickable-row .active').attr('data-val');
//faça algo para excluir
}

Comment: Obrigado pela resposta. Atualizei minha pergunta com a solução encontrada.
Answer: Respondendo a parte complementar
Como vc utiliza parâmetros na ActionResult Detalhes (modal), então o certo a se passar seria
$("#modal").load("Detalhes/" + id, function () {
                $("#modal").modal();
})

public ActionResult Detalhes(string ID)
{
  // Resto da logica
}

Comment: Obrigado pela resposta. Atualizei minha pergunta com a solução encontrada.


Mutual Information between multi-dimensional and single dimensional Variables

Question: I would like to estimate MI between two variables X and Y of shape (nXd) and (nX1) respectively. As X is multi-dimensional (dimension = d) and Y is of dimsnension=1, is it a correct approach of the finding MI between each dimension of X against Y and adding each dimension's MI to get final MI?
Sample example:
X = rand[N,d]
Y = rand[N,]

for i=1 to d:
  mi_total += calculate_MI( X[:,i] , Y) #X[:,i] i_th dimension of X

# X[:,i].shape = (N,1) = Y.shape

Any help and correction is very much appreciated and Thanks in advance :)
Answer: Theoretically speaking, the following quantities are not equal in general, i.e. $$I(\mathbf{X};Y)\neq \sum_{i=1}^dI(X_i;Y)$$ Because, we are dropping out any dependence relationship. For example, if $\mathbf{X}=[X_1,X_1]$ (i.e. $X_2=X_1$), then the mutual information between $\mathbf{X}$ and $Y$ would be $I(X_1;Y)$, not $I(X_1;Y)+I(X_2;Y)=2I(X_1;Y)$. However, if the random variables inside $\mathbf{X}$ are independent, you can sum their individual MIs, as you've done in your code. I couldn't capture yours, but in many coding languages rand is assumed to create independent samples, in which you can really sum MIs.
Comment: Thank you. `X`  in my case is a dataset with `d` dimension, so I reckon it is safe assuming that each dimension is independent of each other and also the reason for using `rand`. I think my doubt is cleared :)


Add JavaScript into a specific content type

Question: I would like to know what is the best way to add a JavaScript file into a specific page basing on the content type. For example, I want to add this:

So far, what I have done is using this way to add into my specific content type. For the  map_page content type, I adde the below two line of code in page--map_page.tpl.php.
drupal_add_js("http://maps.google.com/maps/api/js?sensor=false", 'external');
$scripts = drupal_get_js();

Is there any other better way? if possible can give some example, currently not really understand well...
Answer: I can't comment on the proper Drupal 7 equivalent, but in Drupal 6 sites I do this in a template_preprocess_page.
I will have some logic to make the decision (either based on arg() or page_manager_get_current_page() from panels), and then prepend $vars["scripts"] with the external script.  I prepend so that I don't run into dependency trouble with any local scripts.
I will also sometimes set up a new region called $global_scripts for thinks like Google API and SWFObject that I want to load from a CDN, and this gets printed out before $scripts in the page template.
To be honest, though I normally have all JS on all pages so that the files get cached.
Answer: Since Drupal won't let you redefine template_preprocess_node (because it's already defined in node.module), I added a preprocessor function in my custom module:
function mymodule_preprocess_node(&$vars) {
  if ($vars['type'] == 'my-node-type') {
    drupal_add_js(drupal_get_path('module', 'mymodule') . '/myjs.js');
  }
}

I used preprocess_node rather than preprocess_page because it's easier to get to the node type. If you actually reference a javascript file, then it will be automatically cached (see Parameters section).
Answer: you could also use hook_node_view check for the content type and then add the js in the way you are doing already.
OR
If you have a field which outputs the information which will use the JS use a preprocessor there to add the js, so the js include is dependent on the field displaying the map rather than the content type.
Answer: A simple solution is to just place the add_js:
  drupal_add_js('drupal_get_path('module', 'mymodule') . '/myjs.js');

in the page/node template.php.


Can we approximate the most likely event's probability if we know the distribution's entropy?

Question: Suppose that we know that a distribution $p$ over small $n$ elements has entropy $H(p)=0.01$. I intentionally chose a small number. Is there some kind of inequality or aproximation to the probability $p_i$ for $i = \arg\max_j p_j$?
What I came up with so far is the following inequality:
$H(p) = \sum _j -p_j \log(p_j) \geq -p_i \log(p_i)$. This gives us in principle an inequality for $p_i$, because if we assume that the most likely event has probability larger than $0.5$ (a consequence of the entropy being sufficiently small for a given $n$), then this inequality $H(p) \geq -p_i \log(p_i)$ should give us a bound on $p_i$ in terms of the entropy. I'm not sure how to solve that inequality for $p_i$ though, or if it's even possible. Maybe an approximation would help as well, that works for small entropy.
Is there a bound or approximation on the maximum probability $p_i$ in terms of the entropy, that works for sufficiently small entropy?
Answer: I don't think one can analytically solve this in terms of elementary functions, but using the monotonicity of $z \mapsto -z \ln z$ for $z > 1/e,$ one can numerically invert your relation to get a lower bound on $p_{i}.$ For small $H$, this should be quite close to $1.$
A slightly better approach is to observe that $$ H(X) = \sum p_j \log \frac{1}{p_j} \ge \sum p_j \log \frac{1}{p_i} = \log \frac{1}{p_i},$$ which immediately tells us that $p_i \ge \exp(-H)$. Note that this improves upon inverting $-p\log p = H$ since $-\log p \ge -p\log p$.
We can in fact do better - let $Y = \mathbf{1}\{X = i\}$. Then the data processing inequality tells us that $H(Y) \le H(X)$. But since $Y$ is a binary function, we can (again numerically, but not analytically) invert the entropy to tell us that $p_{i}$ is either smaller than $h_2^{-1}(H(X))$ or bigger than $1- h_2^{-1}(H(X)),$ where $h_2^{-1}$ is the binary entropy inversion function. If we know that $p_{i} > 1/2,$ then this directly gives a lower bound. For small $H$ this should be the tightest possible lower bound, because the random variable could well be supported on just two letters (or have arbitrarily small mass on all but two), in which case $p_i$ has to step back from $1$ enough to at least give enough binary entropy.

Of course, if we're going numerical, then we might as well set up the relevant optimisation program in terms of $H$. Happily, this yields an upper bound upon considering the following convex program \begin{align} p_{\max}(H,n) := &\max p_1 \\ &\textrm{s.t. } \sum_{i = 1}^n  p_i \log p_i = - H, \\ &\phantom{\textrm{s.t. }} \sum_{i = 1}^n p_i = 1,\\ &\phantom{\textrm{s.t. }} \forall i, p_i \ge 0. \end{align}
This has the Lagrangian $$ \mathcal{L} = p_1 + \lambda (\sum p_i \log p_i + H) + \mu(\sum p_i - 1),$$ which yields the first order conditions $$ 1 + \lambda + \lambda \log p_1 + \mu = 0 \\
\forall i \ge 2, \lambda + \lambda \log p_i + \mu = 0,$$ which in turn tells us that the solutions must be of the form $$ (p_1, \pi, \pi, \dots, \pi), \pi = \frac{1-p_1}{n-1},$$ which should make sense - if we want $p_1$ to be big but need to meet an entropy constraint, then the best thing to do is to spread out the remaining mass uniformly on the remainder of the support, to make the relevant conditional entropy as large as possible. In any case, using the above, we may conclude that $p_\max$ must be the largest solution in $[0,1]$ to the equation $$ - p \log p - (1-p) \log \frac{1-p}{n-1} = H \iff h_2(p) + (1-p) \log(n-1) = H.$$
Of course, by definition, we get the upper bound $ p_i \le p_{\max}(H,n).$ I don't quite know how convenient this is, but again, $p_{\max}$ is reasonable to solve for over $[1/2, 1]$ via something like Newton's method or binary search.
As mentioned above, in principle we can also set up a minimisation program (which would minimise $p_1$, but under the extra constraints that $p_1 - p_i \ge 0$ for each $i$), but this should just give the binary entropy inversion solution from above.
Comment: I also wanted to point out that numerically these seem quite good - clearly the bounds will separate as $n$ blows up, and come together as $H$ decreases, but even for the quite large $n = 10^8$ and the modest $H = 0.1$ (in nats), I get the bounds (via Wolfram alpha) $0.979 \le p_i \le 0.996.$ For comparison, $\exp(-0.1) \approx 0.905,$ while the inversion of $-p_i \log p_i = 0.1$ is roughly $0.894$.
Comment: Upon re-reading, this is a bit stream of consciousness. More briefly:  note that we can express the entropy as $H = h_2(p_i) + (1-p_i)H(X|Y = 0),$ for $Y = \mathbf{1}\{X = i\}$. So, $h_2(p_i) \le H \le h_2(p_i) + (1-p_i)\log(n-1) =: g(p_i)$. Now, given $H,n$, $p_i$ must satisfy these relations. If $H \le 1\textrm{ bit},$ then we know that $p_i \ge 1/2$. Both $h_2(p)$ and $g(p)$ are decreasing on $[1/2, 1]$. Thus, the solutions to the equations $h_2(p) = H$ and $g(p) = H$ on $[1/2,1]$ respectively give (tight) lower and upper bounds for $p_i$, and can be found by binary search.
Comment: I like the lower bound $p^*\geq e^{-H}$, which btw also gives $p^*\geq 1-H$. I would love to have a similarly simple upper bound, if it exists. The numerical bounds aren't so useful to me (though I know I didn't say that explicitly in the question). Should I ask for a closed form upper bound in a different question?
Comment: @user56834 I guess so? Equivalently you're asking for elementary upper and lower bounds to the solutions of the two equations that I'm proposing to solve numerically, which does seem like it could be a nice question (that I don't know a good attack for :) ). It's probably worth putting a concrete motivation into it too, which would really help clarify what kind of answer you'd be happy with (e.g. maybe you're looking for some nice bounds that plug into some analysis. Then describing the form of the equations would give a sense of what kind of functions are useful etc).
Answer: Notice that $$H(X) = h(p_j) + (1-p_j) H(X \backslash x_j)  \tag 1$$
where $h$ is binary entropy function and $H(X \backslash x_j)$ is the entropy of the remaining values (or equivalenty, $H(X \mid X \ne x_j)$  (proof).
This gives a lower and upper bound of the entropy in terms of $p_j$:
$$ h(p_j) \le H(X) \le  h(p_j) + (1 - p_j) \log(n-1) \tag 2 $$
where $n=|{\cal X}|$ is the cardinality of the variable $X$ support. (Of course, the logarithm should be in base $2$ if the entropy is expressed in bits).

The graph displays this lower bound  (eq $(2)$, in green) and the upper bound for $n=3$ (blue) and $n=9$ (red), for $p_j \to 1$.  The entropy, in the vertical axis, in bits.
The permisible pairs $(H, p_j)$ lie between the green and red/blue lines.
Hence $(2)$ give lower and upper bounds for $p_j$, which should be computed numerically. See also here.
A semiempirical approximation for the lower bound, for the range $0.01 \le H < 0.4$ :
$$ p_j \approx 1- \frac{a H}{b - \log(H)}$$
where  $a=0.73$, $b = 2.3$.
Comment: Is this a lower or upper bound on the max probability?
Comment: It's an upper bound. I clarified and added the lower bound.
Comment: but this is an upper and lower bound on the entropy. I am assuming that we already know the entropy, and we want a bound on the maximum probability (preferably lower and upper). Also, the equation you gave seems hard to invert for $p^{max}$ btw.
Comment: @user56834 Eq $(2)$ gives a bounds for $H$ in terms of $p_j$, but (as the graph shows) it translates into bounds for $p_j$ in terms of $H$, only that there is not a a closed form formula. It should be evaluated numerically or by approximations. In the final paragraph I give such an approximation.
Comment: I don't like the fact that these bounds aren't closed form, though I know that I didn't explicitly ask for that in the question. Is it possible to formulate (weaker) closed form lower and upper bounds for the maximum probability $p^*$ based on this?
Comment: > I don't like the fact that these bounds aren't closed form
Well, try to overcome that dislike. "Closed form" is a fuzzy term (and probably less important than you think). $sin(x)=y$ has no "closed form" solution for $x$ until you invent the arcsin function. Same for $x^x=y$ until you invent the Lambert-W function. And so on.
Comment: the reaaon I want it to be closed form is so that I can very eaaily calculate a rough upper bound immediately in my head. $p\geq 1-H$ is very good for this purpose
Comment: I have already given an approximate explicit "closed form" bound in the last paragraph


Como saber se a solução foi modificada?

Question: Gostaria de fazer um código, que ao ser executado, saberia se a solução foi alterada e qual projeto da mesma sofreu alteração, mas não sei se existe um método para tomar como base. Então gostaria da ajuda de vocês.
Comment: Você está fazendo um add-in? Ou seria uma aplicação que roda paralelamente ao Visual Studio?
Comment: Uma aplicação que roda paralelamente ao VS.
Answer: Existe uma classe no .Net que é usada para monitorar alterações no sistema de arquivos:

FileSystemWatcher

Com ela você pode fazer o seguinte código para ser notificado sempre que um arquivo mudar:
<code>// Criar uma instância do FileSystemWatcher e configurá-la.
var watcher = new FileSystemWatcher(
    "C:\\MinhaSolucao\\", // caminho raiz da solução a ser monitorada
    "*.csproj"            // vamos monitorar os arquivos `csproj` dentro do caminho acima
    );

// Adicionando os eventos para notificação de alterações.
watcher.Changed += new FileSystemEventHandler(WatcherEvent);
watcher.Created += new FileSystemEventHandler(WatcherEvent);
watcher.Deleted += new FileSystemEventHandler(WatcherEvent);
watcher.Renamed += new RenamedEventHandler(WatcherEvent);

// Iniciar o monitoramento.
watcher.EnableRaisingEvents = true;
</code>
Código que recebe as notificações:
<code>static void WatcherEvent(object sender, FileSystemEventArgs e)
{
    // alterações nos arquivos ocorreram!
    // verificar o argumento `e` para saber o que ocorreu.
}
</code>
Comment: Beleza... se precisar de ajuda com a classe, me fala que adiciono mais informações sobre como usar.
Comment: Muito obrigado, caiu como uma luva.

Como saber se a solução foi modificada?


Linq selecting on string value "not equals" ignores DB nulls

Question: Here's some oddness. A data table, accessed through Entity Framework, has a field with is a nullable string/varchar.
When you attempt to select things using Linq to get items not equal to a given value, i.e.
var thingsToRun = rep.Things.Where(t => t.Status != "Running");

What you get back is a list of all the Things that have a Status other than "Running" except those that have a null status.
In other words if you had three things with a Status of "Running", "NotRunning" and NULL, the above query would only return one item, with a status of "NotRunning".
I presume this is something to do with a mismatch between C# null and DB null. But it seems odd. Is there an easy way round it?
EDIT: Thanks for answers. Still curious about why this happens?
Comment: Do you want to omit nulls or do you want to get them? In general this has nothing to do with C# or LINQ but with your database. Normally databases never return null records if you don't search for them explicitly: `WHERE Status IS NULL` or `Status IS NOT NULL`. So a null value is neither `=` nor `!=`, it is simply not defined.
Answer: include null in your query
var thingsToRun = rep.Things.Where(t => t.Status == null || t.Status != "Running");

Answer: You could test explicitly for null:
var thingsToRun
    = rep.Things.Where(t => t.Status == null || t.Status != "Running");

As for why, Tim provided a good answer in his comments. I'll put something here for the sake of a more complete answer. The value null in database land is typically not equal to anything and not "not equal" to anything. It's incomparable  to any value, one way or the other.
I can't say this is the way every database treats null, but typically if you had a database with three records that contained, to use your example, "Running", "NotRunning", and null, then
... WHERE some_column = 'RUNNING'   <- returns one record
... WHERE some_column <> 'RUNNING'  <- returns one record
... WHERE some_column IS NULL       <- returns one record

If you're able to place a breakpoint on the LINQ statement and see if the generated SQL is visible anywhere in the object, you might be able to tell exactly what's going on. I'd guess you'll see == null being translated to IS NULL.
Answer: Because null != Running is undefined : neither true nor false.
You might want to check out this thread.


Background dinamico com CSS? Como fazer?

Question: eu tenho uma dúvida, é possível a troca de background conforme uma condição?
Exemplo:

function A() {
  if (meuArray.length === 7) {
    eu quero background verde
  } else {
    background azul
  }
}

A principio eu estou fazendo um jogo de cartas chamado Black Jack ou 21 no Brasil, e até agora não achei uma forma viável de por background ou um CSS no array que contém os valores de cada carta.
Alguem teria uma dica ou de como fazer? Obrigado
Comment: Sim. Utilize `document.querySelector("#your-element").style.background = "#F00"` ou `document.querySelector("#your-element").style.setProperty("background", "url('your-image.png')")`
Answer: Boa tarde você pode usar os números da cartas e montar um array com elas e quando for usa-las apenas chamar a posição do array.
exemplo:
var cartas = [];
cartas[0] = '#f333dd';
cartas[1] = '#ffffff';
cartas[2] = '#000000';
cartas[3] = '#f23f5d';

....
$(element).attr('style','background-color:' + cartas[2] + '');

Espero que esse código te ajude.