Analysis of Kullback-Leibler divergence

Question: Let us consider the following two probability distributions
<code>P       Q
0.01    0.002
0.02    0.004
0.03    0.006
0.04    0.008
0.05    0.01
0.06    0.012
0.07    0.014
0.08    0.016
0.64    0.928
</code>
I have have calculated Kullback-Leibler divergence which is equal $0.492820258$, I want to know in general what does this number shows me? Generally, Kullback-Leibler divergence shows me how far is one probability distribution from another, right? It is similar to entropy terminology, but in terms of numbers, what does it mean? If I have a result of result of 0.49, can I say that approximately  one distribution is far from  another by 50%?
Comment: See the discussion [here](http://stats.stackexchange.com/questions/6814/kullback-leibler-divergence-interpretation) which may be some help.
Comment: A similar question:  https://stats.stackexchange.com/questions/188903/intuition-on-the-kullback-leibler-kl-divergence/189758#189758
Answer: The Kullback-Leibler Divergence is not a metric proper, since it is not symmetric and also, it does not satisfy the triangle inequality.  So the "roles" played by the two distributions are different, and it is important to distribute these roles according to the real-world phenomenon under study.
When we write (the OP has calculated the expression using base-2 logarithms)
$$\mathbb K\left(P||Q\right) = \sum_{i}\log_2 (p_i/q_i)p_i $$
we consider the $P$ distribution to be the "target distribution" (usually considered to be the true distribution), which we approximate by using the $Q$ distribution.
Now,
$$\sum_{i}\log_2 (p_i/q_i)p_i = \sum_{i}\log_2 (p_i)p_i-\sum_{i}\log_2 (q_i)p_i = -H(P) - E_P(\ln(Q))$$
where $H(P)$ is the Shannon entropy of distribution $P$ and $-E_P(\ln(Q))$ is called the "cross-entropy of $P$ and $Q$" -also non-symmetric.
Writing
$$\mathbb K\left(P||Q\right) = H(P,Q) - H(P)$$
(here too, the order in which we write the distributions in the expression of the cross-entropy matters, since it too is not symmetric), permits us to see that KL-Divergence reflects an increase in entropy over the unavoidable entropy of distribution $P$.
So, no, KL-divergence is better not to be interpreted as a "distance measure" between distributions, but rather as a measure of entropy increase due to the use of an approximation to the true distribution rather than the true distribution itself.
So we are in Information Theory land. To hear it from the masters (Cover & Thomas) "

...if we knew the true distribution $P$ of the random variable, we
  could construct a code with average description length $H(P)$. If,
  instead, we used the code for a distribution $Q$, we would need $H(P)
 + \mathbb K (P||Q)$ bits on the average to describe the random variable.

The same wise people say

...it is not a true distance between distributions since it is not
  symmetric and does not satisfy the triangle inequality.  Nonetheless,
  it is often useful to think of relative entropy as a "distance"
  between distributions.

But this latter approach is useful mainly when one attempts to minimize KL-divergence in order to optimize some estimation procedure.  For the interpretation of its numerical value per se, it is not useful, and one should prefer the "entropy increase" approach.
For the specific distributions of the question (always using base-2 logarithms)
$$ \mathbb K\left(P||Q\right) = 0.49282,\;\;\;\; H(P) = 1.9486$$
In other words, you need 25% more bits to describe the situation if you are going to use $Q$ while the true distribution is $P$. This means longer code lines, more time to write them, more memory, more time to read them, higher probability of mistakes etc... it is no accident that Cover & Thomas say that KL-Divergence (or "relative entropy") "measures the inefficiency caused by the approximation."
Comment: Extremely useful and informative answer.
Answer: Consider an information source with distribution $P$ that is encoded using the ideal code for an information source with distribution $Q$.
The extra encoding cost above the minimum encoding cost that would have been attained by using the ideal code for $P$ is the KL divergence.
Answer: KL Divergence measures the information loss required to represent a symbol from P using symbols from Q. If you got a value of 0.49 that means that on average you can encode two symbols from P with the two corresponding symbols from Q plus one bit of extra information.

Analysis of Kullback-Leibler divergence


Where do I update sshd to read from another config file for second instance of ssh?

Question: I followed the following steps in order to get a second instance of sshd running on my server: http://fixunix.com/ssh/364505-running-multiple-sshd-instances-one-server.html
The only problem is, I'm not sure where exactly I need to modify to get my new instance of sshd to read from /etc/ssh/newsshd_config. It continues to read from /etc/ssh/sshd_config which is obviously not my intention. my intention is to run with a brand new set of configs.
this is on a rhel box.
Answer: Make a copy of your sshd init script and append the -f option to specify the new sshd_config.


get total sum of counts of repeating key in nested dictionary

Question: basically i have dataframe like this
   col1           col2         col3    col4
1. 554862122    55110385224      PR    26
2. 5242700637   55110385236      CO    246
3. 560297164    55110385250      CO    109
4. 5651138615   55110385266      PR    26
5. 5242699687   55110385289      CO    109

i convert it to dict like this
{554862122: {55110385224:  {'PR 26': 2})},
5242699687: {55110385289:  {'CO 109': 6}),
554862121: {55110385224:  {'PR 26': 3})}"

but now i want this but without loops
{'PR 26':[5,[554862122,55110385224],[554862121,55110385224]],
'CO 109':[6,[5242699687,55110385289]]}

Comment: Is the target always at nesting level 2? What did you try yourself? What result do you want exactly? A dictionary? A print output? I downvoted because the question is unclear and low effort.
Comment: OK, now that you changed the desired output, where is the single `5` coming from? (edit: ah, I got it, it's the sum of 2 and 3)
Comment: Show us what have you tried yet.
Comment: i have done this with loops but i want without loops
Comment: @timegb if you got my problem have you got any solution
Answer: You can use nested loops to iterate over the sub-dicts and use dict.setdefault to initialize the sub-lists in your output dict:
d = {
    554862122: {55110385224:  {'PR 26': 2}},
    5242699687: {55110385289:  {'CO 109': 6}},
    554862121: {55110385224:  {'PR 26': 3}}
}
o = {}
for k, v in d.items():
    for l, w in v.items():
        for m, x in w.items():
            o[m][0] = o.setdefault(m, [0])[0] + x
            o[m].append([k, l])
print(o)

This outputs:
{'PR 26': [5, [554862122, 55110385224], [554862121, 55110385224]], 'CO 109': [6, [5242699687, 55110385289]]}

Comment: can i do this without loop
Comment: No. There is no way this can be done without loops because of how your dicts are nested. And why would you not want a loop?
Comment: because i have a lot of data and i take lot of time
Comment: You should use a better data structure for your input to begin with then. As it is, you simply have to iterate over all the dict items and the sub-dict items to get to the inner values.
Comment: If all your sub-dicts have only one item, you should flatten them all first. Make it a list of tuples, e.g. `[(554862122, 55110385224, 'PR 26', 2), (5242699687, 55110385289, 'CO 109', 6), ...]`.


Exibir tabela dinâmica

Question: Estou criando uma tabela dinâmica que a partir dos valores de um objeto, porém na hora de gerar a tabela ela nao esta aparece. Segue o código:
<!DOCTYPE html>

--------------------------------------------------------------------------------
var dados =[{
    "N1":" CONTROLE DE GESTÃO ORCAMENTARIA CONCESSÕES - INDICADORES / 2017 (MILHARES R$)",
    "N2":" ",
    "N3":"A1 - ATIVIDADE CORE",
    "ANO_ANTERIOR":1214363,
    "ANO_ATUAL":1335800,
    "VAR":121437,
    "JAN":2388000,
    "FEV":2268000,
    "MAR":1728000,
    "ABR":2424000,
    "MAI":1464000,
    "JUN":2124000,
    "JUL":1212000,
    "AGO":1356000,
    "SET":2400000,
    "OUT":1800000,
    "NOV":0,
    "DEZ":0,
    "TOTAL":456291000
}]

function createTable(obj){
    // Criar a table
    $('#tbldados').append('

'); // Adiciona a tabela ao body
    var table = $('#tbldados').children('table'); // Seleciona a tabela

    // Criar o head da table
    var thead =  "
";
    for (coluna in obj[0]) {
        thead += "" + coluna + "	";
    }
    thead += "
";
    $("
").show();

    //Criar o body da table
    var tbody = "
";
    obj.forEach(function(linha,) {
        for (item in linha) {
            tbody += "" + linha[item] + "	";
        }
        tbody += "
";
    })

    // Adiciona a tabela completa ao body
}
$(document).ready(function(){
    createTable(dados);
});

Comment: Olá, não entendi muito bem o seu problema, tente explicar um pouco melhor
Comment: opa blz paulo eo seguinte eu tenho os "dados" e desejo criar uma tabela dinamica com esses dados porem nao esta exibindo a minha tabela no html gostaria de saber oque esta faltando botei $(document).ready e tudo porem nao esta exibindo a tabela
Comment: O cabeçalho aparece? O tbody você monta mas não chega a adocionar à tabela.
Comment: nao chega a aparecer nada ,eu dou append
Answer: Seu código possui erros e ausência de código para formar a tabela. E deve usar .append após completar os laços. Após os laços, use o .append concatenando o resultados dos laços para inserir o resultado na div.
Um dos erros é:
$("
").show();

O seletor
 é inválido. Deveria ser $("table").show();. Mas o .show() também não tem função alguma.
Veja o código corrigido:

var dados =[{
    "N1":" CONTROLE DE GESTÃO ORCAMENTARIA CONCESSÕES - INDICADORES / 2017 (MILHARES R$)",
    "N2":" ",
    "N3":"A1 - ATIVIDADE CORE",
    "ANO_ANTERIOR":1214363,
    "ANO_ATUAL":1335800,
    "VAR":121437,
    "JAN":2388000,
    "FEV":2268000,
    "MAR":1728000,
    "ABR":2424000,
    "MAI":1464000,
    "JUN":2124000,
    "JUL":1212000,
    "AGO":1356000,
    "SET":2400000,
    "OUT":1800000,
    "NOV":0,
    "DEZ":0,
    "TOTAL":456291000
}];

function createTable(obj){
    // Criar a table
    $('#tbldados').append('

'); // Adiciona a tabela ao body
    var table = $('#tbldados').children('table'); // Seleciona a tabela

    // Criar o head da table
    var thead =  "
";
    for (coluna in obj[0]) {
        thead += "" + coluna + "	";
    }
    thead += "
";

    //Criar o body da table
    var tbody = "
";
    obj.forEach(function(linha,) {
        for (item in linha) {
            tbody += "" + linha[item] + "	";
        }
        tbody += "
";
    })

    // Adiciona a tabela completa ao body
    $("table").append(thead+tbody);
}
$(document).ready(function(){
    createTable(dados);
});

Comment: obrigado, eu so estava meio nervoso na sexta porem quando cheguei em casa e mexi acabei conseguindo

Exibir tabela dinâmica


How to hide a flat pick in the right hand when switching to finger picking, Warren Haynes style

Question: Watch any Warren Haynes video on YouTube and you'll notice that he often likes to mix it up and play solos with a pick but mid-way switch to using his fingers.
http://www.youtube.com/watch?v=EMxG90vP-aU
Joe Bonamassa is another guy I see doing this a fair bit. A nice technique if you can get it to work!
Where do people think he is most likely holding the pick in the right hand when he has switched to finger picking?
I've tried putting the pick between the 4th and 3rd fingers, or using the pinky to hold it against my palm. I just can't find anything that feels comfortable, but still allows the other fingers to move freely in order to fingerpick, AND can easily transition the pick back to the fingers for playing.
Does anyone have any insights or tips on this technique?
Also, when he has switched to finger picking, it looks like the way he would use the right hand when playing slide guitar. I.e. mainly thumb and index finger.
Comment: I wear glasses, and wear my hair very short. I simply tuck it above my ear between my glasses and my head.
Answer: I know that Brian Setzer of the Stray Cats does this a lot too. He explains his approach ina video here; he forfeits the index finger, and uses it to hold the pick, curling it against his palm:

He then uses his thumb and remaining fingers for fingerstyle. The article says:

You may find it feels awkward playing fingerstlye without your first finger, but it shouldn't take much practice before this feel completely natural. If you really can't get used to it, then try tucking the pick under whichever finger you find easiest.

I can also recommend this DVD, where you can see him do it in some detail.
Comment: Thanks, very helpful. As I mentioned in my own answer, this is also how Joe Bonamassa does it
Comment: +1. when playing bass, I do this but use my middle finger. this frees up the index for plucking when slapping. it's the simplest way I've found other than just dropping it
Answer: Since the 4th finger isn't usually used for picking, seems logical, that use can hold the pick between 3rd and 4th fingers, but this will require some tough training, because you will have to have some extra tension in your right hand witch is not good - the right hand must be relaxed as possible.
for me, I use two "techniques", if you can call the that:
1
Out a pick in my teeth. Not very hygienic, but very easy and it works (also some girls find it quite attractive :)
2
Use a pick holder glued to the body of a guitar - makes really easy to get rid of a pick fast.
Comment: RE point 1, it is very easy to inhale a guitar pick. Less easy to get it back out!
Comment: Instead of putting it between the teeth, I prefer to just press it on my forehead. It holds there pretty well all by itself! :-)
Comment: Or use the technique Cheap Trick's guitarist Rick Nielsen uses. Play for about a minute with a pick then throw it into the audience, run over and grab another from the mike stand, and play on. But he's making fun of rock and rollers who do similar things from what he said in an old Guitar Player interview.
Comment: Some people use their ring + little fingers, put them together, but slide the pick between them. It takes very little pressure to hold it there, and leaves the thumb + index + middle finger for picking.
Comment: @the Tin Man - I've used the toss-the-pick many times, generally for one particular song that had a fingerstyle ending. It works well with a brightly-colored pick.
Answer:
I picked this up before I could do anything really well. I hold the pick between the joints of my picking hand ring finger. This leaves the thumb, index and middle finger free to fingerpick.
Comment: This is exactly what I do. It stays there without much thought and gives access to all the fingers :)
Answer: I tend to

tuck it into the strings beyond the
nut
pop it between my teeth
tuck it between my 2nd and 3rd fingers (I use p and a more than i and m)

Need to get some Metaltech branded picks so I can lob them into the audience though - I should have thought of that before!
Comment: I assume you use a locking system like Floyd Rose, or else tucking into the string would affect the tuning.
Comment: I do this with all my guitars. Some have locking nuts. Most don't. I have very few problems with guitars going out of tune.
Answer: I simply have an oval silver ring in my ring finger. I tuck it there and it sticks well, I sacrifice no fingers, and can go crazy with fingerpicking.
Answer: Well, I'm actually going to answer my own question.
I can do that, because I recently saw both Warren Haynes and Joe Bonamassa play. I was close enough that I could actually see for myself how they do it.
So even though I like this question to be quite general (in order to be helpful to others), to be honest, I actually just wanted to know how Warren Haynes does this ;)
And I can say that Warren actually puts the pick between his index and middle fingers, high up, so he can still move all of his fingers to some degree.
In that way, he is able to finger-pick with all of his fingers, and not sacrificing any particular finger. The trick seems to be though that you can't go crazy with the finger picking, or the pick is going to come loose.
As well, you have to really practice that transition of moving the pick from your normal grip, to holding it between your fingers, and vice versa. Warren does it smoothly, and without effort. He's obviously been doing this for decades. I think it's going to take me some time to get even close, but I'll keep trying.
The other benefit to Warren's technique, is that as a very good slide guitarist, Warren naturally has very well developed finger-picking technique with the thumb, index and middle fingers. (Warren's style of slide involves plucking and muting the strings with those fingers). So of course, it then makes sense to keep those fingers free when finger-picking with the plectrum tucked away, to make the most of that well-developed picking technique. I was thinking that when I originally wrote my question, and I can see that it is true.
The technique Bill Cheatham describes for Brian Setzer is actually the same technique Joe Bonamassa uses.
I'm going to concentrate on Warren's technique however, because it is closer to what I'm hoping to achieve with my playing.
Answer: I do this a lot as I learnt electric guitar without a pick at first, then learnt to use a pick later. I end up alternating between the two a lot.
I have a few methods that I use :
1) Stick pick between teeth/lips - works on but there's a yuck factor (as others have mentioned)  and it takes too long to do. Need it out of the way instantly really.
2) I play a Strat. I often put the pick between then top of the scratch plate and the body. I've enven loosened the scratch plate a little to accommodate for this. this is my preferred method as it's very fast and easy to get the pick back.
3) Tuck between 2nd and 3rd finger (assuming forefinger is 1st) quite high up near the knuckle. That means it can sit there while I noodle about and doesn't fall out as my fingers move. This is fine but not if I want to span several frets withg right hand (which I sometimes do).
I see you've answered the question anyway (thanks, really good info) but thought I'd mention some other techniques.
Answer: You can basically make any finger work. Really depends on what feels good to you and which fingers you primarily use while playing.
I go over a few different ways of doing it in this video I did.


How to get rid off the empty values (0 values) using table() function in R

Question: I have a simple question. I want to do a frequency table with 3 variables of my original table. If I do
as.data.frame(table(df$var1,df$var2,df$var3))

as it provides every possible combination of the 3 variables -and I have many values for each variable-, I get the error: "attempt to make a table with >= 2^31 elements".
The problem is that many of the combinations are actually empty. In other words, there is a 0 frequency for a lot of those possible combinations, and so I was wondering how to make R to keep into account only the non-null frequencies (so that the function table() works with my 3 variables without giving the error message.
Any idea?
Thank you very much for reading.
A very simplified table (not my original one -as I have many values so that the Cartesian product of the three when running "as.data.frame(table())¨ goes beyond de 2^31 elements- could be:
var1           var2           var3   var4  var5
0               a1            1234     a     1
1               a2            1234     b     2
1               a2            1235     c     2
1               a2            1235     a     7
1               a1            1235     d     3

And what I want is the frequencies of the first 3 variables together through the code:
as.data.frame(table(df$var1,df$var2,df$var3))

This is something I was trying:
subset(table(df$var1,df$var2,df$var3),table(df$var1,df$var2,df$var3)$Freq!='0')

Or
droplevels(table(df$var1,df$var2,df$var3))

with no luck.
In the case outlined for my example, the code as.data.frame(table(df$var1,df$var2,df$var3)) provides a table like this -as you know, creating an extra variable "Freq" that gives the time each combination of the 3 variables in the line occurs-:
var1           var2           var3   Freq
0               a1            1234     1
0               a1            1235     0
0               a2            1234     0
0               a2            1235     0
1               a1            1234     0
1               a1            1235     1
1               a2            1234     1
1               a2            1235     1

But, as I say, as there are many lines with frequency 0, making R not to take them into account when running the function table(), may simplify remarkably the calculations with way less elements than 2^31, so that an outcome may be provided without any error message. So, if available, after applying this workaround, the outcome I would expect is something like this (where all the lines with Freq=0 are not calculated when running table()):
var1           var2           var3    Freq
0               a1            1234     1
1               a1            1235     1
1               a2            1234     1
1               a2            1235     1

Comment: Hard to tell without a reproducible example, but perhaps try: `library(dplyr); inowner %>% count(relhh, identificatiehuis, IDNR)`
Comment: Thank you very much for your time, @JasonAizkalns. I think I made it a bit more clear after editing. I thought of not giving a reproducible example as the only way to get the error is by way of a real example with many rows (that cannot fit in this frame for discussion), and I thought what the code -as.data.frame(table())- does was generally speaking, well known. Thank you again.
Comment: Actually, only applying table() to two of the variables gives an outcome with 424 million combinations. Imagine adding the extra third variable
Answer: Well, I think I found the solution. It´s basically:
a <- summarise(group_by(df,var1,var2,var3),count =n())


Use Rules to email all members of a role that is specified within a taxonomy field attached to a node

Question: I tried to concisely explain what I am looking to accomplish in the subject, but will go into more details here. I think I'm really close but my Google-fu is failing me.
My question: How can I use the role reference field coming through field_responsible_team in a dynamic fashion opposed to the static fashion I've solved for currently?
Current Setup:
Content Type: Question
-- Taxonomy: Category (attached to Question content type)
---- Taxonomy Field: Responsible Team (user role) / (attached to Category taxonomy)
Example Question node:
Node Type: Question
Category: Training
Responsible Team: Learning & Development
    { "rules_XYZ" : {
    "LABEL" : "XYZ",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--question" : { "bundle" : "question" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_category" } },
      { "AND" : [] },
      { "entity_has_field" : {
          "entity" : [ "node:field-category" ],
          "field" : "field_responsible_team"
        }
      }
    ],
    "DO" : [
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "4" : "4" } },
          "subject" : "XYZ [node:workbench-access-sections]",
          "message" : "XYZ"
        }
      }
    ]
  }
}

I got excited when this worked, but realized I had limited this to just users of role 4.
Preferred solution: Dynamically pull in the role from the new node created and use that for the role selection in the "mail_to_users_of_role" function. I would've thought I could've used the "node:field-category:field-responsible-team" data selector, but it's telling me that "The data type of the configured argument does not match the parameter's roles requirement." I'm using the Role Reference module.
Secondary solution (solved - see below): Create one rule for each of the roles and specify the categories within the rule set (not ideal).
{ "rules_XYZ" : {
"LABEL" : "XYZ",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_insert--question" : { "bundle" : "question" } },
"IF" : [
  { "entity_has_field" : {
      "entity" : [ "node:field-category" ],
      "field" : "field_responsible_team"
    }
  },
  { "AND" : [] },
  { "data_is" : {
      "data" : [ "node:field-category:field-responsible-team" ],
      "value" : "4"
    }
  }
],
"DO" : [
  { "mail_to_users_of_role" : {
      "roles" : { "value" : { "4" : "4" } },
      "subject" : "XYZ",
      "message" : "XYZ"
    }
   }
  ]
 }
}

Comment: I reopened this, and think I understand it, but this it could use a little more editing to make it useful for future readers.
Comment: @mpdonadio merci for reopen! Glad to see I am not the only one anymore who understands this question. BTW, Have you seen the comment from OPer from last Wed at 10:45 below my answer (now moved to chat)? It confirms my answer did work. So maybe first read my answer to get more details about the question? PS: the question title is a perfect resume about the question I think.
Answer: Preface: there is no need for the "AND" in your Rules Conditions (that's the default). Moreover, that "AND" applies to all Rules Conditions following the "AND" (but you only have 1 Rules Condition that follows it). Therefor, start by simplifying your Rules to get rid of the "AND". Refer to my answer to "How to make an OR statement in rules?" for more details about all this.
What you could do for sure is to rework your 2nd Rule (for role "4"), into a rule that performs a (new) Rules Component. To start, at least perform these changes:

Create a Rules Component which uses a parameter named (say) "Selected term". Use a data type of "Taxonomy term".
In your original Rule:

Replace the Rules Action (to send an eMail) by a Rules Action to just execute the (new) Rules Component. While doing so, pass node:field-category as the value of "Selected term".
Remove the last Rules Condition (with the hardcoded role "4").

The above changes will be a good start, but still it won't be sufficient. The remaining challenge (in the rules Component) will be related to the "Data selector" you need to specify for the Rules Action "Send mail to all users of a role" (= the replacement for your hardcoded "4"). That challenge is because the rules Component parameter "Taxonomy term" is a single value, while for the roles to be emailed you need a list (repeat: list!), as indicated also below the roles label, where it says "Select the roles whose users should receive the mail." (note: "roles", not "role"!).
Too bad, if we don't have a list, we'll massage the single value (Taxonomy term) into a "list". What follows is an example of a Rule and related Rules Component, with which I could make it work in my own setup:
Main rule
Here is my sample rule (in which I'm using 2 Rules Events, just to simplify testing and so that the logic is also triggered when updating content):
{ "rules_notify_users_of_selected_role_about_new_content" : {
    "LABEL" : "Notify users of selected role about new content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_demo_tags" } }
    ],
    "DO" : [
      { "component_rules_do_something_with_selected_term" : { "selected_term" : [ "node:field-demo-tags" ] } }
    ]
  }
}

Note that I'm using a field like field-demo-tags (instead of field_category as in your case). I'm NOT using the Role Reference module, no need for it. The Rules Action is to only perform a Rules Component, in which the real magic will happen (see below).
Rules component
Here is my sample Rules Component:
{ "rules_do_something_with_selected_term" : {
    "LABEL" : "Do something with selected term",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "selected_term" : { "label" : "Selected term", "type" : "taxonomy_term" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-term" ], "field" : "field_related_role" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Field \u0022field_related_role\u0022  (for Related role ID) is [selected-term:field-related-role]." } },
      { "variable_add" : {
          "USING" : { "type" : "list\u003Cinteger\u003E", "value" : [ "" ] },
          "PROVIDE" : { "variable_added" : { "list_of_roles" : "List of roles" } }
        }
      },
      { "list_add" : {
          "list" : [ "list-of-roles" ],
          "item" : [ "selected-term:field-related-role" ],
          "unique" : "1"
        }
      },
      { "mail_to_users_of_role" : {
          "roles" : [ "list-of-roles" ],
          "subject" : "Some eMail subject (delivered to all users with role id = [selected-term:field-related-role])",
          "message" : "Some message content related to the term named [selected-term:name] (delivered to all users with role id = [selected-term:field-related-role])"
        }
      }
    ]
  }
}

The field field_related_role is an extra field I added to my taxonomy term I'm using (single value, data type integer), instead of field_responsible_team as in your case.
Some more details about this Rules Component:

Rules Conditions:

Check the type of node (in my case "article", adapt to fit your needs).
Check that the entity (node being created or updated) has a field field_demo_tags (the term I'm using).

Rules Action:

Show a message on the site (just for QA-testing purposes, omit if not needed anymore).
Add a variable, i.e. a "list of integers", which will become the "List of roles" we'll need in a subsequent Rules Action.
Add to this list, the value of selected-term:field-related-role (part of the Rules Component parameter).
Send mail to all users of a role, whereas we use the newly created "List of roles" to get it all to work (adapt eMail subject, message, etc to fit your needs).

The above works like a charm, at least in my case/setup: I have 3 users with a role related to a taxonomy term I used while updating an article, and each of those 3 users did receive an eMail as in my last Rules Action.
Voilà ...
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/74441/discussion-on-answer-by-pierre-vriens-use-rules-to-email-all-members-of-a-role-t).


How to find the 3D point from projection point?

Question: I can calculate projection point on monitor of a 3D polygon using the following equation.
$x'=x/(1+z/d)\\y'=y/(1+z/d)$.
Where $(x,y,z)$ is the $3D$ points and $(x',y')$ is projection points on the monitor. And $d$ is distance between COP(center of projection) and PP(Projection plane/monitor).
Now, I have $3$ points of polygon $(x_1,y_1,z_1),(x_2,y_2,z_2),(x_3,y_3,z_3)$. Using the above equation I can find out $(x'_1,y'_1),(x'_2,y'_2),(x'_3,y'_3)$ on the monitor. After find out the projection point of corner of polygon I can find out all projection points of the polygon.
Now, my question is if I choose a point $(x_p,y_p)$ on the projected polygon that is on the PP, how can I find out the original $3D$ point of this point?
[I need this to implement polygon filling algorithm with shading in computer graphics.]
Answer: Suppose the $3D$ co-ordinate of COP, projection point, and original object point are $(x_c,y_c,z_c)$, $(x',y',z')$, and $(x_3,y_3,z_3)$.
$\frac{x_c-x'}{x'-x_3}=\frac{y_c-y'}{y'-y_3}=\frac{z_c-z'}{z'-z_3}=k'=\frac{1}{k}$
So, $x_3=x'-k(x_c-x'),\\y_3=y'-k(y_c-y'),\\z_3=z'-k(z_c-z')$
Where $z'=0$ if the PP is on the origin.
To calculate value of k, we have to use the general equation of plane $Ax+By+Cz+d=0$. Substituting $(x,y,z)$ with $(x_3,y_3,z_3)$ we find
$A\{x'-k(x_c-x')\}+B\{y'-k(y_c-y')\}+C\{z'-k(z_c-z')\}+d=0$
$Ax'-Ak(x_c-x')+By'-Bk(y_c-y')+Cz'-Ck(z_c-z')+d=0$
$-k\{A(x_c-x')+Bk(y_c-y')+Ck(z_c-z')\}+Ax'+By'+Cz'+d=0$
$k=\frac{Ax'+By'+Cz'+d}{A(x_c-x')+Bk(y_c-y')+Ck(z_c-z')}$
To know the value of $A,B,C,d$ see this answer


How to interpret the plotted difference of in-factor smooths

Question: I used the gamm4 R package to analyze the location effect on heart rate over time (Inc_age), including some linear co-variates and a random effect. My model looks like this:
model <- gamm4(Heart rate ~ s(Inc_age, by = Location) + Location + Time_dec +
               Mass * Egg_temp, data = hr1, random = ~ (1 |Egg_ID),
               REML = TRUE)

I checked for colinearity of linear predictors, concurvity, autocorrelation, adequate k, and also the residuals look fine. Now I am struggling a bit with the interpretation of the results.
1) The summary table tells me that both smoothers per location are significant. The parametric coefficients table tells me that location has a significant effect on heart rate. The linear fixed effects and the interaction term are not significant. R-squared is 0.73. So far, so good. Now, I want to know in which exact time window the locations differ.

2) When plotting the two smoothers (one per location) the confidence levels are overlapping in most parts of the curves, only one part seems to be just not overlapping. Is this non-overlapping time window the only one in which the locations differ? This is the code I used:
plot_smooth(model$gam, view="Inc_age", cond=list(Location="North"),
            rm.ranef=TRUE, rug=FALSE, col="red", ylim=c(0,400))
plot_smooth(model$gam, view="Inc_age", cond=list(Location="South"),
            rm.ranef=TRUE, rug=FALSE, col="cyan", add=TRUE)

3) I also try to plot the difference between the smooths with the following code:
model$gam1 <- getViz(model$gam)

plotDiff(s1 = sm(model$gam1, 1), s2 = sm(model$gam1, 2)) + l_ciPoly() +
         l_fitLine() + geom_hline(yintercept = 0, linetype = 2)

The y-axis is s(North)-s(South) = SD = the difference between the fitted smooth. X-axis is time. It shows a single curve with a confidence interval. Again, there is one time window in which the confidence bands do not cross the 0 line. This is not the same time window that I described in (2).

My question is whether this is the correct way to find the exact differences between locations. And if so, how do I interpret the plots? Is there also a way to calculate the exact time window instead of visualizing it?
Follow-up
I am following the steps you presented on link.
I adjusted it slightly because I only have two groups (not more) that I want to compare. When I try to calculate the difference between the smoothers ( dif <- X %*% coef(model) ), I get an error saying "non-conformable arguments". I assume this is because I run this on the model that also includes my linear predictors. Because it does work for the same model, excluding those. If understand correctly, that is also what you describe in your comment above.
Then, when I calculate dif, se, upr, and lwr of the reduced model (excluding linear covariates) and I plot this against time (inc_age), I get indeed the same plot as the second one in my original question. So, I guess this confirms that plotDiff computes the same as in your example.
Then, !(upr_ci > 0 & lwr_ci < 0) tells me that the difference lies in inc_age 6 and 7. However, when I plot the raw data the lines are overlapping at that stage and the difference seems to be from inc_age 9 onwards. I am still struggling to understand this. Or did I make a mistake somewhere?
Comment: When you did `coef(model)` you didn't forget to use the `$gam` component of the model did you? That post was written expecting a model fitted by `gam` so you have to be sure to change all instances referring the `model` to `model$gam`. But it may not be that; covariates shouldn't affect things... but I can take a look at the code again.
Comment: Re the second follow-up question, I think there is some confusion about what is being tested when you compute the difference in the smooth effects. What we mean by a difference in the smooths is a difference in the *shape* of the two smooths. Whether the fitted values for the two groups over lap is not of interest *when one is looking at differences in the shapes of the smooths*. If you're interested in whether the *fitted values* differ, you are looking at effects of *smooths* + *group_means*, not just *smooths*. 1/2
Comment: You would need to not zero out the columns in the Xp matrix that relate to the intercept and the other group coefficient, and retain their coefficients also. That way, when you difference the Xp matrix, you are differencing the columns that relate to the smooth plus the columns that relate to the group effects. Another way to do this would be to simulate predictions from the model posterior many times, and for each simulation, subtract the values for one group from the other. That gives you a posterior distribution for the differences, and you can see how many sims include zero difference. 2/2
Comment: I'm keenly aware that what I wrote above may not be something you know how to do. If you can post some example data to work with or email me the data offline, I can work up an answer to show how to do these things in a setting that is like yours. Otherwise, I can modify the example from the blog post to show you how both of these might be done? Won't get to that until later this afternoon however.
Comment: I really appreciate your effort, thanks so much! Sorry for the late response!  I tried to figure out on my own what you described above, but I have to admit that I do struggle a bit. I did indeed check and `model` generally does not work on these functions as it is a list of a gam and a mer object.
Comment: I will give it another try today, but I would love to take your kind offer to email you my data and script. Or maybe even better to post a subset of the data here, so this example can help others struggling with the same problem. I will try to figure out how to post some data here.
Answer: The first plot showing the two smooths also includes the model constant term (the intercept), whereas the second plot is showing the difference between the two smooths themselves, excluding the constant term. As such you have to be careful to distinguish what you mean by the difference between the two smooths; the first figure conflates differences in group means and differences of smooth effects of the covariate between the groups.
Typically, however, one is interested in the difference in the estimated smooth effect of the covariate. As such the second plot is the one I would typically use to look at differences between smooths.
That said, the first plot is useful because it shows more clearly the differences between groups (i.e. groups means plus by group smooth effects).
There are ways to get the differences directly; I'm not sure how one does this with the software you are using (unstated) but it is reasonably trivial (if tedious) to compute them by hand. I have an example of how to do this here: https://fromthebottomoftheheap.net/2017/10/10/difference-splines-i/ and I'm reasonably sure that plotDiff is following the same approach to compute the differences between smooths. As such you could also look at the code behind plotDiff to see what it is doing.
Once you have the difference and the confidence interval, it only requires you to identify which points where the CI excludes 0. Find the points where 0 is inside the interval and then invert that selection: !(upr_ci > 0 & lwr_ci < 0) for example.
Comment: Dear Gavin, this response is a great relief!! Thanks a lot!! I will follow up on your advice and will post later on how it went.
About your question: I am sorry, I forgot to mention that the software that I work with is R (4.0 hooray!)


add category with different attribute in spring boot

Question: I have web site that every one can have advertisement .
All advertisements have category and admin can add category with different fields for example for selling house we have number of room but for car we have another option . I dont know what I should do for fields and how is sub category table.
<code> public class category{
private long id;
private String name;
@OneToMany
List<subcategory> sub;
}
</code>
How is sub category class with different fields for different category?
Comment: post code that you've tried?
Comment: Im not sure code help but i will add it
Answer: You could use a Map rather than a subcategory object. This Map could contain the key and value of the fields on each case.
And remembeer to capitalize class names like java conventions says.
Comment: We have name ,  value and key from category .Correct?
Comment: You can have a Map using the category key as the key of map and category object as value of map


exclude - None of the following functions can be called with the arguments supplied

Question: here build.gradle
dependencies {
    implementation(enforcedPlatform("org.springframework.boot:spring-boot-dependencies:3.1.2")) {
        exclude group: "ch.qos.logback", module: "logback-classic"
        exclude group: "ch.qos.logback", module: "logback-core"
    }

    implementation("org.apache.logging.log4j:log4j-api")
    implementation("org.apache.logging.log4j:log4j-core")

    testImplementation("org.jetbrains.kotlin:kotlin-test")
    testImplementation("junit:junit")
    testImplementation("org.junit.jupiter:junit-jupiter-api")
    testImplementation("org.junit.jupiter:junit-jupiter-engine")
    testImplementation("org.junit.jupiter:junit-jupiter-params")
    testImplementation("org.assertj:assertj-core")
}

And it's work just fine.
But I want to do same in build.gradle.kts
build.gradle.kts
dependencies {
      implementation(enforcedPlatform("org.springframework.boot:spring-boot-dependencies:3.1.2")) {
        exclude("ch.qos.logback", "logback-core")
    }

    implementation("org.apache.logging.log4j:log4j-api")
    implementation("org.apache.logging.log4j:log4j-core")
    implementation("org.apache.logging.log4j:log4j-slf4j-impl")

    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

But rise error:
Script compilation error:
  Line 28:         exclude("ch.qos.logback", "logback-core")
                   ^ None of the following functions can be called with the arguments supplied:
                       public open fun exclude(vararg p0: Class<*>!): Categories.CategoryFilter! defined in org.gradle.internal.impldep.org.junit.experimental.categories.Categories.CategoryFilter
                       public open fun exclude(p0: Boolean, vararg p1: Class<*>!): Categories.CategoryFilter! defined in org.gradle.internal.impldep.org.junit.experimental.categories.Categories.CategoryFilter

Answer: The short answer is you can remove that call to exclude.
When you use enforcedPlatform you are declaring a dependency on a Maven BOM which doesn't add dependencies per se, it just specifies versions for them. So it won't add Logback as a dependency (which appears to be your desired outcome), and in turn you don't need to exclude it.
In the Kotlin DSL, calling exclude for a platform dependency is no longer a valid call1. It has, then, has removed some functionality from Gradle.
I don't believe this is a big problem though. Using exclude in the Groovy way appears useful if you want to use Logback (or another dependency specified in a BOM) but you didn't want the version specified in the BOM. However, in such a case you could use platform rather than enforcedPlatform to register the BOM and you could go on to choose the version you wanted (which would then have precedence).

1On a code level, using enforcedPlatform changes the receiver in the closure from ModuleDependency to a plain Dependency, meaning that the extension function exclude, an extension of ModuleDependency, is no longer available in that scope.


iOS vice versa import workaround

Question: I try to find answer for my question but failed.
Can i do any workaround to let two classes import each other.
#import "classB.h"
@interface classA : NSObject
{
    classB bObject;
}

#import "classA.h"
@interface classB : NSObject
{
   classA aObject;
}

Thanks
Answer: Instead of actually importing your headers in your headers, use @class to make a forward class declaration:
@class classB;
@interface classA : NSObject
{
    classB bObject;
}

@class classA;
@interface classB : NSObject
{
   classA aObject;
}

This just tells the compiler that classA and classB are classes, without actually loading any of the interfaces.
If you use any of classA's methods in classB, you'll need the classA interface in classB's implementation, in which case you can just import classB.h in classA.h (or vice versa).

iOS vice versa import workaround


Calculating Pixel Distance in QT C++

Question: I am writing an  application , to  compare  2 images of same dimensions  ,  I need to compare distance For example if two images of the Same then the distance between those two images would be zero. If two images are completely different than the distance between them would be quite large.The project involves taking a sample image and using that as a base and seeing any distortions in color or  gradient have occurred in the subsequent images.
Comment: What is your question? And what have you tried?
Comment: So far nothing , I was  looking OpenCV ,  or some other image processing library
Answer: It is quite difficult to define a distance between images which is similar to what the human brain recognizes as "close" images. In particular distortion of images is not easy to catch. However if you only look at pointwise distortion of color and gradients you can define a distance between images A and B as:
<code>d(A,B) = sqrt ( sum ( A(i,j)-B(i,j) )^2 )
</code>
where A(i,j) is the 3D-vector with RGB components of the color of pixel at coordinates i,j in image A.
Comment: I was thinking more in the lines of Damerau–Levenshtein distance  ,  I know is is applied  to  string or  array of  characters , I was kind of hoping I could get some thing  similar for images.

Calculating Pixel Distance in QT C++


Elementary inequality with norms

Question: Is it reasonable to hope the validity of an inequality of this form, where $H$ can be any separable Hilbert space
$$\forall \alpha \geq 0 \, \exists \gamma \geq 0: || x - \alpha y|| \leq \gamma || x -y ||, \quad \forall x,y\in H$$
If not, any counterexample to get an intuition of what goes wrong?
Thanks a lot
Answer: If $\alpha\neq 1$, then it fails for $x=y$, since the right hand side is $0$, and the left hand side is positive.
Comment: oh, gosh, such a stupid question I asked...quite embarassing.
Thanks a lot and sorry for the waste of time :)
Comment: @Matt no worries.

Elementary inequality with norms


Convergence of $\frac{\cos(x)}{n\sin(x)}$ an n$\rightarrow \infty$

Question: So I have this as my homework in Measure Theory and I don't know how to prove it. The question is the following:
On the domain $\Omega = (0, \pi)\times {\rm I\!R}$ we have a function defined as:
\begin{equation}
\phi_{n}(x,y) = \frac{\cos(x)}{n\sin(y)} \qquad if\,\,y\in {\rm I\!R}\setminus \{k\pi | k\in {\rm I\!N} \} \\ \phi_{n}(x,y)=n^2 \,\,\,\,\,\,\qquad if\,\,y\in \{k\pi | k\in {\rm I\!N} \}.
\end{equation}
Now I need to prove that the sequence
\begin{equation}
\{\int_{\Omega}|\phi_{n}(x,y)|dxdy\}
\end{equation}
is convergent almost everywhere. I know that since $\{ k\pi | k\in {\rm I\!N}\}$ is just a set of disjoint points, its Lebesgue measure is $0$, hence, we don't care about them.  I was specifically told that I should use Fatou's lemma which we can apply due to the absolute sign. Thus, since we have sequence of positive functions we have
\begin{equation}
\int_{\Omega}\lim \inf |\phi_{n}| \leq \lim \inf \int_{\Omega}|\phi_{n}|.
\end{equation}
Also, we have the inverse inequality for the $\lim \sup$ as well i.e.
\begin{equation}
\lim \sup \int_{\Omega}|\phi_{n}| \leq \int_{\Omega}\lim \sup |\phi_{n}|.
\end{equation}
Then, if the $\lim \inf$ and $\lim \sup$ coincide, we have that the sequence is actually converges and we get that
\begin{equation}
\int_{\Omega}\lim \inf |\phi_{n}| = \lim \int_{\Omega} |\phi_{n}| = \int_{\Omega}| \lim \sup |\phi_{n}|.
\end{equation}
However, I am stuguling with how to use the properties of $\phi_{n}$ to show that $\lim \inf = \lim \sup$. Any help would be appriciated.
Comment: Look at the expression for $\phi_n(x,y)$. What does it converge to almost everywhere?
Comment: I know that it converges to 0, but I assumed that I should not know that, and by just using some properties of sin and cos we can prove that limsup and liminf are the same.
Comment: Why did you assume that? The pointwise a.e. limit doesn't really have anything to do with sin and cos, that's kind of the "trick" with problems like this. At a.e. point $(x,y)$ its just a sequence of the form $const.\times 1/n$
Comment: So then I should just show that liminf = 0 and limsup = 0, if yes then please post it as an answer and when I am done with the proof (probably tomorrow), then I accept as an answer.
Answer: Let $Y=\{k\pi : k\in\mathbb N\}$ then $|Y|=0$ so by Fubini theorem
$$
\int_{\Omega} |\phi_n(x, y)|dxdy = \frac 1n\int_{\Omega\setminus Y}\left\lvert\frac{\cos x}{\sin y}\right\rvert dxdy=\frac 1n\int^\pi_0\lvert\cos x\rvert dx\int_{\mathbb R\setminus Y}\left\lvert\frac{1}{\sin y}\right\rvert dy=
$$
Now
$$
\int_{\mathbb R\setminus Y}\left\lvert\frac{1}{\sin y}\right\rvert dy=\sum^{+\infty}_{i=-\infty}\int^{(i+1)\pi}_{i\pi}\left\lvert\frac{1}{\sin y}\right\rvert dy=\sum^{+\infty}_{i=-\infty}\int^{\pi}_{0}\left\lvert\frac{1}{\sin y}\right\rvert dy=+\infty
$$
and doesn't converge
Comment: That is true, $\int |1/\sin(y)|$ $\rightarrow \infty$ but as was pointed out by @T_M, we can consider $\int |1/sin(y)|$ as a constant for all $y \in R\setminus Y$ which is less than $\infty$ and as n $\rightarrow \infty$ we indeed get that $\int |\phi_{n}(x,y)|$ converges to 0, don't we?
Comment: The integral doesn't converge for all $n$, if $\frac{1}{\lvert\sin y\rvert}$ is integrated on a set smaller than $\mathbb R$ (like compact set) the integral _may_ be considered as a finite constant


Alterar nome de uma variavel em um dataframe R

Question: Tenho um dataframe com 34846 observações e 15 variaveis, gostaria de saber como tenho que fazer para alterar o nome de uma variavel.                       Exemplo:Tenho a variavel "Country" e gostaria de renomear para "Pais"
Answer: Com dplyr você pode fazer assim:
library(dplyr)
df <- df %>% rename(Pais = Country)

Comment: Ou com uma sintaxe mais curta, já que está usando pipes: `df %<>% rename(Pais = Country)`
Answer: Usando grep para achar o número da coluna que quer mudar de nome:
dados <- data.frame(
  'Year' = 2015:2018,
  'Country' = 'Brazil',
  'Continent' = 'America'
)

names(dados)[grep('Country', names(dados))] <- 'País'

> dados
  Year   País Continent
1 2015 Brazil   America
2 2016 Brazil   America
3 2017 Brazil   America
4 2018 Brazil   America

Answer: Outra maneira, mas sem utilizar pacotes.
x = names(dataset)
x[(names(dataset) == "Country")] = "Pais"
colnames(dataset) = x

Answer: Você também pode fazer isso:
colnames(dados)[1]<-'Pais' # 1 é o número da coluna Country


How do I get a user field from an entity reference?

Question:

I'm working with the Twilio module to create a Rule that will send out an SMS message when a user creates a specific piece of content.  Here's how I've got things laid out at the moment.

I have a content type called Office (field_office), which contains the regional office name (imported from LDAP, but that probably doesn't matter.)
I have an entity reference user profile field called field_user_office that links to the Office content type.
I created a content type called Blast Message with an entity reference field called field_office_sms which also links to the Office content type.  When a user wants to create an SMS they create one of these nodes and select one or more offices to send to.

When I set up my rule I'm not seeing the fields exposed as I expected.  I tried adding two Entity has field conditions, Parameter: Entity: [node], Field: field_office_sms and Parameter: Entity: [node], Field: field_mobile_phone, the last of which is the actual mobile number saved in the users' accounts.
How do I navigate from the original content (Blast Message) through the Offices, then to the specific Users who are linked to that office, and ultimately retrieve their mobile phone numbers?
Answer: You need to use the action: Fetch entity by property.

Condition: Entity has field > node: field_office_sms
Fetch entity by property > User > Property: field_user_office > Value: node: field_office_sms:nid
Loop: List: [entity-fetched]
Action: Send SMS > list-item: field_mobile_phone
Comment: Interesting -- though I'm running into a problem with the Fetch entity by property action in that I don't have nid as an option.  For node:field_office_sms my options are 0, 1, 2, and 3.  Also, my Send SMS action doesn't have list-item as a choice as I get (only site, node, and entity-fetched, and entity-fetched has the same 0, 1, 2, and 3 options.)
Comment: You have 0,1,2 and 3 because it's an unlimited field. So you have to go into 0:nid as it's the first (and only?) option. When you do the fetch, you can do the loop and get list items.
Comment: Unfortunately trying to force node:field-office-sms:0:nid gives the error "The data type of the configured argument does not match the parameter's value requirement." and it won't save.
Comment: Have you made any progress? Some screenshots could help.. Also try using the action, "convert value" to integer. I've had to do that before.
Comment: No luck so far, but screenshots added.  I tried adding "convert data type" as I don't see "convert value", but I'm not sure what to do with that once it's in place.


POSTing variable with an array within it

Question: As the title says
$champion = array();
for($i=1;$i<=$champ_number; $i++){
                    $champion[$i] = $_POST['champno'.$i];
}
echo '<input type="hidden" name="champion[]" value="'.$champion.'">';

What's the simplest least secure way to POST this variable $champion through POST is?
Comment: I would suggest you to make hidden fields with corresponding name and value inside the loop itself and keepone more hidden field outside the loop to keep the count of `i`..all these will be posted to the next page and there you can get all the values using a for loop..try it..
Answer: try to follow this simple format:
E.g. : FORM
 <form method="post" action="submit.php">
    <?php
    $champion=array('hiii','helloooo');

    echo '<input type="hidden" name="champion" value="'.htmlspecialchars(json_encode($champion)).'">';

    ?>
    <input type="submit" value="sub">
    </form>

your submit.php :
<?php
$champions = json_decode($_POST['champion'], true);
echo $champions[1];// out put helloooo
?>

Comment: $champion = array("test", "test2");
$championSerialized = json_encode($champion);
    echo '';

Tried it

$champion = json_decode($_POST['champion'], true);
    echo $champion[0];
      echo $champion[1];
Comment: You must use `htmlspecialchars` in your `$championSerialized` data.
Answer: If you really want to post the entire array, then: serializing your array. http://php.net/manual/de/function.serialize.php
...
$championSerialized = serialize( $champion );
echo '<input type="hidden" name="champion" value="' . $championSerialized . '">';

Retrieving the data is just using $championPost = deserialize( $_POST[ 'champion' ] );
Comment: I tried something like that
     $championSerialized = serialize($champion);
     echo ''; and on the next page
     $champion = unserialize($_POST['champion']);
Comment: Unserializing user-supplied data is a bad idea.


Survey data: finding the most significant predictors?

Question: I have about 5,000 responses to a survey in which users were asked how strongly they agreed with a statement on a 5-point Likert scale. This response is my dependent variable - I want to find out what influences this answer.
In the same questionnaire, the users gave a lot of other data, including age, employment, gender, location, and answers to other Likert questions.
From all of these, I want to find the factors that are most strongly correlated with their answers to the dependent variable  - so that I can say "The most important predictive factor for agreeing with the statement was X. Other important predictive factors were Y and Z."
What approach should I use? I've been reading around and it looks like the two best approaches might be:

individual chi-squared tests for each column, then compare the probability of the chi-squared scores and see which is most significant
a multiple linear regression model

I'm not completely clear on the second approach: specifically, whether I can use to pull out the importance of individual factors, and whether it's useful for analytical work rather than predictive work. I don't want to dive in without having a good understanding of the best approach.
Suggestions much appreciated.
Comment: Can you say something about what you mean by "analytical" versus "predictive" work?
Comment: Sorry - I'll try to be more clear.

I'm looking for a way to say "the most important factors in the answers to question X were questions E and J, and demographic factors Y and Z".

I don't want to build a model that given answers A, B, C, D... P and demographic factors Q, R...  Y, Z can create a complicated (and hard to understand) equation accurately predict the answer to question X. Prediction isn't my use case, and I want an answer that is actionable - focus on E and J!

Does that make things clearer? I hope so, thank you very much for looking at my question.
Answer: Multiple regression provides opportunities for looking not only at how individual variables are related to your response of interest (from their regression coefficients), but also at how interactions among them may influence that response. For example: does variable E have a different relation to the response in demographic Y1 than in demographic Y2? For continuous variables like age and income, including them as continuous variables (possibly scaled) in regressions is generally preferable to breaking them down into arbitrary categories. Formulating the problem that way also makes it straightforward to examine correlations among the individual variables, which can be important for interpreting your present results and for design of future studies.
Comment: (+1) Note the response is probably better treated as an ordinal categorical variable - a proportional odds multiple regression model might well suit.
Comment: OK great - thank you. And just to be clear - I don't need to create a training and test set, because my goal isn't prediction. I can create the model across the whole dataset. Correct?
Comment: Depends on how much you care about generalization to the population of interest and the model's robustness. If you are, say, just trying to identify action items you can take (e.g., question E is "waiting time for checkout" in a store, and you can hire more cashiers), and your outcome is "overall customer satisfaction", then the whole-dataset model may point to potentially useful interventions. But no model will prove causality, and without model validation it may be unreliable to extend your model beyond your original dataset.


Expression to use on array in ng-class

Question: There's an array on my controller's $scope ...
$scope.myElements = [false, false, true, false, true, false];

... and the class on a div tag should be firstClass if at least one of the elements in said array is true, otherwise secondClass. Easy to achieve with ng-class ...

...and a helper function...
$scope.anyElementTrue = function () {
    for (var i = 0; i < $scope.myElements.length; i++) {
        if ($scope.myElements[i]) return true;
    }
    return false;
}

Is there an easier way to achieve the same just with an expression? Something like this:

Except that there is no angular.any. Thoughts?
Answer: You can do it like this:

 -1 ? 'firstClass' : 'secondClass'">

Expression to use on array in ng-class


Android Retry/Cancel Dialog

Question: I have the following problem. My main activity consists of a ListView populated with the data obtained from a web service. When the main activity is first loaded, in case the data can't be retrieved from the web, I want to display a dialog with 2 buttons, 'Retry' and 'Cancel'. If the user clicks on 'Reply', the reload data method is called, and if there's any exception, the dialog should appear again.
I haven't found a way yet to implement my desired behavior.
<code>@Override
protected void onResume() {
   super.onResume();
   Log.i("ItemListActivity", "onResume()");
   if(isNewInstance) {
      reloadItems();
      isNewInstance = false;
   }
}

private void reloadItems() {

   try {
       itemService.reloadItems();
       items = itemService.getItemList();
       listAdapter.notifyDataSetChanged();
   } catch (Exception e) {
       showDialog(RETRY_DIALOG);
   }

}

protected Dialog onCreateDialog(int id) {
   switch(id) {
      case RETRY_DIALOG:
         return new AlertDialog.Builder(this).setTitle(R.string.retryDialog_title)
         .setPositiveButton(R.string.retryDialog_retry, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    reloadItems();
                }

            })
            .setNegativeButton(R.string.retryDialog_quit, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            })
            .create();
    }

    return null;
}
</code>
The first time the reloadItems() is called from onResume() and an exception is encountered, the dialog is displayed. But when I click the "Retry" button and this time  reloadItems() is called from the dialog's onclicklistener, the dialog isn't displayed second time, I guess because the onclicklistener will return only after the the reloadItems() has returned the second time.
I tried to run reloadItems() in a new thread from onClick(), but the code still runs in the main thread. If I run reloadItems() from onResume() in a new thread, the code runs in a new thread.
What I also noticed while debugging is that the dialog isn't showed right after showDialog(RETRY_DIALOG) returns, only after the reloadItems() returns.
As what I want to do is quite common behavior I'm sure that there is a "best practice" solution to this. I'm totally new to Android and I'm not used with this style.
Answer: You should be running your reloadItems method in an ASyncTask.
These run your web access and download process in a background thread and allow you to post UI updates ON THE UI THREAD.
You can also handle the exception in the background thread and then post an update to the UI thread that shows your dialog.  Don't forget to kill your task after this failure update or it will keep trying to run and think it finished successfully.
Also important, you have to create a NEW INSTANCE of your task each time it runs (so on the onClick listener for the Retry button for example.  Reusing a task will cause an exception.

Android Retry/Cancel Dialog


How to find the values of q for which the integral $\int_3^\infty \frac{(1 + x^{25q})(1 - x^q)}{((1 + x^q)(1 - x^{25q})}\, dx$ diverges?

Question: For the integrand $\frac{(1 + x^{25q})(1 - x^q)}{((1 + x^q)(1 - x^{25q})}$, I calculated that the dominant term in the numerator is $x^{26q}$ and the dominant term in the denominator is also $x^{26q}$. So the integrand simplifies to 1. What does this mean in terms of convergence and divergence? The answer is that the integral diverges for any real value of q but I don't know what theorems are used to find this.
Comment: If this integral were convergent, you would necessarily get a decay towards infinity. Do you have such decay of the integrand?
Answer: For $q>0$ the dominant term of the top and bottom for large $x$ are equal as you said, so the $\lim_{x \to \infty} =1$. Since this limit is defined and not $0$, the integral to infinity must diverge.
For $q<0$ the dominant terms on top and bottom are both 1, so again it must diverge by the same logic.
Finally, for $q=0$, we are dividing by zero, so the integrand is not defined.
Comment: I'm confused about the definition of a divergent integral. I thought that a divergent integral is where an improper integral's limit doesn't exist and that if the limit exists and is a real number it's convergent?
Comment: @Crystal This is right but if $\lim_{x \to \infty} f(x) = 1$ as discussed above, then the integral won't converge. Think of the divergence test for infinite series.


Q-Learning: state independent of agent's action

Question: Could state be independent of the action chosen by agent? We would have a situation in which agent learns only which actions are the best in specific states without having any impact on those states (States change with every next iteration). If I create such algorithm will it create anything sensible or agent should always have an impact on the next state when he perform action?
Answer: Since you're using the q-learning tag, I'll assume that your question is concerning the $Q$-learning algorithm.
Typically we assume in Reinforcement Learning (RL) that an agent's action will have some level of influence on what state we end up with, but that actually still covers your case.
Let $P(S, A, S')$ denote the probability that we end up in state $S'$ after executing action $A$ in state $S$. Essentially, what you say is that, given any pair of states $S$ and $S'$:
\begin{equation}
P(S, A_1, S') = P(S, A_2, S') = \dots = P(S, A_n, S').
\end{equation}
This is simply one special case of the more generally considered case, so it's certainly allowed and you'll certainly learn something useful.
$Q$-learning may be unnecessarily complex for such a case though. It will work, but simpler algorithms may work equally well/better in such a specific case (specifically; algorithms that, unlike $Q$-learning, exploit knowledge of the specific properties you have described and do not also have to function in more general cases).
For example, in the specific case you have described it may be worth considering Contextual Multi-Armed Bandit algorithms, where your current state $S$ is the context, and the actions $A$ are the arms. These algorithms aim to optimize the immediate one-step reward of selecting an action $A$ in a state $S$, whereas an algorithm like $Q$-learning aims to optimize the discounted long-term rewards, of which the immediate one-step reward is only a single component. In your case, where the selected action has no influence on the state you end up in, those two goals are equivalent.


Force reload watchOS 2 Complications

Question: I have issues getting Complications to work. It would be helpful if I was able to reliably refresh them.
Therefore I linked a force-press menu button to the following method
@IBAction func updateComplication() {
    let complicationServer = CLKComplicationServer.sharedInstance()
    for complication in complicationServer.activeComplications {
        complicationServer.reloadTimelineForComplication(complication)
    }
}

Unfortunately this leads to the app crashing. with a fatal error: unexpectedly found nil while unwrapping an Optional value.
I understand that calling reloadTimelineForComplication(complication) is budgeted but that can't be the issue here as it doesn't work from the very beginning.
I am currently using watchOS2 + Xcode 7 GM
I'd appreciate any ideas on making Complications refresh while the app is running?
Answer: Trace or use the exception breakpoint and focus on reading the whole error message where it tells you exactly on which line it found the nil unexpectedly (I do suspect the complicationServer). Use 'if let' instead of 'let' to force unwrap the respective variable.
private func reloadComplications() {
    if let complications: [CLKComplication] = CLKComplicationServer.sharedInstance().activeComplications {
        if complications.count > 0 {
            for complication in complications {
                CLKComplicationServer.sharedInstance().reloadTimelineForComplication(complication)
                NSLog("Reloading complication \(complication.description)...")
            }
            WKInterfaceDevice.currentDevice().playHaptic(WKHapticType.Click) // haptic only for debugging
        }
    }
}

Comment: One thing: Do not forget to add observer for CLKComplicationServerActiveComplicationsDidChangeNotification to update it continuously
Comment: It fires on events like watch face change
Comment: why CLKComplicationServer.sharedInstance().activeComplications always returns nil?
Comment: Is it always? I think it is only when throttling disables that complications... that's why there is the `if let` construct, because this happens most of the time (except for when the complications are scheduled for redraw).

Force reload watchOS 2 Complications


Does software exist to catalogue band parts?

Question: My brass band is looking at putting our band library catalogue into a database, but we haven't been able to find any software designed for this purpose. We'd like to store not only information about the pieces (composer, arranger, date, length, difficulty), but also information about the parts: which parts are supposed to exist, how many of each part we have, the date it was last checked.
We'd like to be able to search the database by piece name, composer, and arranger; but also browse a list, filtering it by whether our training band could play it, or whether we have enough parts. Ideally, we'd also be able to store the playing history for each piece (so we can avoid playing the same piece at the same event) and 'tag' each piece with its style (jazz, march, &c.) and suitability for special events (Christmas, bandstand, church service, &c.).
Given the value of these data and how hard it would be to replace it, we'd rather not trust it to some "cloud" provider unless we can be sure we'll always be able to get the data back out of it.
Does this software exist, or would we have to hack it together ourselves using a generic database package?
Comment: A quick search came up with this: http://www.musiclibrarian.net/   Maybe it's what you're looking for?
Answer: You're looking to manage a database. I'm sure Google could help you now, but here are a few leads:

FileMaker is the industry standard. The cheapest version is $300, and it's way overpowered for what you need, but if you want the standard solution, here it is.
OpenOffice contains a database editor, and is free (open source, even). From my experience with it, this won't be the prettiest catalogue when you're done, but it'll work.
I'm a middle school band teacher, and I use Bento for exactly this. It's made by FileMaker, and I believe they share a good deal of code, but Bento sacrifices a little of FileMaker's power for tons of ease of use. (It's also much cheaper--but it only runs on Mac OS X and iOS.) Here's what I was able to accomplish in my first hour of using Bento:

Table view:

And form view:

All of these products are built to manage your data and have excellent export capabilities, so no worries there--if you don't like your first choice, you won't be "locked in". Good luck!
Answer: Based on your description, what your needs are, are very simple. You should be able to build your own with a simple database like Microsoft Access.  At its simplest, your description could be just one table.  Further, instead of a single table you could start with a single spreadsheet, like Microsoft Excel. That would get you started and let you further develop your ideas for what your really need. Not a bad way to start even bigger computer projects.
Having said that, and as a computer professional, I could tell you there are a lot of reasons you should not do that. But its still a good way to start.
This is really a database problem, so there are some advantages to starting with Access.  For example, rather than putting a composer into several records, where his name could be spelled differently on each record, you could make a Composer table and list each composer's name once, then just refer to it from your main catalogue table. So, if you start with just one table you can add tables as you define the database. Access will also let you create a form to enter the data and provide lookups of composers and other information. They system can grow with you.
I think its good to be involved because the system will become what you need it to do. It doesn't sound like you really need more than that.
Answer: The most flexible solution is likely to be a generic database app like FileMaker.  This would allow you to create any fields you need and search on them any way you like.  An out of the box solution will likely not have all the features you want.  I found this company, RCI  http://riden.com/index.shtml  but their webpage doesn't inspire confidence in me, although it seems many people use their software.  If you don't want to pay the $300 for FileMaker, writing your own app is the way to go.  More time intensive, but free, rewarding, and obviously will meet your exact specs.
Answer:
IN Harmony Sheet Music Cataloging Tool (free): http://inharmonycat.sourceforge.net/

This tool has been designed to assist libraries, archives, museums and individual collectors describe their sheet music collections in a robust and standards-based way. This is a production system of the Indiana University Digital Library Program and was used to catalog more than 10,000 pieces of sheet music for the IN Harmony project.

NOTE: short of installing the software, it's not clear whether or not individual parts can be cataloged.

MusicLibrarian.net (donation based):

Adding a new piece of music: This is done in two stages. Firstly the piece is added (including details such as composer, arranger and duration) and then the copies of all the parts are added individually. (http://www.musiclibrarian.net/docu/ml_userguide.pdf)


Showing a function is measurable in a product measure space

Question: I'm working on problem 10.G in Bartle's Elements of Integration and Lebesgue Measure:

Let $f$ and $g$ be real-valued functions on $X$ and $Y$, respectively; suppose that $f$ is $\mathcal{X}$-measurable and $g$ is $\mathcal{Y}$-measurable.  If $h$ is defined on $X\times Y$ by $h(x,y) = f(x) g(y)$, show that $h$ is $(\mathcal{X} \times \mathcal{Y})$-measurable.

My problem is that I can't really think of a way to show that any function is $(\mathcal{X} \times \mathcal{Y})$-measurable.  The only thing I can think to do is try to show that
$$
h^{-1}(\alpha,\infty] \in \mathcal{X} \times \mathcal{Y},
$$
but I can't make any progress in this direction.  Any advice would be appreciated.
Comment: Do you know how to show that the product of two measurable functions (in the same sigma algebra) are measurable?
Answer: What you can do is consider functions $\tilde f, \tilde g:X\times Y\to\mathbb R$, where
$$
\tilde f(x,y)=f(x),\ \ \tilde g(x,y)=g(y).
$$
These are easily seen to be measurable:
$$
\tilde f^{-1}(\alpha,\infty)=f^{-1}(\alpha,\infty)\times Y, \ \ \tilde g^{-1}(\alpha,\infty)=X\times g^{-1}(\alpha,\infty).
$$
As $h=\tilde f\,\tilde g$, it is measurable.
Comment: Oh, and then since products of measurable functions on the same space are measurable, $h$ is measurable.  Thanks, good tip :)


Which megamenu supports i18n content translation?

Question: Do you know which megamenu supports i18n content translation?
Comment: With Drupal core alone, user-defined menu items are not translatable. The Menu translation module, part of the i18n package, allows users to select a translation mode for each menu.
Answer: At this time only tb_megamenu seems to support i18n.
Comment: Any research to support this claim?
Comment: I tried it and its working.
Each language has to got own menu.
Comment: But why do you claim "only"?


Trouble Mounting a Bucket

Question: I am trying to mount this public bucket into my Google cloud shell:
gs://mssng-share/released/genomes/ILMN/VCF/*Using mount point:

/home/serdarrowanalytics/mount

I tried:
gcsfuse mssng-share ./mount

however, i get flagged with this error message.
Opening GCS connection...
Opening bucket...
Mounting file system...
daemonize.Run: readFromProcess: sub-process: mountWithArgs: mountWithConn: Mount: mount: running fusermount: exec: "fusermount": executable file not found in $PATH

stderr:

Comment: What was your question?
Comment: When I run this GCSFuse on Google Shell it does not complete the task of mounting a bucket and replies  "fusermount": executable file not found in $PATH
Comment: second problem: I also tried running it on my local server, and it says "successfully mounted!" but then the directory I mounted the bucket to is empty.
Comment: my question is what I should do differently, or if there are other trouble shooting ideas. I use a very simple command which is:gcsfuse bucket mountdirectory
Comment: If you see this after building and trying to run `gcsfuse` in a Docker container (or in general), one possibility is you just forgot to install `fuse`, which is a dependency.
Answer: Following the tutorial provided by Google, I was able to mount a bucket successfully in my cloud shell.
I followed the install instructions linked from the Google article.
Commands were as follows (starting in my home directory ~/):
export GCSFUSE_REPO=gcsfuse-`lsb_release -c -s`

echo "deb http://packages.cloud.google.com/apt $GCSFUSE_REPO main" | sudo tee /etc/apt/sources.list.d/gcsfuse.list

curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -

sudo apt-get update

sudo apt-get install gcsfuse

mkdir -p ./path/to/mount

Then ran command:
gcsfuse [bucket name (no prefix or suffix)] ./path/to/mount

And it worked.
I had to "sudo su" to enter the directory, but the contents were mounted.
Without steps to reproduce this error, I cannot provide a guaranteed answer. It would all be speculation based on existing articles found through a Google search.
This is not a bug in the cloud shell.
Comment: I've done some research, but everything related to your error is related to Docker. No other programs, other than Docker, are getting this error, & it seems like the Docker issues are resolved based on syntax. I've also failed to reproduce this error. Are you running as root? Also, how large is the file in your bucket? How many files do you have of what type? Following the tutorial, can you mount on a fresh GCE instance? How about using a different bucket? My suggestion is to uninstall & reinstall GCS fuse on your cloud shell. If you can provide reproduction steps I can look further into it.
Comment: Thank you for your attention. I did the same thing. It says "successfully mounted"
Comment: However, the mount directory is empty.
Comment: rowus@bashful:/home/jim$ gcsfuse mssng-share ./mnt
Using mount point: /home/jim/mnt
Opening GCS connection...
Opening bucket...
Mounting file system...
File system has been successfully mounted.
rowus@bashful:/home/jim$ ls
rowus@bashful:/home/jim/mnt$ ls
ls: reading directory '.': Input/output error
Comment: I tried mounting a few buckets. The mount folder is always empty.
Comment: io errors are usually caused by hardware issues. Can you confirm this is happening on your cloud shell?
Comment: I have not been able to mount on the shell or my local server.
Comment: You said " It says "successfully mounted"", then you mentioned the directory was empty, then you showed you were getting an IO error. Then you said you are not able to mount on cloud shell or local server? I am confused.

So, are you able to mount on the cloud shell? What errors are you receiving on the cloud shell? Do you have files in your bucket? I cannot help with an IO error on a local machine.

Trouble Mounting a Bucket


Timer in vb.net Console Application

Question: I looking for an example of Timer which can run my procedure or function every x minutes.
I found only examples of Windows Form project but not in a console application.
Comment: You didn't do much research, did you? (which by the way is the number one reason people down vote)  This will probably help: https://www.codeproject.com/Articles/167365/All-about-NET-Timers-A-Comparison
Comment: If you want to run the console application every x minutes, can you not create a task in windows task scheduler? Or do you want a specific function within the console app to run?
Comment: Hi @rory.ap your link not refers to vb.net console application language. I found many Windows Forms examples but not in console application.
Comment: @tigerdi I want to have internal timer in my application to run procedures, for example one procedure which will be run once a day at specific time, and another every 5 minuts. Thanks
Answer: here is an answer from How can we use timer control in VB.Net Console Application?
<code>Module Module1

Sub Main()
    aTimer.AutoReset = True
    aTimer.Interval = 2000 '2 seconds
    AddHandler aTimer.Elapsed, AddressOf tick
    aTimer.Start()
    Console.ReadKey()
End Sub

Dim aTimer As New System.Timers.Timer

Private Sub tick(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
    Console.WriteLine("tick")
End Sub

End Module
</code>

Timer in vb.net Console Application


Getting 'E/RecyclerView: No adapter attached; skipping layout' in Kotlin tabbedActivity

Question: Hi I am beginning with Kotlin and tried to create tabbedActicity with parsed list. I am getting data with retrofit from google APIs.
Then I try to pass it to recycleView.
I tried many ways, but I keep getting error: E/RecyclerView: No adapter attached; skipping layout
Corresponding textView is present in score_row.xml layout and RecyclerView in thirdtab.xml layout.
thirdTabFragment.kt :
class thirdtabFragment : AppCompatActivity() {

    private lateinit var binding: ThirdtabBinding
    override fun onCreate(savedInstanceState: Bundle?){
        super.onCreate(savedInstanceState)

        binding = ThirdtabBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        val apiInterface = APIClient.client.create(ApiInterface::class.java)

        val call = apiInterface.getScore()
        call.enqueue(object : Callback<List<Item>> {
            override fun onResponse(call: Call<List<Item>>, response: Response<List<Item>>) {
                Log.d("Success!", response.toString())
                showContenders(response.body()!!)
            }

            override fun onFailure(call: Call<List<Item>>, t: Throwable) {
                Log.e("Failed Query :(", t.toString())
            }
        })
    }

    private fun showContenders(contenderList: List<Item>) {

        binding.recyclerView.apply{
            layoutManager = LinearLayoutManager(this@thirdtabFragment)
            adapter = ScoreAdapter(contenderList)
        }
    }

ScoreAdapter.kt :
class ScoreAdapter(private val contenderList: List<Item>) : RecyclerView.Adapter<ScoreAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.score_row, parent, false)
        return ViewHolder(view)
    }

    override fun getItemCount() = contenderList.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val contender = contenderList[position]
        holder.contenderName.text = contender.contenderName
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
        val contenderName: TextView = itemView.findViewById(R.id.contenderName_tv)
    }
}

Answer: Attach the adapter sooner, in the onCreate method.
For that make contenderList in ScoreAdapter public
var contenderList = listOf<Item>()
   set(value){
      field = value
      notifyDataSetChanged()
   }

then
//move this code to onCreate
adapter = ScoreAdapter()
binding.recyclerView.layoutManager = LinearLayoutManager(this)
binding.recyclerView.adapter = adapter

Then modify the onResponse method
override fun onResponse(call: Call<List<Item>>, response: Response<List<Item>>) {
   Log.d("Success!", response.toString())
   adapter.contenderList = response.body()!!

}

Comment: Thanks for response. I moved it up to onCreate function as you suggested and predefined List, but it still shows the same error.
Comment: What does logcat say?
Comment: After displaying json in log it shows two errors```2021-09-29 16:18:03.025 16827-16827/com.coza.typ E/Failed Query :(: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 5 column 6 path $.values[0]
2021-09-29 16:18:09.239 16827-16827/com.coza.typ E/RecyclerView: No adapter attached; skipping layout```
Comment: your model classes are probably not accurate. Generate them with json to kotlin classes extension for android studio.


Text format dropdown has dissapeared from edit article form

Question: There is something strange it happened at a certain time. I no longer can set the text format from article (node) edit because the Text format input has dissapeared.
I can configure them from Configuration page but no longer can choose them from edit mode.
I have all permissions over them set up ok.
Please if you have any suggestions help me up.

Strangely, this combo dissapeared from admin/structure/types/manage/CONTENT_TYPE/fields/body as well
I tried to alter the content type filter using a module but no luck:
<code>function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {

 $form['body']['und']['0']['#format'] = "full_html";

}
</code>
Comment: This normally happens when there is just an input format, or the user is allowed to use just an input format. Can you verify that is not the case?
Comment: No, there all 3 in place. Still not appears when I activate PHP input filter.
Answer: I have experienced this issue when a rich-text editor is enabled. In my experience, the input format box reappears when the rich-text editor is disabled.


2 threads handling sockets with weird behaviour

Question: I just finished my C# proxy containing 2 sockets (one client-socket receiving data from a certain client, one server-socket receiving data from a certain server).
- Method I)
The fully working receive/send procedure from a previous early-alpha version uses the following memory eating, quick and dirty method I won't implement again:
            while (true)
            {
                if (ClientSocket.Available > 0)
                {
                    // Received data from the game client
                    byte[] buf = new byte[ClientSocket.Available];
                    ClientSocket.Receive(buf);
                    Packet p = new Packet(buf);
                    Logger.Log(p.ID, LogType.PACKET);
                    // Forward re-encrypted data back to the official server
                    ServerSocket.Send(p.Encrypt());
                }

                if (ServerSocket.Available > 0)
                {
                    // Received Data from the official server
                    byte[] buf = new byte[ServerSocket.Available];
                    ServerSocket.Receive(buf);
                    Packet p = new Packet(buf);
                    Logger.Log(p.ID, LogType.PACKET);
                    // Forward re-encrypted data back to the game client
                    ClientSocket.Send(p.Encrypt());
                }
            }

- Method II)
The not working receive/send procedure from the actual version uses the following memory friendly method split into 2 threads:
class ClientReceiveThread
{
    public Thread T { get; set; }
    public ClientReceiveThread(Socket ClientSocket, Socket ServerSocket)
    {
        T = new Thread(() =>
        {
            try
            {
                while (ClientSocket.Available > 0)
                {
                    // Received data from the game client
                    byte[] buf = new byte[ClientSocket.Available];
                    ClientSocket.Receive(buf);
                    Packet p = new Packet(buf);
                    Logger.Log(p.ID, LogType.PACKET);
                    // Forward re-encrypted data back to the official server
                    ServerSocket.Send(p.Encrypt());
                }
            }
            catch (Exception e)
            {
                ExceptionHandler.Handle(e);
            }
        });
        T.Start();
    }
}

class ServerReceiveThread
{
    public Thread T { get; set; }
    public ServerReceiveThread(Socket ClientSocket, Socket ServerSocket)
    {
        T = new Thread(() =>
        {
            try
            {
                while (ServerSocket.Available > 0)
                {
                    // Received Data from the official server
                    byte[] buf = new byte[ServerSocket.Available];
                    ServerSocket.Receive(buf);
                    Packet p = new Packet(buf);
                    Logger.Log(p.ID, LogType.PACKET);
                    // Forward re-encrypted data back to the game client
                    ClientSocket.Send(p.Encrypt());
                }
            }
            catch (Exception e)
            {
                ExceptionHandler.Handle(e);
            }
        });
        T.Start();
    }
}

Method I) does insofar work that both Client- and Serversockets receive data, while method II) only receives data from the ClientReceiveThread.
Why does ServerReceiveThread in method II) not receive data? It's basically the same code as in the while(true) loop, only ported to a seperate thread.
Any suggestions or answers are highly appreciated.
Thanks in advance!
Comment: Unrelated to the actual question. Take a look into the Task Parallel Library in place of threads.
Answer: Fixed it by avoiding the "Available" property:
class ClientReceiveThread
{
    public Thread T { get; set; }
    public ClientReceiveThread(Socket ClientSocket, Socket ServerSocket)
    {
        T = new Thread(() =>
        {
            try
            {
                byte[] buf = new byte[1024];
                while (ClientSocket.Receive(buf) > 0)
                {
                    // Received data from the game client
                    Packet p = new Packet(buf);
                    Logger.Log(p.ID, LogType.PACKET);
                    // Forward re-encrypted data back to the official server
                    ServerSocket.Send(p.Encrypt());
                }
            }
            catch (Exception e)
            {
                ExceptionHandler.Handle(e);
            }
        });
        T.Start();
    }
}

class ServerReceiveThread
{
    public Thread T { get; set; }
    public ServerReceiveThread(Socket ClientSocket, Socket ServerSocket)
    {
        T = new Thread(() =>
        {
            try
            {
                byte[] buf = new byte[1024];
                while (ServerSocket.Receive(buf) > 0)
                {
                    // Received Data from the official server
                    Packet p = new Packet(buf);
                    Logger.Log(p.ID, LogType.PACKET);
                    // Forward re-encrypted data back to the game client
                    ClientSocket.Send(p.Encrypt());
                }
            }
            catch (Exception e)
            {
                ExceptionHandler.Handle(e);
            }
        });
        T.Start();
    }
}


probability of contingency table

Question: Mary is one of Doctor Brown's patients. She has conducted a home pregnancy test which has given a positive result. What is the probability that the pregnancy test used by Doctor Brown in his surgery will say Mary is pregnant given that the home test was positive?
Home pregnancy test is $85$% accurate
Doctor Brown pregnancy test is $95$% accurate
$20$ females are pregnant and $80$ females are not
*I don't know how to add the contingency tables to this question
Answer: Strictly speaking, you don't have enough information to solve this.  Here's how I'd approach it.
Let $X$ be the random variable which is $1$ if the home test is positive and $0$ otherwise.  Similarly let $Y=1$ if Dr. Brown's test is positive, and let $P=1$ if Mary is actually pregnant.  We want the conditional probability $Pr(Y=1\mid X=1)$.  Write
$$\begin{align}
 & Pr(Y=1\mid X=1)\\
 =\,&Pr(X=1 \wedge Y=1) / Pr(X=1)\\
 =\,&\frac{Pr(X=1 \wedge Y=1 \mid P=1)Pr(P=1) + Pr(X=1 \wedge Y=1 \mid P=0)Pr(P=0)}{
  Pr(X=1 \mid P=1)Pr(P=1) + Pr(X=1 \mid P=0)Pr(P=0).}
\end{align}$$
If we're willing to assume $X$ and $Y$ are independent given $P$, we can write $Pr(X=1 \wedge Y=1 \mid P=1)=Pr(X=1\mid P=1)\,Pr(Y=1\mid P=1).$  This may be a reasonable assumption if Dr. Brown's test works on different principles than the home test, but it might not.  Given that assumption, this gives an answer of
$$\frac{(0.85)(0.95)(0.2) + (0.15)(0.05)(0.8)}{0.85)(0.2)+(0.15)(0.8)}\approx 0.56$$

probability of contingency table


Problem with JS linked to an Ajax loaded page

Question: I am trying to load a form via ajax, the PHP callback that send the data to the Ajax request looks like this :
function group_form (){

        $node_type = 'group';
        $form_id = $node_type . '_node_form';
        $node = new stdClass();
        $node->type = $node_type;
        $node->title = 'helllooo';
        $node->language = LANGUAGE_NONE;
        $node->path = '';
        node_object_prepare($node);
        $return=drupal_get_form($form_id,$node);

    echo render($return);
}

I use to have a problem when using return instead of echo as mentioned in this Q, where the whole page was being sent via Ajax instead of just the form element. However now that i use echo all the script attached to that form do not get reloaded, witch cause problem as my form uses the date module with a jQuery popup calender, and infinite value fields witch need some Drupal JS in order to add multiple values without page reload.
So i wonder if there is a way around that, if not, anyone has anyidea of what script i should reload on the ajax succes callback in order to have my date module popup calendar and the drupal "Add more" function for infinite value field working ?
EDIT: I found that using Drupal.attachBehaviors(jQuery('#LoadedContent')); seems to be helping as it brings me from this

to this ,

though clicking on the "Add another item" Button still reload the page and i end up with this :
Thanks a bunch for the help.
Answer: Have a look at the Ajax Framework. It will make your life way easier. You can probably accomplish everything you're trying to do with out a single line of js.
Answer: You need to pass the JS settings that are created when the form is rendered:
function group_form (){

  $node_type = 'group';
  $form_id = $node_type . '_node_form';
  $node = new stdClass();
  $node->type = $node_type
  $node->title = 'helllooo';
  $node->language = LANGUAGE_NONE;
  $node->path = '';
  node_object_prepare($node);
  $form = drupal_get_form($form_id,$node);

  $response = render($form);

  $scripts = drupal_add_js();
  if (!empty($scripts['settings']))
  {
    $settings = '';
  }

  $response .= $settings;

  echo $response;
  drupal_exit();
}

Though personally I'd put the response in an array. So instead of this:
$response = render($form);

$scripts = drupal_add_js();
if (!empty($scripts['settings']))
{
  $settings = '';
}

$response .= $settings;

echo $response;
drupal_exit();

I'd use this:
$response['form'] = render($form);

$scripts = drupal_add_js();
if (!empty($scripts['settings']))
{
  $settings = '';
}

$response['form'] .= $settings;

drupal_json_output($response);
drupal_exit();

Your form will be available at data.form in the ajax.
You will also need to call the following after injecting your form into the page:
Drupal.attachBehaviors();