Combining results of z-test after multiple imputation

Question: I work with multiple imputed data and want to compare two proportions of successes/failures using a z-test (one-tailed). Unfortunately, I don't know how to poole the results.
I created 50 complete (imputed) datasets and ran the comparisons resulting in 50 z-scores and p-values. I suppose that I cannot simply average these results but rather have to take the uncertainty of the imputation procedure into account.
What do I have to do to poole my results correctly?
Comment: If you have an estimate of the effect size (difference in proportions) and its standard error then you would use Rubin's rules to combine them. Is there any particular reason which leads you to prefer combining the $p$-values?
Comment: Thank you for your reply. I actually do not want to combine the $p$-values but combine the effect sizes and standard errors as you suggested. Unfortunately, I am not sure how to do so. I found this case
http://stats.stackexchange.com/questions/78479/how-to-run-chi-squared-test-on-imputed-data
- does the answer apply to my case as well?
I looked the procedure up in the original source from 1987 and citing Rubin it says that "More work is needed on this problem" (p. 102). Is this nevertheless still the way to proceed here?
Comment: As far as I know they are still the way to go. There is a site http://missingdata.lshtm.ac.uk/ dedicated to missing data which has many esources. Perhaps one of them will help you.
Comment: Thank you very much for your help. I found a way to get to a test statistic for the combined results. Maybe someone can approve the approach above or give me a hint for a better solution.
Comment: Why not post that as an answer? You are allowed to answer your own question. Then people can comment on the answer and vote on it.
Comment: Thank you very much, again! I did as you suggested. I'm new as a poster here so I really appreciate any advise.
Answer: I collected some resources and decided to stick with the following procedure - maybe this helps somebody in the future. As I am still not confident with my solution, I would appreciate any comments and/or advise.
Some background: I conducted a study with two groups, one control and one experimental group. My goal was to compare the proportions of successes of both groups, that is, I analysed the difference between the two proportions. In my control group, out of 60 people 21 were successful, 30 were not successful and 9 were missing (ignoring the missing, 41% were successful). In my experimental group, out of 55 people 27 were successful and 8 were missing (ignoring the missing, 57% successful).
At first, I wanted to do 50 z-tests in the 50 completed data sets but I realised, that with multiple imputation I won't perform 50 hypothesis tests (that's what I asked about in my question) but rather calculate the differences in proportions 50 times and afterwards test this difference. Here is how I did it:

I calculated the mean difference in proportions $diff_{mean}$ over all $m = 50$ imputed data sets, it's approximately $0.169$.
The variance for the difference in proportions in a single completed data set $i$ is calculated as

$$U_i = (p_{i} * (1 - p_{i}))* (\frac{1}{n_1} + \frac{1}{n_2})$$
($p_i$ being the 50 proportions of successes in the 50 data sets, regardless of the group; $n_1$ and $n_2$ are the group sizes)

I calculated the mean within-variance as $$\overline{U} = \frac{1}{m}\sum _{i=1}^{m} U_i = 0.008689644$$
I calculated the between-variance
$$B = \frac{1}{m - 1}\sum _{i=1}^{m} (diff_i - diff_{mean})^2 \\
= \frac{1}{50 - 1}\sum _{i=1}^{50} (diff_i - 0.169)^2 \\
= 0.001116486$$
where $diff_i$ are the 50 differences of the proportions of the 50 single data sets.
I calculated the total variance as $$T = \overline{U} + (1 + \frac{1}{m}) * B = 0.00982846$$
The relative increase in variance was calculated as

$$r = \frac{(1 + \frac{1}{m}) * B}{\overline{U}} = 0.1310543$$

The degrees of freedom where calculated as

$$v = (m - 1)(1 + \frac{1}{r})^2 = 3649.726$$

Finally, the test-statistic was calculated as

$$\frac{(diff_{H_0} - diff_{mean})^2}{T}
= \frac{(0 - 0.1687879)^2}{0.003769771} = 2.974081$$
$diff_{H_0} = 0$ as the null hypothesis states there is no difference in proportions.
The test statistic is referred to an $F$-distribution with $1$ and $v$ degrees of freedom (Schafer, 1997), resulting in a $p$-value of $0.08469283$.
For reference: The $p$-value of my complete case analysis ($n = 98$) was $~ 0.054$.
That's as far as I got. Here's the literature I used:
Marshall, A., Altman, D. G., Holder, R. L., & Royston, P. (2009). Combining estimates of interest in prognostic modelling studies after multiple imputation: Current practice and guidelines. BMC Medical Research Methodology, 9-57.
Rubin, D. B. (1987). Multiple Imputation for Nonresponse in Surveys. John Wiley & Sons.
Schafer, J. L. (1997). Analysis of Incomplete Multivariate Data. CRC Press.
Comment: It looks OK except that I think you may have missed out an exponent in step 6 where I think $(1 + \frac{1}{r})$ should be squared.
Comment: Yes, you are correct, thank you! I actually squared the term but missed it here.


Jquery Datables sorting_asc and sorting_desc not working

Question: I am using: jquery.dataTables.js from: https://datatables.net
Jquery Datables sorting_asc and sorting_desc are not working after me  apply drag drop in the rows.
someone can help me on this issue I have
jsfiddle:
http://jsfiddle.net/f7debwj2/9/
html:

      <select class="form-control" id="sel1">
        <option value="Filter by">Filter by country </option>
        <option value="All">All</option>
        <option value="China">China</option>
        <option value="EUA">EUA</option>
        <option value="Spain">Spain</option>
      </select>

        First name
        Place
         Order

jquery
$(document).ready(function() {
  var dt = $('#example').dataTable();
  dt.fnDestroy();
});

$(document).ready(function() {
  var url = 'http://www.json-generator.com/api/json/get/clmDuyndua?indent=2';
  var table = $('#example').DataTable({
    ajax: url,
    createdRow: function(row, data, dataIndex){
      $(row).attr('id', 'row-' + dataIndex);
    },
    rowReorder: {
       dataSrc: 'order',
    },
    columns: [
      {
         data: 'order'
      },{
         data: 'name'
      },{
         data: 'place'
    }]
  });
    table.rowReordering();

  $('#sel1').change(function() {
    if (this.value === "All") {
      table
        .columns(1)
        .search('')
        .draw();
    } else {
      table
        .columns(1)
        .search(this.value)
        .draw();
    }
  });
});

Answer: CAUSE
Unofficial old row reordering plugin forces sorting to be done only on the indexing column.
SOLUTION
Replace it with official RowReorder extension that doesn't have that limitation, see this example.
Remove table.rowReordering(); and include additional files files for RowReorder plugin.
Also RowReorder plug-in requires jQuery DataTables 1.10.8 or newer.
EXAMPLE
See updated example for code and demonstration.


Number of strings on the set N4 that are of length 10 and contain seven ones.

Question: Sample Question 10.
Let N4 = {1, 2, ..., 4}.
A) Calculate the number of strings on the set N4 that are of length 10.
B) Calculate the number of strings on the set N4 that are of length 10 and contain seven ones.
The answers are:
A) 1048576
B) 3240
I know A is 4^10, gives me 1048576
but i have no clue how to get B, any help, so i can plug it in on a calculator?
Comment: When you say "contain seven ones" do you mean exactly seven or at least seven?  The answer indicates exactly seven, per Rustyn, but you need to be clear.
Answer: Pretend your string of ten digits chosen from $\{1,2,3,4\}$ is 10 bins organized in a line.
Ten choose seven = 120 is the number of ways to place seven ones in 10 bins. Now the other entries can be 2,3, or 4 so this yields 3 possibilities for each of the three other bins. Hence $$3\cdot 3\cdot 3\cdot {10\choose 7} = 3240$$
Comment: Thank you, makes a bit more sense, Though, im not sure why it yields 3 possibilities for each of the three other bins

i mean if it was N4 = {1,2,3,4,5,6}
it would simply be the count of N4 - 1? so 5 possible?

3^3*(120) right?
Comment: 3 other possibilities for the other bins because none of the bins can have a 1


How to build qt .lib files out of .prl files

Question: I'm new to Qt. I'm under Win 10, 64bit, using Visual Studio 2019.
I installed Qt 5.15.1 a while ago to work on an open source project. Python and CMake are also installed. vcvarsall.bat was also executed.
Now I'm working on a new project where I need QtCharts. I found that QtCharts was not installed by default. So I installed QtCharts with the Qt MaintenanceTool.exe. After that, I was expecting to see the *.lib files added to the lib folder but what I see are added *.prl files.
What is the next step for me to get the *.lib files.
Answer: Well, I found the .lib files I was expecting are there in the lib folder. I'm not sure how and when they got there. I re-checked in the lib folder after I succesfully built Qt provided examples that use QtCharts within Qt Creator. The dates on the files are from back to September 2020, though. Like if the files had been copied from another folder or from an archive.
Anyway. My problem is solved.
Comment: The dates on those files are build dates. I'd also suggest that you forget about qmake and switch to cmake. You'll have a much easier time - such low level details will be of mostly no concern.


Connecting homomorphism of long exact sequence sends fundamental class to fundamental class of a boundary component

Question: I have the following homework problem.

Let $f\colon (M,\partial M)\to (M',\partial M')$ be a map between two
compact connected oriented $n$-manifolds such that $f\big|\partial M\to \partial
 M'$ is a homeomorphism. Then $\deg(f)=\pm 1$.

My idea is to use the long exact sequence of the pair $(M,\partial M)$ and $(M',\partial M')$. Since, $f\big|\partial M\to \partial M'$ is a homeomorphism $H_{n-1}(f)\colon H_{n-1}(\partial M)\to H_{n-1}(\partial M')$ is an isomorphism.
Now, if $\partial M$ is connected then $\partial M'$ is also connected and the connecting homomorphisms $\partial_n\colon H_n(M,\partial M)\to H_{n-1}(\partial M)$, $\partial_n'\colon H_n(M',\partial M')\to H_{n-1}(\partial M')$ send the fundamental classes $[M],[M']$ to the fundamental classes $[\partial M],[\partial M']$, respectively. So, $\partial_n, \partial_n'$ are isomorphisms. Finally, using naturality of connecting homomorphism we can say $H_n(f)\colon H_n(M,\partial M)\to H_n(M',\partial M')$ is an isomorphism. So, we are done in case $\partial M$ is connected.

But, I don't know how to deal with the case when $\partial M$ is not
connected.
Answer: Perhaps the point is that if we decompose the boundary into its components
$$\partial M = B_1 \cup \cdots \cup B_K
$$
then the image of the homomorphism
$$\partial_n : H_n(M,\partial M) \to H_{n-1}(\partial M) \approx H_{n-1}(B_1) \oplus \cdots \oplus H_{n-1}(B_K)
$$
is an infinite cyclic group, generated by the sum over $k$ of the fundamental class of each component $B_k$ with respect to the induced boundary orientation on $B_k$.
So in the context of your problem, $\partial_n$ and $\partial'_n$ will still be isomorphisms onto their images.
Comment: As far as multiplication by $p$ is concerned, all of the homomorphisms in question are abelian group homomorphisms, hence they are all $\mathbb Z$-module homomorphisms.
Comment: Thanks for your answer. So, you are saying this $H_n(M,\partial M)\cong \Bbb Z$ and $H_{n-1}(\partial M)\cong \Bbb Z^3$(assuming $k=3$), and if $\partial_n$ is the map $1\mapsto (1,1,1)$ then $\partial_n$ is the isomorphism between $\Bbb Z$ with $\big\{(\ell,\ell,\ell): \ell\in \Bbb Z\big\}$. But, the restriction map $f\big|\partial M\to \partial M'$  induces a map $H_{n-1}(\partial M)\to H_{n-1}(\partial M')$ which may look like this $(1,1,1)\mapsto (+1,-1,+1)$.
Comment: I am struggling why $(1,1,1)\mapsto (+1,-1,+1)$ is not possible? May be first I need to show $H_n(f)\colon H_n(M,\partial M)\to H_n(M', \partial M')$ is non-zero, say multiplication by $p\in \Bbb Z\backslash \{0\}$, and we are giving induced orientation on the boundary components. Is it true then that $f\big|B_i\to B_i'$ induces a map $H_{n-1}(B_i)\to H_{n-1}(B_i')$ which is again multiplication by $p$ for any $i=1,...,k$.
Comment: Ahh! sorry, it is diagram chase:  $\require{AMScd}$
\begin{CD}
 H_n(M,\partial M) @>\displaystyle\partial_n>> H_{n-1}(\partial M)=\oplus_{i=1}^kH_{n-1}(B_i)\\
@V f_* V V @VV \oplus_{i=1}^k f_{i*} V\\
H_n(M',\partial M') @>>\displaystyle \partial_n'> H_{n-1}(\partial M')=\oplus_{i=1}^kH_{n-1}(B_i')\\
\end{CD}

Let  $$\displaystyle\big(\oplus_{i=1}^k f_{i*}\big)\circ\partial_n\big([M]\big)=\big(\oplus_{i=1}^k f_{i*}\big)\big(\oplus_{i=1}^k[B_i]\big)=\oplus_{i=1}^k\varepsilon_i\cdot [B_i'],$$ where $\varepsilon_i\in \{+1,-1\}$.
Comment: Also,

 $$\partial_n'\circ f_*\big([M]\big)=\partial_n'\big(p\cdot [M']\big)=p\cdot \partial_n'\big( [M']\big)=p\cdot\oplus_{i=1}^k[B_i']=\oplus_{i=1}^kp\cdot[B_i'],$$ for some $p\in \Bbb Z$. Now, commutativity of diagram says, $$\oplus_{i=1}^k\varepsilon_i\cdot [B_i']=\displaystyle\big(\oplus_{i=1}^k f_{i*}\big)\circ\partial_n\big([M]\big)=\partial_n'\circ f_*\big([M]\big)= \oplus_{i=1}^kp\cdot[B_i']$$$$\implies\varepsilon_i=p\text{ for each }i=1,...,k.$$$$\implies \deg f=p\in \{+1,-1\}.$$ **Am I right?**


Redirect non-www to www giving me hundreds of 404's

Question: Thanks to anyone who can take a moment to look at this.
Recently I created a new section "subdomain" in my website and in this new folder I have  includes a Joomla CMS installation the url looks like this: http://www.example.com/subdomain/
In this folder I have a htaccess file to which I have added.
## No directory listings
# Redirect non-www to www:
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

When I try to access say http://example.com/subdomain/anytrailingstring then it's NOT redirecting me to http://www.example.com/subdomain/anytrailingstring as I expected, it is redirecting to http://www.example.com/anytrailingstring leaving out the /subdomain/ and this is of course a page that doesnt exist and therefore a 404.
This is a problem.
I do not have any directive in the root .htacces file except for this :
DirectoryIndex index.php
Options +FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Can someone perhaps see why the subdomain htaccess isnt redirecting to correctly? Did I miss something?
I am not good with htaccess at all, if anybody can help me I would really appreciate it.
Thanks!
Answer:
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

You need to use the REQUEST_URI server variable instead of the backreference ($1). The URL-path matched by the RewriteRule pattern (first argument) is relative to the current directory, so excludes the parent subdirectory (ie. /subdomain in your example).
Do it like this instead:
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

You will need to clear your browser cache since the erroneous (301 - permanent) redirect will have been cached by the browser. Test with 302 (temporary) redirects to avoid potential caching issues.
However, a couple of questions:

Why are you not using HTTPS? (You are redirecting to HTTPS in the parent .htaccess file - but this is now being overridden by the mod_rewrite directives in the subdirectory.)
Why not include this in the parent .htaccess file?

UPDATE: So, taking the above points into consideration... if you want to move this rule to the parent .htaccess file in the root then have it like this:
DirectoryIndex index.php
Options +FollowSymLinks
RewriteEngine on

# Redirect non-www to www (and HTTPS)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Redirect HTTP to HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

The order of the directives is to ensure there is only ever at most 1 redirect (assuming you are not implementing HSTS).
You were unnecessarily duplicating the RewriteEngine directive (so I removed the second instance).
The RewriteBase directive was not being used.
The capturing subgroup in your HTTP to HTTPS rule was not required. ie. ^ is better than ^(.*)$ in this instance.

Aside:.

...a new section "subdomain" in my website and in this new folder I have includes a Joomla CMS installation the url looks like this: http://www.example.com/subdomain/

This is a subdirectory, not a "subdomain".
This is a "subdomain":
http://subdomain.example.com/

Comment: I agree as to subdirectory and yes, you are right, thats should be https.  It was picked up from a  post from 12 years ago.  Question: This I should now put in the subfolder or in the root htaccess file? I guess you imply it  probably should be in the root. Right?
Comment: "This I should now put in the subfolder or in the root htaccess file?" - Well, I wondered if you had a specific requirement for why this should be the subdirectory? However, ordinarily this should be in the root `.htaccess` file since you normally want to enforce www on the entire site. I've updated my answer.
Comment: Thank you so much.  For some reason it doesnt do anything in the root htacess but I added it to the folder and it works fine!  Have a great Sunday
Comment: "it doesnt do anything in the root htacess" - Do you have other directives in the subdirectory `.htaccess` file? If so, then the directives in the parent `.htaccess` file might be getting overridden (and one reason why you might include the directives in the subdirectory instead). Otherwise, they really should work in the root directory.


How to separe these values?

Question: I've been trying to do this around 2 hours and my brain is about to explode.
I have a table called DEPARTMENTS and a column called TOTAL_ROOMS but each DEPARTAMENT have their own room size but I don't know how to show the total rooms of each department.
It should look something like this
DEPARTMENT NAME ||  TOTAL DEPARTMENTS || TOTAL DEPARTMENTS WITH ONE ROOM || TOTAL DEPARTMENTS WITH TWO ROOMS || TOTAL DEPARTMENTS WITH THREE ROOMS

EXAMPLE A       ||          10        ||          5                      ||           3                      ||             2

EXAMPLE B       ||           8        ||          2                      ||           4                      ||             2

I Have tried using a WHERE , IN, DISTINCT function but I'm not very professional doing this (I'm still learning) :/ This is what I've done and the column name about rooms size is TOTAL_ROOMS and I'm trying to SUM every ROOM that has "1 room size" then SUM every ROOM that has "2 room size" and shows the result :/
SELECT TOWER.EDI_NAME_TOWER AS "DEPARTMENT NAME",
COUNT(DEPARTAMENT.NRO_DEPARTAMENT) AS "TOTAL DEPARTMENTS"
FROM DEPARTAMENT
JOIN TOWER
ON DEPARTAMENT.ID_TOWER= TOWER.ID_TOWER
GROUP BY TOWER.EDI_NAME_TOWER;

Comment: Can you provide a sample of the original data from `DEPARTMENT` and `TOWER` as well as the expected output you want to get? Ideally in the format of a http://sqlfiddle.com/
Comment: What data inside `NRO_DEPARTMENT` column? Room size?
Comment: Please explain how you know how many rooms there are for *any* department.  Why are you calling the "tower" name the name of the department?
Answer: I am not clear what your data looks like so here's a guess where conditional aggregation (sum(case when...)) is used to separate the columns.
drop table if exists t,t1;

create table t (ID_TOWER int,NRO_DEPARTAMENT int);
create table t1(id_tower int, EDI_NAME_TOWER varchar(3));

insert into t values
(1,1),(1,1),(1,1),(1,1),(1,1),(1,2),(1,2),(1,2),(1,3),(1,3),
(2,1),(2,1),(2,1),(2,1),(2,2),(2,2),(2,3),(2,3),(2,3),(2,3);

insert into t1 values
(1,'aaa'),(2,'bbb');

SELECT TOWER.EDI_NAME_TOWER AS "DEPARTMENT NAME",
        count(DEPARTAMENT.NRO_DEPARTAMENT) AS "TOTAL DEPARTMENTS",
        sum(case when DEPARTAMENT.NRO_DEPARTAMENT = 1 then 1 else 0 end) '1 room',
        sum(case when DEPARTAMENT.NRO_DEPARTAMENT = 2 then 1 else 0 end) '2 room',
        sum(case when DEPARTAMENT.NRO_DEPARTAMENT = 3 then 1 else 0 end) '3 room'
FROM t DEPARTAMENT
JOIN t1 TOWER
ON DEPARTAMENT.ID_TOWER= TOWER.ID_TOWER
GROUP BY TOWER.EDI_NAME_TOWER;

+-----------------+-------------------+--------+--------+--------+
| DEPARTMENT NAME | TOTAL DEPARTMENTS | 1 room | 2 room | 3 room |
+-----------------+-------------------+--------+--------+--------+
| aaa             |                10 |      5 |      3 |      2 |
| bbb             |                10 |      4 |      2 |      4 |
+-----------------+-------------------+--------+--------+--------+
2 rows in set (0.00 sec)

If this is not what your data looks like please add sample data as text to the question. If you have more rooms keep adding aggregations, if that becomes unmanageable consider dynamic sql.
Answer: Thanks for the answers and sorry for the delay.
@P.Salmon you gave me an idea but i tried and i even failed… This is what i need to show
IMAGE
this is my code
SELECT EDIFICIO.EDI_NOMBRE_EDIFICIO AS "NOMBRE EDIFICIO",
COUNT(DEPARTAMENTO.NRO_DEPARTAMENTO) AS "TOTAL DEPTOS",
SUM(TOTAL_DORMITORIOS) AS "TOTAL DEPTOS 1 DORMITORIO", -- fix
COUNT(TOTAL_DORMITORIOS) AS "TOTAL DEPTOS 2 DORMITORIO", -- fix
COUNT(TOTAL_DORMITORIOS) AS "TOTAL DEPTOS 3 DORMITORIO", -- fix
COUNT(TOTAL_DORMITORIOS) AS "TOTAL DEPTOS 4 DORMITORIO", -- fix
COUNT(TOTAL_DORMITORIOS) AS "TOTAL DEPTOS 5 DORMITORIO" -- fix
FROM DEPARTAMENTO
JOIN EDIFICIO ON DEPARTAMENTO.ID_EDIFICIO= EDIFICIO.ID_EDIFICIO
GROUP BY EDIFICIO.EDI_NOMBRE_EDIFICIO
ORDER BY EDI_NOMBRE_EDIFICIO;

I'm pretty sure it can be done using SUM ! and i was trying this but i don't know how to sum every value and show the result final per department
SELECT ID_EDIFICIO, NRO_DEPARTAMENTO, TOTAL_DORMITORIOS
FROM DEPARTAMENTO
WHERE TOTAL_DORMITORIOS IN (1,2,3,4,5);

EDIT ---- THANKS P.Salmon i just figured out the code
SUM(CASE WHEN TOTAL_DORMITORIOS = '1' THEN 1 ELSE 0 END) AS "TOTAL DEPTOS 1 DORMITORIO",

This sum every room per department!

How to separe these values?


Como Trabalhar com objeto em javascript

Question: Bem estou tento dificuldades para entender como trabalhar com um objeto que vem do meu controller no javascript, já realizei alguns testes para ter certeza que essa informação subiu de forma correta para o view porem, não entendi como trabalhar essa informação no javascript se alguém poder ajudar ficarei grato.
segue o controller que utilizo para subir o lista de objeto
<code>  @RequestMapping(value = "/show/{id}", method = RequestMethod.GET)
    public ModelAndView viewPesquisar(@PathVariable("id") Long id, ModelMap
    model, HttpServletRequest request) {

    LOGGER.debug(" O id a ser consultado é {}", id);

    List<Ito> optional = itoService.findByIdFetchAll(id);

    if (optional.isEmpty()) {

        LOGGER.debug(" Não foi possivel localizar o Tipo com o Id:{}", id);

        throw new BusinessException("Não foi possivel Localizar o Tipo de Projeto");
    }

    List<Ito> listaCompletaItos = itoService.findByIdFetchAll(id);

    model.addAttribute("listaCompletaItos", listaCompletaItos);

    return new ModelAndView(REQUEST_MAPPING_PAGE_SHOW_ITO);
}
</code>
eu mando a informação para o view através do ModelAndview não sei dizer se é a melhor forma nesse caso.
Comment: Não tem como você ter um `controller no javascript` uma vez que [tag:javascript] é uma linguagem client-side executada pelo Browser.
Comment: certo a questão é como posso trabalhar essa lista dentro do javascript
Answer: Voce tem duas formas de fazer isso! Uma é escrevendo essa informacao no header da tua página como uma variável JavaScript e a outra é puxando via ajax do JavaScript para o teu controler! Só depois de decidires qual vais usar e que posso lhe ajudar

Como Trabalhar com objeto em javascript


Variance of MLE of a function of bernoulli parameter

Question: Given $m$ i.i.d. Bernoulli( $\theta$ ) r.v.s $X_{1}, X_{2}, \ldots, X_{m},$ I'm interested in finding  the variance (Not asymptotic)  of estimator of $(1-\theta)^{1 / k},$ when $k$ is a positive integer.
Optimizing the likelihood function implies $\hat{\theta}=\sum_{i=1}^{m} \frac{X_{i}}{m} .$ Thus, using the invariance property, the required MLE estimator is $\left(1-\sum_{i=1}^{m} \frac{X_{i}}{m}\right)^{1 / k}$.
I am wondering is there a way of finding the variance of this estimator?
I know that asymptotically MLE is efficient and achieves CRLB. Thus, asymptotic variance is easy to calculate using Fisher information.
I am interested in finding the variance in the non-asymptotic case? Is it even possible? Any tips are appreciated.
Answer: First note that $S = m\hat{\theta} \sim Binomial(m,\theta)$. We are seeking to find:
$$Var(\hat{\theta}) = E[ (1-\hat{\theta})^{2/k}] - E[ (1-\hat{\theta})^{1/k}]^2.$$
Using the fact that $\hat{\theta} = S/m$ and the pmf of $S$ is $f_S(s) = {m \choose s} \theta ^s (1-\theta)^{m-s},$ we can write:
$$Var(\hat{\theta}) = \sum_{j=0}^m(1-j/m)^{2/k}f_S(j)- [\sum_{j=0}^m(1-j/m)^{1/k}f_S(j)]^2$$
$$Var(\hat{\theta})  = \sum_{j=0}^m(1-j/m)^{2/k}{m \choose j} \theta ^j (1-\theta)^{m-j} - [\sum_{j=0}^m(1-j/m)^{1/k}{m \choose j} \theta ^j (1-\theta)^{m-j}]^2.$$


Which is the best php extension for reading xml file?

Question: Which is the best php extension for reading xml file from absolute path?
The xml file is simple:
<code><?xml version="1.0" encoding="utf-8"?>
<online>
    <coountry value='us'>
        <user hours='10' name='user1' id='1' />
        <user hours='9' name='user2' id='2' />
        <user hours='8' name='user3' id='3' />
    </country>
</online>
</code>
From the xml I will need to loop through the country tag and use each user tag attributes.
Comment: all PHP's XML extensions by default support reading a file from a *file* path (that is what you mean, "absolute path" means something different). You can use whichever XML library you like.
Comment: You mean a file path? Using what tool / library? Can you show some code?
Comment: I mean like reading file from absolute path /home/user/www/system/online.xml. I don't have any cause I can't figure out how to properly read the xml.
Comment: What do you want to do with the XML file?
Comment: @Pekka, thank you for clearing it out! :)
Answer: It all depends on how complex or large the XML file is. If it's a simple file or is relatively short I'd go for SimpleXML. Can you post a sample of the XML? You might get a better answer then.
Answer: What do you want to do with the xml?
The way to handle complex XML documents is:
<code>$doc = new DOMDocument();
$doc->load('/home/user/www/system/online.xml');
</code>
However, without knowing what you intend to get from the XML, it is hard to suggest the right parser.
Comment: Edited the main post adding the xml and what i'll do with it.


Solving Wave Equation on $0 < x < L$ with initial condition containing both sine and cosine terms

Question: I am trying to solve the wave equation as follows:
$$u_{tt} = u_{xx} \,\,\,\,\,\,\,\, 0 < x < L$$
$$u(0,t) = u(L,t)$$
$$u_x(0,t) = u_x(L,t)$$
$$u(x,0) = sin\bigg(\frac{2\pi x}{L}\bigg) + cos\bigg(\frac{4\pi x}{L}\bigg)$$
The issue I'm running into is somehow I end up with $-1 = 1$ and I'm not sure what I'm doing wrong.
I use separation of variables and get
$$X(x) = a\,\text{cos}(\lambda x) + b\,\text{sin}(\lambda x).$$ The boundary conditions for $u$ imply $X(0) = X(L)$ so I set these equal to each other and get that the coefficient $a$ is $$ a = \frac{b\,\text{sin}(\lambda L)}{1 - cos(\lambda L)}.$$ This then yields
$$X(x) = \frac{b\,\text{sin}(\lambda L)}{1 - cos(\lambda L)}\,\text{cos}(\lambda x) + b\,\text{sin}(\lambda x)$$
I'm going to omit all the calculations because it's kind of messy, but my process is as follows:
The boundary conditions also imply $X'(0) =  X'(L)$ so I plug each one into the derivative of X, $X'(x)$. Then I set these equal to each other and solve. I end up with $-1 = 1$. This is obviously incorrect. Can someone point me in the right direction? Also obviously didn't even start to solve for $T(t)$ yet.
Comment: Don't use separation of variables. Use the fact that $u(x,t)=f(x+t)$ will satisfy your wave equation for any twice differentiable function $f$ . So $u(x,t)=u(x+t,0)$.
Comment: @WW1 There's more than one method. SoV is perfectly valid.
Answer: You were going in the right direction. The mistake is probably in your algebra somewhere. Since you didn't show your work (please edit to add that in if you can), I can't say more.
The corresponding derivatives are
\begin{align}
X'(0) &= \lambda b \\
X'(L) &= -\frac{\lambda b\sin(\lambda L)}{1-\cos(\lambda L)}\sin(\lambda L) + \lambda b \cos(\lambda L)
\end{align}
Assuming $b \ne 0$, one solution is obviously $\lambda = 0$. If $\lambda \ne 0$, the equation reduces to
$$ 1 = -\frac{\sin^2(\lambda L)}{1-\cos(\lambda L)} + \cos(\lambda L) $$
Going through the steps
$$ 1-\cos(\lambda L) = -\sin^2(\lambda L) + \cos(\lambda L)\big(1-\cos(\lambda L)\big) $$
$$ \implies 1 - \cos(\lambda L) = \cos(\lambda L) - 1 $$
$$ \implies \cos(\lambda L) = 1 $$
$$ \implies \lambda L = 2n\pi, \quad n = 0,1,2,\dots $$
Using the property of linear equations, we obtain a series solution:
$$ u(x,t) = a_0(c_0 + d_0 t) \\ + \sum_{n=1}^\infty \left[a_n \cos\left(\frac{2n\pi}{L} x\right) + b_n \sin\left(\frac{2n\pi}{L} x\right)\right]\left[c_n \cos\left(\frac{2n\pi}{L} t\right) + d_n \sin\left(\frac{2n\pi}{L} t\right)\right] $$
We can sort of simplify this by break up the terms and renaming the constants
$$ u(x,t) = A_0 + B_0 t + \sum_{n=1}^\infty \left[A_n \cos\left(\frac{2n\pi}{L} x\right) + B_n \sin\left(\frac{2n\pi}{L} x\right)\right]\cos\left(\frac{2n\pi}{L} t\right)\\ + \left[C_n \cos\left(\frac{2n\pi}{L} x\right) + D_n \sin\left(\frac{2n\pi}{L} x\right)\right]\sin\left(\frac{2n\pi}{L} t\right)$$
Then, you'll need to solve 2 different Fourier series
\begin{align}
u(x,0) &= f(x) = A_0 + \sum_{n=1}^\infty \left[A_n \cos\left(\frac{2n\pi}{L} x\right) + B_n \sin\left(\frac{2n\pi}{L} x\right)\right] \\
u_t(x,0) &= g(x) = B_0 + \sum_{n=1}^\infty \frac{2n\pi}{L}\left[C_n \cos\left(\frac{2n\pi}{L} x\right) + D_n \sin\left(\frac{2n\pi}{L} x\right)\right]
\end{align}
Comment: Was just trying to do out the work again to show you guys, realized there's definitely an algebra error somewhere. I just got close to your answer while I was doing out the work (got to the point of being able to solve for $\lambda$ so I probably was rushing and made another mistake. I can still post the work for you if that will be helpful for you to help me.
Comment: @math Thanks. That's up to you. Try doing it again to see if you can follow my steps. Also, I believe you need a second initial condition, i.e $u_t(x,0)$, to obtain the full solution
Comment: Just did out the work again and got your answer for $\lambda$. This problem was from a worksheet from class so we don't have solutions, but I am looking at the sheet right now and that's what it says. I'm prepping for an exam (today, technically...). Also I am sure you are right about the second initial condition. I think there might be an error with that problem (perhaps copied and pasted from the previous problem which is the diffusion equation with those same conditions.) Guess I can't really finish the problem!
Comment: I added some more info on the last step. See if you can solve it with $u_t(x,0)=0$.


No response received in startscan method at WifiManager in Android 8 Oreo

Question: According to official Android documentation, the method startScan  at WifiManager is deprecated in API level P. However I am trying to use this method in API level 26 (previous to P) without success. I have developped an app which requires the scanning of the WiFi networks, if the user agree with the required permissions, and this behaviour is paramount for the appropriate functioning of the app. However I do not receive any response when calling the startScan method. ¿Can anyone help me to solve this problem or find an alternative solution?
This is a link to the documentation.
https://developer.android.com/reference/android/net/wifi/WifiManager.html#startScan()
Cheers
EDIT:
This is the code to start de scannig process:
public boolean startScan() {
   WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
   if (!wm.isWifiEnabled()) {
     try {
       wm.setWifiEnabled(true);
     } catch (SecurityException e) {
       Log.w(LOG_TAG, "Error enabling wifi", e);
       return false;
     }
   }
   boolean started = wm.startScan();
   Log.d(LOG_TAG, "Scan started? " + started);
   return started;
}

And this is the BroadcastReceiver that receives the result of the scan. It works except in Android 8 with targetSdkVersion 26+
public class InOutWifiScanResultsReceiver extends BroadcastReceiver {
   private static final String LOG_TAG = "ScanResults";

   @Override
   public void onReceive(Context context, Intent intent) {
     super.onReceive(context, intent); // Never called in Android 8 and targetSdkVersion 26+
     List<ScanResult> results = getWifiResults(context);
     Log.d(LOG_TAG, "Received results (" +  results.size() + " AP's)");
   }

   private static List<ScanResult> getWifiResults(Context context) {
      WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
      try {
        return wm.getScanResults();
      } catch (SecurityException e) {
        return new ArrayList<>();
      }
   }
}

In the Manifest we use the followint permissins and the BroadcastReceiver declared:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

 <receiver
    android:name=".InOutWifiScanResultsReceiver"
    android:exported="false">
    <intent-filter>
        <action android:name="android.net.wifi.SCAN_RESULTS"/>
    </intent-filter>
 </receiver>

The location permission is required in runtime so I'm sure it is allowed. I'm also true that location is active (GPS level).
The BroadcastReceiver works fine because compiling with targetSdkVersion =  25 or less every works as expected and scans are received. I have also tested with android:exported="true" , but it doesn't have influence on the results.
I will grateful with your help.
Answer: In Android 8 or higher the implicit BroadcastReceivers declared via Manifest are no longer send nor received due to performance reasons (this is an optimization introduced in Android 8 which limits background execution). There are some exceptions which are listed here, but android.net.wifi.SCAN_RESULTS action isn't an exception, so in Android 8+ you can't register a android.net.wifi.SCAN_RESULTS action to wait for ScanResults in the Manifest (actually you can, but you'll receive nothing).
This happens if your targetSdkVersion is 26 (Android 8 Oreo) or higher, but if you declare in your Gradle file a targetSdkVersion 25 or lower this optimization will not run for your app and your implicit Intents registered through Manifest will work as expected.
To get it work in Android 8 Oreo with a targetSdkVersion 26+ you have to register it through your Application Context.
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.wifi.SCAN_RESULTS");
context.registerReceiver(new InOutWifiScanResultsReceiver(), intentFilter);

But be aware, this kind of registration requires the app being running, so when your app is stopped you will not receive this BroadcastReceiver.
P.S: Your code is correct, but you didn't keep in mind this Android 8 limitation.


How to get path of different express route

Question: Lets say I have the following routes in my express app:
router.get('/register', registrationController.register);

router.get('/confirm', registrationController.confirm);

In some service I would like to retrieve the absolute url of the confirm route.
Instead of doing something like this:
const url = req.protocol + '://' + req.get('host') + '/confirm'

Is there an option to retrieve routes in some way like this:
const express = require('express');
const router = express.Router();

const confirmRoute = router.confirm;

// Do something with the route name instead of typing it statically as a string

What can I do differently without installing another dependency?
Comment: Not a global.  You need to export the value, either from your route module or put constants in a shared module that anyone who wants them can import. That's how you maintain proper modularity in nodejs.
Comment: It's not clear to me exactly what you're asking, but perhaps one of `req.path`, `req.baseUrl` or `req.originalUrl` would be useful.  See [express doc](http://expressjs.com/en/4x/api.html#req.originalUrl) for what those are.
Comment: @jfriend00 Thank you for your answer. I updated the question. In php frameworks its common to not statically type routes but rather to retrieve them like above. If the route path changes there will be in issue.
Comment: So, is `req.path` what you're looking for?  That will be what matched the router specification for the current route.  There is no such thing as `router.confirm` to indicate some other route's path.  You can define that yourself as in `const confirmRoute = "/confirm"` and just use that in both the router definition and some place else you want to access it.
Comment: Okay, the latter is what I am looking for, thank you! Could you give me a hint on how to access a ```const confirmRoute = "/confirm"``` in a different service than the router? I was thinking some global variable but I don't really know how to realize that. Do you have any tipps?
Comment: Makes perfectly sense, appreciate your help, thanks!
Answer: Define a constant that you can use in multiple places.
const confirmRoute = "/confirm";

Then, you can use that in multiple places.  If those places are in separate files, then you can either export it from the file where it was declared and import in the other.  Or, you can create a shared constants file and export it from there and both other files that want to use it can import it from that shared file.
Alternately, you don't even have to expose the route itself.  You can keep that private to the file where they route is defined and then export and function that either retrieves the route path or just executes the redirect for you.


Alias to forward mail to all addresses for a domain using Exim

Question: I'm using Exim v4.91 in a CentOS 7 server hosting more than one domain and I'd like to set up a group address/alias to forward mail messages to all addresses of a given domain (one for every domain). I.e. if I send an email to firstname.lastname@example.com it would be sent to *@example.com, all email to email@example.com should be sent to *@example2.com, etc.
I've found how to set up catch-all aliases but what I want to achieve is the opposite, not an alias to receive all incoming messages but a forward-to-all-accounts all incoming messages.
Answer: This all depends on whether the source of your domain addresses can be enumerated or not. If the account information is stored in SQL, LDAP or a plain text file then it should be possible. You'd have to set up a redirect router with a data = directive consisting of a string expansion that returns a comma-separated list of accounts. That string expansion might use ${lookup ldapm{<query>}} for LDAP, ${lookup mysql{<query>}} for SQL or ${readfile{<filename>}{,}} for a plain text file. The LDAP and SQL will likely require further processing of the output, for instance replacing the newline record separator by the comma required by the redirect router.
Without knowing where your account information is stored I can't give you any more explicit information, sorry. I don't think the generic linux PAM interface can be enumerated, so if your accounts are just regular linux users then I'm afraid you're out of luck.
Answer: A simple way of doing it on a per account basis, if you are using a text config file, e.g.
Add to the top of ROUTERS something like this:
domain_aliases:
   driver = redirect
   allow_fail
   allow_defer
   data = ${lookup {$domain} lsearch {/usr/exim/exim.domainalias} {$local_part@$value} }

Where /usr/exim/exim.domainalias contains something like this:
example.net: example.com
example.org: example.com
example.biz: example.com

Each line corresponds to a source domain and a target domain.
You'll sill have to figure out how to expand the account list though, if this is not enough.


Slack Integration with Cloud Composer - broken DAG No module named 'slackclient'

Question: We are having trouble integrating slack with Cloud composer. The SlackAPIPostOperator has slackclient dependency, which we installed directly on the worker nodes using below:
sudo python3 -m pip install apache-airflow[slack]

This installs slack 1.3.2.
We had to install on the worker nodes since the pypi package install option on the Cloud composer UI was repeatedly timing out.
The module import statements work fine on the worker nodes. However, composer still reports broken DAGs with the error message: Broken DAG: [/home/airflow/gcs/dags/composer-slack-test.py] No module named 'slackclient'
The Composer version is:  composer-1.16.0-airflow-1.10.15
Any help is appreciated.
Thanks!
Comment: Have you tried installing dependencies directly to the composer? https://cloud.google.com/composer/docs/how-to/using/installing-python-dependencies#install-package
Comment: As I mentioned in my post, it did not work, it was repeatedly timing out. Hence I installed on the worker nodes.
Answer: If the package installation times out, it likely means there was a package conflict when Cloud Composer attempted to build the worker/scheduler images. To troubleshoot this, you should look at the build logs after the update operation times out, and look for the output of pip check. There, you will be able to identify which packages were unable install due to version constraints.
Packages installed on worker nodes will be not be accessible from workflows because the Airflow worker/scheduler run as Kubernetes pods. You should not manually install packages onto nodes or worker/scheduler pods, because they can be replaced at any time.


How to show one node from particular content type into all other pages?

Question: I have content type and have few fields and I want to display each node from that content type into basic page.
In this i want to choose which node i want to display on which page.  Like i want to show node1 from A content type into Basic Page 1.  and node2 from A into basic page 2.
Any idea?
Comment: *I want to display each node from that content type into basic page.* So, if that  content type will have 50 nodes, you want to show all those in basic page. Can you please be specific in your question, so Answerer can provide the best solution.
Comment: @CodeNext: i want to display one node of that content type into basic page.  Admin will use which node he wants to display on which page
Answer: You can use Entity Reference Module

A generic entity reference field Four widgets: Two implemented on top
  of the Options module (Select and Radios/Checkboxes), Two autocomplete
  widgets (one with one text field per entry, one tag-style with
  comma-separated entries in the same text field) Two formatters: A
  "Label" formatter, with optional link that displays the label of the
  referenced entity (the node title, the user name, etc.) A "Rendered
  entity" formatter, that renders the references entity using a
  configurable view mode
Comment: i don't want to link into another page.. i want to display on same page.. can u tell me how to do that?
Comment: You can use View module. Create a block with referecened nodes and show call that block in node template
Comment: Can you please explain this little more
Comment: Add entity refrence or node reference on basic page content type and add refrence of content which you want to display on that basic page.


How to create sql using IN condition include two columns (doma)

Question: I use Doma.
then, I want to create sql like below.
select * from
table
where (col1, col2) in (('val1', 'val2'), ('val3', 'val4'));

can I do this? Do you know anything to solve it ?
thanks.
Answer: Yes, you can do that with Doma Criteria API.
See my example:
https://github.com/nakamura-to/getting-started/blob/in-condition/java-8/src/main/java/boilerplate/java8/repository/EmployeeRepository.java#L31-L32
The above example issues the following sql statement:
select t0_.id, t0_.name, t0_.age, t0_.version from Employee t0_ where (t0_.id, t0_.version) in ((1, 0), (2, 0))

Comment: Thanks a lot! I found Qiita article that you wrote. I gonna see that one too!


JAWS 2018: Making a select/drop-down "clickable"

Question: I'm working on a website project and fixing accessibility defects.
Constraints of my setup:

Operating System is Windows 7/10
Browser is Internet Explorer 11
Accessibility software is JAWS 2018.1804.26

I have no control over these contraints, so please do not suggest any solutions for any other setup.

I have a defect that says that an HTML <select> (drop-down) should be listed in the "clickable" elements by JAWS. (This is the modal dialog shown when pressing the Ins+Ctrl+/ keyboard chord.) I have encountered this kind of issue before with other HTML element types, and I have fixed those with a combination of the following:

Add an onclick handler (in my case, an empty function)
Add a value to the aria-label attribute (in my case, dynamically)

When attempting to do those steps in the current defect, I can make the <select> show up in the "clickable" modal dialog, but no text is listed (I'm guessing it's "reporting" an empty string). This is in spite of having a value for aria-label.

Other item of note:

The <select> in question is inside of a  that is inside of a 1

It looks like this:

          <select> ... options ... </select>

I tried altering the above code like this:

          <select onclick="emptyHandler" aria-label="Some text">
            ... options ... </select>

function emptyHandler() {
    /* This function is empty by design     */
    /* Its function is to expose an element */
    /* as a clickable element to JAWS, when */
    /* otherwise JAWS would ignore it.      */
}

Making the above modifications DID add the element to the list of clickable elements, but with no text displayed. You can see the extra row, and you can highlight it, but it's some amount of just blank spaces/text (or maybe just nothing).
1  I did not write the UI for this page, and I have no desire (nor am I authorized) to re-write the entire page. I suspect that wrapping controls inside of  elements does some really wonky things when interacting with JAWS, but I can't fix that part of this problem.

I have a few questions around this, since I cannot find great documentation on exactly how this is supposed to work:

Is there any detailed documentation on how this is supposed to work? My searches on Freedom Scientific's website as well as on Mozilla's and around the web has produced some information, but I'd love a central place where I could find these kinds of answers. In particular, there doesn't seem to be a consistent, canonical definition for what a "clickable" element is. Some elements seem to be treated as "clickable" be default, whereas adding a custom onclick handler seems to allow ANY element to be added to that list. Which leads me to...
How - exactly - does the "clickable" modal dialog work in JAWS? I think I have figured out how to get an element into this list, but what it displays seems slightly inconsistent. Which leads me to...
What is supposed to show up in that modal dialog? In prior testing, it appeared that the text that is displayed is the value in the aria-label attribute, so why isn't that working here?
Is it an inappropriate expectation that a <select> element would show up here? I can always kick this defect back for this reason, but I don't want to do so unless I'm sure that this is the correct course of action.
Comment: Could you include a complete code sample? Not sure what you're asking for if you don't have the authority to amend the code
Comment: How do you get to the "clickable" dialog in JAWS?  If you use Ins+F3, you get a list of various dialogs you can display.  One of them is for "controls", which includes comboboxes.  Is that what you're calling the "clickable" dialog?
Comment: @jwebb I'm not sure what code sample to include. The question contains all of the pertinent information. I can make minor changes to the page, but cannot do a full structural re-write. That is, I can alter the `` in the ways I mentioned (`onclick` and `aria-label`), but can't re-write the table/page in which those controls reside.
Comment: @slugolicious If you press Ins+Ctrl+/, you get a "clickable elements" dialog window. That's what I'm talking about. I'll edit the question to make that more obvious.
Comment: Instead of saying "The  in question is inside of a  that is inside of a " why not include that actual block of code? It will help us to help you diagnose issues or make recommendations. But also if you cannot amend the code yourself as you stated, what is your goal? Are you doing QA and making recommendations to the developer or is just asking for your own learning and interest?
Comment: You said "I'm working on a website project and fixing accessibility defects" and then "I have no control over this, so please do not suggest any solutions for any other setup." so how are you fixing these defects then?
Comment: @jwebb That comment clearly applies to the section just previous to it, "Constraints of my setup". I **can** make some edits to the page, but I can't re-write the whole page. I also can't change the OS, browser, or accessibility software used. Those are completely fixed.
Comment: Would love some feedback instead of just drive-by downvotes, please.
Comment: Could you post an example of the block of code with the actual  etc you're talking about then? It's hard to help without a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
Answer: With the added details, I understand the problem now.  The "clickable" dialog (ins+ctrl+/) in JAWS shows elements with an onClick() handler but the label used for <select> elements in that dialog is the value of the select, which is whichever <option> that is currently selected.  Using an aria-label or aria-labelledby or  does not affect the clickable dialog, although using those attributes on a <button>, for example, does work in that dialog.
I would suggest filing a bug for JAWS.
The good news is that the JAWS shortcut key for navigating to the next <select> element is C and the dialog for showing all the <select> elements is ins+ctrl+C and that dialog does honor the aria-label or aria-labelledby' or .
Comment: Thanks for the answer! So, it sounds like you're saying that I can't actually resolve the defect as specified, using the current functionality of JAWS. Am I reading you correctly? Also, looking at the Freedom Scientific website, I don't see any place to file a bug. Do you know of a specific place, or was your suggestion simply to ask for technical support and/or give feedback?
Comment: That is correct, you cannot fix your "bug" with the way JAWS currently works.  But your `` should show up with the proper label in the ins+ctrl+c dialog.  To file a bug with JAWS, go to https://github.com/FreedomScientific/VFO-standards-support/issues
Answer: It is not a bug. A <select> is not a clickable element in no way, for a JAWS user. this keystroke brings a list of elements that are clickable but could not be identified as something other: links, buttons, combo boxes.
So, mark your defect as "Not a bug" and tell your user to use Insert+Ctrl+C instead.
A screen reader such as JAWS always tries to identify HTML elements as fine as it can, so "a clickable something" is actually not of great help for a blind user. Unlike a combo box.
Comment: I totally agree with you that a `` is not a clickable element in the sense that it is not a non-semantic element with a click handler. A `` has built in semantics where as a `` or `` does not. If the `` or `` have a `role` attribute such as `button` or `radio` or `combobox`, then it too becomes a non-clickable element.  But I don't agree that this is **not** a bug.  It is absolutely a bug.  As mentioned in my first comment, either JAWS should not list the combo in the clickable dialog (which is the actual bug) or it should honor the `aria-label`.
Comment: As an added fun fact, in case anyone is reading these comments and is wondering about 'up vote', 'down vote', or 'start a bounty', if you inspect the code those elements are all anchor tags (``), which would normally have a built in role (`link`) and semantic meaning (and thus not be listed in the clickable dialog), but they are all missing the `href` attribute so they become "placeholder links", which have no semantic meaning and are not keyboard focusable (you can't TAB to them). Since they have a click handler, they become "clickable" elements and show up in the clickable dialog.
Comment: If a `` is not a clickable element, then why does JAWS show it in the clickable dialog?  Either JAWS shouldn't include the ``, or JAWS should honor the `aria-label`.  Either way, it's a JAWS bug.
Comment: I'll ask the devs and come with it later. Anyway, by saying that a `select` is not a clickable element, I mean that it is not a "clickable something-totally-indeterminable", like a span with an `onclick` handler, but rather a specific and known element. for instance, on this very page the Insert+Ctrl+/ dialog shows me "up vote", "down vote" and "Start a Bounty" elements, because they are neither buttons, nor lists, nor radiobuttons, - just clickable "somethings", as I said in the answer.


constant $\times$ distribution

Question: I know that if $U\sim\chi^2(k)$ then $aU\sim \Gamma(k/2,2a)$ for $a>0$. But i read about the estimator and its distribution
$$\hat{\sigma}_k^2=\frac{1}{2k}\sum_{i=1}^k (X_{2i}-X_{2i-1})^2=\frac{2\sigma^2}{2k}\sum_{i=1}^k \frac{(X_{2i}-X_{2i-1})^2}{2\sigma^2}\sim \frac{\sigma^2}{k}\chi^2(k)$$
where $X_i\sim\mathcal{N}(\mu,\sigma^2)$ iid distributed. Here, it can be shown that
$$ \sum_{i=1}^k \frac{(X_{2i}-X_{2i-1})^2}{2\sigma^2}\sim \chi^2(k).$$
 Is it correct to write  $\frac{\sigma^2}{k}\chi^2(k)$ instead of $aU\sim \Gamma(k/2,2a)$ where $a=\frac{\sigma^2}{k}$. If this is ok when can i use this type notation?
Comment: Can you tell the source from where you arrived at this result that constant times chi squared is gamma RV ?
Comment: @Akhil [Wikipedia](https://en.wikipedia.org/wiki/Chi-squared_distribution#Relation_to_other_distributions) is a good online source of such information.
Comment: Are you sure your expression for $\hat{\sigma}_k^2$ is correct? Don't you need to take the square of the terms in the sum? As it is now, it is a very bad estimator for the population variance $\sigma^2$ since $\hat{\sigma}_k^2\sim N(0,\frac{\sigma^2}{2n})$.
Comment: OK, this makes sense now!
Answer: Everything in the post is correct. The question is really about notation, and I think it comes down to: can $\chi^2(k)$ be used as a notation for both the type of distribution that is intended and as a generic random variable having that distribution. For the normal distribution (and many others), we clearly make a distinction: the distribution is denoted as $N(\mu,\sigma^2)$ and a random variable having that distribution is denoted as $X$. For the chi-squared distribution, both are often written as $\chi^2(k)$ or $\chi^2_k$ which may lead to confusion.
If you are aware of this issue, there is no problem in writing $\frac{\sigma^2}{k}\chi^2(k)$ instead of $aU$. Both have the same distribution. Depending on how you define them they can be the same, $aU=\frac{\sigma^2}{k}\chi^2(k)$, or not.
A remark on the quality of the estimator $\hat{\sigma}_k$: its mean is $\sigma^2$ (so it is unbiased) but its variance is $\frac{2\sigma^4}{k}$. Note that the sample variance $S^2$ of the $2k$ observations is also unbiased but has a smaller variance $\frac{2\sigma^4}{2k-1}$. So unless you have good reasons not to, it is better to use the sample variance as an estimate for $\sigma^2$.

constant $\times$ distribution


Programa para fazer perguntas de multiplicação

Question: Pretendo fazer um programa em Python (2.7.14) que gere dois números aleatoriamente (de 0 a 10), multiplique-os, pergunte o resultado para o usuário, e exiba se o resultado está correto ou errado, até que seja digitada a string "fim", meu código ficou assim:
    import random

    m = 0

    while m!="fim" :
        n1=int(random.random()*10)
        n2=int(random.random()*10)

        m = raw_input("{} * {} = ".format(n1,n2))
        mult = int(n1*n2)

        if m==mult :
            print "correto!"

        else :
            print "errado!!"

Porém, sempre que eu digito algo, o programa sempre imprime "errado!!" , Qual o erro no meu código? Ele está bem escrito? É possível otimizá-lo mais? Se sim , como?
Answer: Se você fizer type(m) e type(mult) vai ver que o primeiro é um str enquanto o segundo é int.
Pra resolver é só modificar o if, fazendo uma conversão da variável m para inteiro:
if int(m)==mult :
    print "correto!"
else :
    print "errado!!"

Answer: Tem alguns problemas, além de estar comparando uma string  com um número, deixar digitar um texto onde se espera um número não parece ser uma boa ideia. Claro que pode tratar a exceção gerada. Não seria uma má ideia já que é um erro possível. Mas para simplificar preferi só mudar a entrada que indica o fim.
Os números gerados também estavam errados, gerava 0 que eu imagino que não é o que deseja, já que isto parece ser caso de tabuada. Se realmente quer 0, pode voltar ao 10 como estava.
import random
m = 1
while m != 0:
    n1 = int(random.random() * 9) + 1
    n2 = int(random.random() * 9) + 1
    m = int(raw_input("{} * {} = ".format(n1, n2)))
    print ("correto!" if m == n1 * n2 else "errado!!")

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.


zsh alias not creating file properly

Question: I'm trying to change the touch command to create. It needs to take one parameter so I searched up how to do this and I came across creating a function for it. I definitely did not do this right.
Here is my function:
create() {
    touch fileName $1
}

And I call the function like this
create foo.py

It does create the file, though the file name includes "fileName".
fileName foo.py

Can someone please tell me what I'm doing wrong?
Comment: @BubbyBobill : I can't say why you got the downvote - perhaps it is because you could have found the problem by simply reading the _man-page_ for `touch`, and a downvote means that you didn't put much own effort. However, just being curious : What is the advantage of your function _create_ over just using _touch_ directly, except that you have to type one more character...
Comment: I find it hard to remember.
Comment: Understood. You are aware that touch is doing more than just creating a file? If you type `create foo` and the file _foo_ does already exist, the file stays unchanged, but its timestamp is changed. Perhaps a name _create_if_not_already_exists_  or _create_or_modify_time_change_ would be more appropriate than _create_, and easy to remember too.
Comment: No I had no clue thatnk you though, im kind of a noob at this stuff rn
Comment: @BuddyBoblll : _man touch_ will tell you everything you need to know.
Answer: Remove fileName. That's a placeholder for the file name to create, which in your case is $1.
create() {
    touch $1
}

zsh alias not creating file properly


Relations on free algebra

Question: If we have any class $K$ of algebras (sets with operations and constants) of given type, then there is the well-known construction of free algebra $F_K(X)$ with respect to $K$ generated by given set of variables $X$. If structures of given type in $K$ also have some relations, is there a canonical way, how to define realisations of that relation symbols on $F_L(X)$, where $L$ is the class of reducts of members of $K$ only to such operations and constants?
Comment: I don't understand the reason for the close votes. I also don't know the answer, but I think the question is legitimate and interesting (+1)
Comment: @amrsa I suspect the close-voters are not familiar with the basic language of universal algebra. But this isn't a reason to close as needing more context; we don't ask every question on algebraic geometry to define what a sheaf is, after all.
Answer: If we have any class $K$ of algebras (sets with operations and constants) of given type, then there is the well-known construction of free algebra $F_K(X)$ with respect to $K$ generated by given set of variables $X$.
The notion of freeness is a categorical one, and one ought to refer to a category when speaking about free algebras. Let's assume that we are speaking about free algebras in varieties.
If $L$ is a first-order algebraic language, then a variety in this language is a class $K$ of $L$-algebras axiomatizable by identities.
$K$ may be considered to be a category if we choose the class of morphisms to be 'all algebra homomorphisms'. Birkhoff used free algebras to show that such classes (=varieties) are precisely the classes of $L$-algebras that are closed under the formation of homomorphic images, subalgebras and products.
Now let's add relations.  Assume our language $L$ is an arbitrary first-order language. Let's say that $K$ is a variety of $L$-structures if it is axiomatizable by universally-quantified atomic formulas. (Atomic formula = formula of the form $R(s_1,\ldots,s_k)$ for terms $s_1,\ldots,s_k$.) One can extend Birkhoff's Theorem to show that $K$ is a variety of $L$-structures precisely when it is  closed under the formation of homomorphic images, not-necessarily-induced substructures and products. The morphisms in $K$ are the functions that preserve the operations and relations. (We do not require that the morphisms reflect the relations.) The proof uses free algebras
constructed as follows.
First, ignore the relations and construct the free algebras $[F]_K(X)$ with respect to the underlying algebra structure. Then interpret the relations on $[F]_K(X)$ as follows.
For any $k$-ary relation symbol $R$, say that $R^{F_K(X)}(s_1,\ldots,s_k)$ holds for
$s_1,\ldots, s_k\in [F]_K(X)$ if and only if
$R^A(s_1^A(x_1,\ldots,x_n),\ldots,s_k^A(x_1,\ldots,x_n))$ holds universally for every in $A\in K$. Here I am writing $s_i^A(x_1,\ldots,x_n)$ to mean: choose an $n$-ary $L$-term which when applied to $X\subseteq [F]_K(X)$  yields $s_i$. This term has an interpretation $s_i^A(x_1,\ldots,x_n)$ in $A$.
Example. Let $K$ be the class of all lattices. Let $R(x,y)$ be a relation symbol which interprets in every lattice as the order relation. ($R^{A}(x,y)$ holds iff $x\leq y$ for any $A\in K$.) Let $X=\{x_1,x_2,x_3\}$. In $F_K(X)$ we do have $R^{F_K(X)}(x_1\wedge x_2,x_1)$ since $x_1\wedge x_1\leq x_1$ holds universally in every member of $K$, but we do not have $R^{F_K(X)}(x_1\wedge (x_2\vee x_3),(x_1\wedge x_2)\vee(x_1\wedge x_3))$, since
$x_1\wedge (x_2\vee x_3)\leq (x_1\wedge x_2)\vee(x_1\wedge x_3)$ does not hold universally in every member of $K$.
One sentence summary. The relation symbols are interpreted in the free algebras so that they only relate the tuples that they are forced to relate.

Relations on free algebra


Likelihood Ratio for two-sample Exponential distribution

Question: Let $X$ and $Y$ be two independent random variables with respective pdfs:
$$f \left(x;\theta_i \right) =\begin{cases} \frac{1}{\theta_i} e^{-x/ {\theta_i}} \quad 0<x<\infty, 0<\theta_i< \infty \\ 0 \quad \text{elsewhere} \end{cases} $$
for $i=1,2$. Two indepedent samples are drawn in order to test $H_0: \theta_1 =\theta_2 $ against $H_1 : \theta_1 \neq \theta_2 $ of sizes $n_1$ and $n_2$ from these distributions. I need to show that the LRT $\Lambda$ can be written as a function of a statistic having $F$ distribution, under $H_0$.

Since the mle of this distribution is $\hat{\theta}=\bar{x} $, the LRT statistic becomes (I am skipping a few tedious steps here):
$$ \Lambda =\frac{\bar{x}^{n_1} \bar{y}^{n_2} \left( n_1+n_2 \right)}{n_1 \bar{x}+n_2 \bar{y}}$$
I know that the $F$ distribution is defined as the quotient of two independent chi-square random variables, each one over their respective degrees of freedom. Additionally, since $X_i,Y_i \sim \Gamma \left( 1,\theta_1 \right)$ under the null, then $\sum X_i \sim \Gamma \left(n_1 ,\theta_1 \right)$ and$\sum Y_i \sim \Gamma \left(n_2, \theta_1 \right) $.
But how can I proceed from here? Any hints?
Thank you.
Comment: Maybe you need to _not_ skip the few tedious steps and actually derive the likelihood ratio from scratch instead of jumping to maximum-likelihood _estimators._  This is a problem about _hypothesis testing_ not about maximum-likelihood estimation of an unknowm parameter $\theta_i$.
Comment: Perhaps you can start by explaining to me (a non-statistician, by the way) what the T in LRT means.
Comment: Hint: An exponential random variable is linearly related to a $\chi^2$ random variable with two degrees of freedom, and thus a $\Gamma$ random variable with order parameter $n$ is linearly related to a $\chi^2$ random variable with $2n$ degrees of freedom.
Comment: @DilipSarwate I can see that $Z= \frac {2}{\theta_1} \sum X_i \sim \chi^2 \left(2n_1 \right) $.  Should I go on and try to reformulate my fraction according to that?
Comment: @DilipSarwate You misunderstood. I have these intermediate steps written down but have not presented them here. This is what you get after simplification.
Comment: @DilipSarwate A test. This is a very specific question I am asking though. How can I reformulate my test so that it depends on the F-statistic? I am a beginner so people kind enough to help will have to be a little more explicit. Thank you.
Comment: The final statistic will be $\frac{\sum x_i}{
\sum x_i +\sum y_i}$
Answer: If memory serves, it appears you have forgotten something in your LR statistic.
The likelihood function under the null is
$$L_{H_0} = \theta^{-n_1-n_2}\cdot \exp\left\{-\theta^{-1}\left(\sum x_i+\sum y_i\right)\right\}$$
and the MLE is
$$\hat \theta_0 = \frac {\sum x_i+\sum y_i}{n_1+n_2} = w_1\bar x +w_2 \bar y, \;\; w_1=\frac {n_1}{n_1+n_2},\;w_2=\frac {n_2}{n_1+n_2}$$
So$$ L_{H_0}(\hat \theta_0) = (\hat \theta_0)^{-n_1-n_2}\cdot e^{-n_1-n_2}$$
Under the alternative, the likelihood is
$$L_{H_1} = \theta_1^{-n_1}\cdot \exp\left\{-\theta_1^{-1}\left(\sum x_i\right)\right\}\cdot \theta_2^{-n_2}\cdot \exp\left\{-\theta_2^{-1}\left(\sum y_i\right)\right\}$$
and the MLE's are
$$\hat \theta_1 = \frac {\sum x_i}{n_1} = \bar x, \qquad \hat \theta_2 = \frac {\sum y_i}{n_2} = \bar y$$
So
$$L_{H_1}(\hat \theta_1,\,\hat \theta_2) = (\hat \theta_1)^{-n_1}(\hat \theta_2)^{-n_2}\cdot e^{-n_1-n_2}$$
Consider the ratio
$$\frac {L_{H_1}(\hat \theta_1,\,\hat \theta_2)}{L_{H_0}(\hat \theta_0)} = \frac {(\hat \theta_0)^{n_1+n_2}}{(\hat \theta_1)^{n_1}(\hat \theta_2)^{n_2}}=\left(\frac {\hat \theta_0}{\hat \theta_1}\right)^{n_1} \cdot \left(\frac {\hat \theta_0}{\hat \theta_2}\right)^{n_2}$$
$$= \left(w_1 + w_2 \frac {\bar y}{\bar x}\right)^{n_1} \cdot \left(w_1\frac {\bar x}{\bar y} + w_2 \right)^{n_2}$$
The sample means are independent -so I believe that you can now finish this.
Comment: It's not very important but I think you should define the LRT as the reciprocal of the fraction you've used, see http://www.stats.ox.ac.uk/~dlunn/b8_02/b8pdf_8.pdf .
Comment: The reciprocal was used because it helps with the algebraic manipulations. When this part is done, one just takes the negative of the outer powers.
Comment: Alright. In order to show that the fraction $\frac{\bar{X}}{\bar{Y}} $ follows an F-distribution, it suffices to write it as $ \frac{\frac{2\sum X_i}{2 \theta_1 n_1}}{\frac{2\sum Y_i}{2 \theta_1 n_2 }}$ , right?
Comment: If that's a correct "link" between gammas and chi-squares, indeed.
Comment: Yes, $\frac{2}{\theta_1} \sum X_i \sim \chi^2 \left( 2n_1 \right) $ And we also have to divide by the degrees of freedom, $2n_1 $. Thank you very much.
Answer: The likelihood function given the sample $\mathbf x=(x_1,\ldots,x_{n_1},y_1,\ldots,y_{n_2})$ is given by
\begin{align}
L(\theta_1,\theta_2)&=\frac{1}{\theta_1^{n_1}\theta_2^{n_2}}\,\exp\left[-\frac{1}{\theta_1}\sum_{i=1}^{n_1} x_i-\frac{1}{\theta_2}\sum_{i=1}^{n_2}y_i\right]\mathbf1_{\mathbf x>0},\quad\theta_1,\theta_2>0.
\end{align}
The LR test criterion for testing $H_0:\theta_1=\theta_2$ against $H_1:\theta_1\ne \theta_2$ is of the form
\begin{align}
\lambda(\mathbf x)&=\frac{\sup\limits_{\theta_1=\theta_2}L(\theta_1,\theta_2)}{\sup\limits_{\theta_1,\theta_2}L(\theta_1,\theta_2)}
=\frac{L(\hat\theta,\hat\theta)}{L(\hat\theta_1,\hat\theta_2)},
\end{align}
where $\hat\theta$ is the MLE of $\theta_1=\theta_2$ under $H_0$, and $\hat\theta_i$ is the unrestricted MLE of $\theta_i$ for $i=1,2$.
It is easily verified that
$$\left(\hat\theta_1,\hat\theta_2\right)=(\bar x,\bar y)$$
and $$\hat\theta=\frac{n_1\bar x+n_2\bar y}{n_1+n_2}.$$
After some simplification we get this symmetry for the LRT criterion:
\begin{align}
\lambda(\mathbf x)&=\underbrace{\text{constant}}_{>0}\left(\frac{n_1\bar x}{n_1\bar x+n_2\bar y}\right)^{\!\!n_1}\left(\frac{n_2\bar y}{n_1\bar x+n_2\bar y}\right)^{\!\!n_2}
\\&=\text{constant}\cdot\,t^{n_1}(1-t_1)^{n_2},\quad\text{ where }t=\frac{n_1\bar x}{n_1\bar x+n_2\bar y}
\\&=g(t),\,\text{say.}
\end{align}
Studying the nature of the function $g$, we see that $$g'(t)\gtrless 0\;\iff\; t\lessgtr \frac{n_1}{n_1+n_2}.$$
Now since $2n_1\overline X/\theta_1\sim \chi^2_{2n_1}$ and $2n_2\overline Y/\theta_2\sim \chi^2_{2n_2}$ are independently distributed, we have
$$\frac{\overline X}{\overline Y}\stackrel{H_0}{\sim}F_{2n_1,2n_2}.$$
Define $$v=\frac{n_1\overline x}{n_2\overline y},$$
so that $$t=\frac{v}{v+1}\quad\uparrow\, v$$
Therefore,
$$\lambda(\mathbf x)<c \iff v<c_1\quad\text{ or }\quad v>c_2,$$
where $c_1,c_2$ can be found from some size restriction and the fact that, under $H_0$,
$$\frac{n_2}{n_1}\,v\sim F_{2n_1,2n_2}.$$


My site is HTTPS and want only a URL with HTTP with Nginx

Question: I have a site in a Nginx server forces HTTPS for all site, but i need only an URL in HTTP.
This is the URL:
https://site.meudominio.com.br/index.php?route=primeiro/segundo/terceiro/funcao

I want it to be forced to stay in HTTP just like this and hold:
http://site.meudominio.com.br/index.php?route=primeiro/segundo/terceiro/funcao

My config file is:
server {

    listen      80;
    listen [::]:80;
    server_name site.meudominio.com.br;
    return 301 https://site.meudominio.com.br$request_uri;
}

server {
    listen      443 ssl http2;
    listen [::]:443 ssl http2;
    server_name site.meudominio.com.br;

    ssl on;
    ssl_certificate     /etc/ssl/fullchain.pem;
    ssl_certificate_key /etc/ssl/privkey.pem;

    include snippets/ssl-params.conf;

    root /var/www/meudominio.com.br/site;

    index index.html index.htm index.php;

    charset utf-8;

    location / {
         try_files $uri @meudominio;
    }

    location @meudominio {
      rewrite ^/(.+)$ /index.php?_route_=$1 last;
    }

location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/run/php/php-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_intercept_errors off;
        fastcgi_buffer_size 16k;
        fastcgi_buffers 4 16k;
    }

    location ~ /\.ht {
        deny all;
    }
}

Comment: What have you actually tried? what's not working as expected? This looks more like a "do it for me" instead of a question, please clarify what the actual issue is.
Answer: The return 301 in your http section is the problem. It is telling Nginx to send everyone who comes in via http to the https URL.


C: Cannot get fprintf to print to output-file

Question: I'm trying to print a matrix into a csv. arg[2] in this is the file name and I can verify that works correctly since it will generate the file but will not populate it. I do close the file and try flushing to it but it does not work.
// Open the output/second file and write the contents of truncated DCT matrix into it
outputfp = fopen(argv[2], "w");

if (outputfp == NULL) {

fprintf(stderr, "Can't open output file %s!\n", argv[2]);
exit(1);
                      }
double hold = 0;
printf("test\n");

for (i = 0, i < idx; i++;) {
    for (j = 0, j < ARRAY_WIDTH; j++;) {

    hold = test_write[i][j];

            fprintf(outputfp, "%.61f", hold);
                if (j != ARRAY_WIDTH) {

                    fprintf(outputfp, ",");
                }
                else {
                    //continue;
                }
                fflush(outputfp);
    }
}

fclose (outputfp);
return 0;
}

Answer: This cycle
 for (j = 0, j < ARRAY_WIDTH; j++;) {

never iterates.
Wrong placement of , and ; makes j++ the iteration condition. Since before the very first iteration j++ evaluates to 0, the cycle is never entered. Apparently, you meant to write
 for (j = 0; j < ARRAY_WIDTH; j++) {

Comment: Thank you I had an issue earlier where I had incorrectly typed out the for loop I though I had gotten rid of all of them. I just needed a second pair of eyes. I already got it fixed and working. I'm just confused why the compiler views what I had as valid c code.


Flutter: How to create a new list with only one class member?

Question: I have a class named Recyclable with many members, including title, description, and recyclable. I then created an object named recyclable using the class Recyclable as follows:
List<Recyclable> recyclable = [
  Recyclable('myTitle', 'myDescription', 'is recyclable'),
  Recyclable('myTitle2', 'myDescription2', 'is recyclable'),
];

Now, I want to copy the object recyclable but only with the title information. In other words, I want to create a list named newInfo as below:
List<String> newInfo = List.from(recyclable.title);

However, there is a red underline below .title, and I have no idea how to fix this.
Answer: Try the code below :
List<Recyclable> recyclable = [
    Recyclable('myTitle', 'myDescription', 'is recyclable'),
    Recyclable('myTitle2', 'myDescription2', 'is recyclable'),
  ];

  List<String> newInfo = recyclable.map((item) {
    return item.title;
  }).toList();
  print(newInfo);
  //[myTitle, myTitle2]

The Recyclable class :
class Recyclable {
  String title;
  String description;
  String isRecyclable;

  Recyclable(this.title, this.description, this.isRecyclable);
}


How to interpret standardized beta coefficients with a log-log and lin-log combinations?

Question: I carried out a multiple linear regression analysis with three dependent variables. Two of them are measures as a logarithm, one of them is measured on a range from [0,1]. The dependent variable is also a logarithm. In order to make them comparable, I used the stdBeta command in Stata to obtain the standardized coefficients, i.e., the beta weights.
However, I am unsure how to interpret these values. For the normal regression output, I would use the following interpretation:

Log-Log: For a 1% increase in X, there is a x % increase in Y.
Lin-Log: For a 1-unit increase in X, there is a 100x % increase in Y. (at least for small values).

How does the interpretation for the standardized coefficients work? Is it the following?

Log-Log: For a 1% increase in the standard deviation in X, there is a x % increase in the standard deviation in Y.
Lin-Log: For a 1-standard-deviation increase in X, there is a 100x % increase in the standard deviation in Y?

I really appreciate your help!
Answer: What Beta Coefficients Are
Beta coefficients do not require any special interpretation, as they are standardized. To approximate the coefficient value, it estimates the change in standard deviation units in the average value of y per standard deviation increase in the predictor, bounded from -1 to +1. This is achieved with the formula for obtaining them, which is simply:
$$
\begin{aligned}
  \beta^*=\frac{s_x}{s_y}\beta
\end{aligned}
$$
where $s$ is the standard deviation and $\beta$ is the regression slope coefficient (see Vittinghoff et al., 2012, page 75). As such, their meaning is the same regardless of whatever transformation you apply to the regression, because the values are always rescaled to be unitless.
Practical Example in R
I demonstrate with an example below using R, first by manually transforming two regression beta coefficients, then by using the lm.beta function to compare how it is done automatically in R. First the simulated data, which has a curvilinear trend.
#### Simulate Data ####
library(lm.beta)
x=1:15
z=rnorm(n=15)
y=c(59, 50, 44, 38, 33, 28, 23, 20, 17, 15, 13, 12, 11, 10, 9.5)
plot(x,y)

I fit a model that includes the raw units of x and z by their raw values, then a second model with x logged.
#### Fit MLR ####
fit <- lm(
  y ~ x + z
)

#### Fit MLR with Log X ####
fit2 <- lm(
  y ~ log(x) + z
)

To obtain the beta coefficients manually, we just plug in the values from the formula for each by using the coef function on our regression fits, selecting the 2nd coefficient (the x slope or log(x) slope). Then we multiply the sd or standard deviation of x, then divide by the standard deviation of y. The only difference we make in this case is logging x for the second regression, as this was the value of x when entered into the regression.
#### Manually Obtain Betas ####
coef(fit)[2]*sd(x)/sd(y)
coef(fit2)[2]*sd(log(x))/sd(y)

You can see the output for each below:
> coef(fit)[2]*sd(x)/sd(y)
         x
-0.9506303
> coef(fit2)[2]*sd(log(x))/sd(y)
    log(x)
-0.9917196

The slightly higher log(x) beta makes sense, as now that it's been transformed to become more linear, its predictiveness of y is accordingly better than the raw x units. To check if this was calculated right, we can use the lm.beta function.
#### Obtain Betas ####
lm.beta(fit)
lm.beta(fit2)

And we will see that both x and log(x) match their manual calculations.
> lm.beta(fit)

Call:
lm(formula = y ~ x + z)

Standardized Coefficients::
 (Intercept)            x            z
          NA -0.950630304  0.001188294

> lm.beta(fit2)

Call:
lm(formula = y ~ log(x) + z)

Standardized Coefficients::
(Intercept)      log(x)           z
         NA -0.99171958  0.01540832

You will find the same applies for a log-log regression. The definitions don't change, and neither does interpretation.
#### Fit MLR with Log Log ####
fit3 <- lm(
  log(y) ~ log(x) + z
)

#### Manually Calculate ####
coef(fit3)[2]*sd(log(x))/sd(log(y))

#### Check Again with LMBETA ####
lm.beta(fit3)

You will find the approximation is still similar.
Citation
Vittinghoff, E., Glidden, D. V., Shiboski, S. C., & McCulloch, C. E. (2012). Regression methods in biostatistics: Linear, logistic, survival, and repeated measures models (2nd ed.). Springer US. https://doi.org/10.1007/978-1-4614-1353-0


Monitor root commands issued by users

Question: I tried to log the commands issued by the system administrators in our organization and its output using sudo plus the log_output directive as follows on the visudo file
<code>Defaults        env_reset
Defaults            secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
Defaults:%sudo log_output

...
root    ALL=(ALL) ALL

...
%sudo ALL=(ALL)  ALL
</code>
This does exactly what it is requested but it has a big flaw.
When the system administrators execute sudo su - the sudo file handler buffers the command output until the sudo session is closed, so the administrator can close the terminal and the commands output is never logged.
Also, we tried auditd but it does not who switched to root in the first place.
Is there a known way to force sudo flush the log files?
Please let me know if it is a better software to log root activities that we may have overlooked.
Thanks!
Answer: Sudosh may be a better solution. It logs sessions as needed and gives you "VCR" capabilities allowing you to replay sessions, its also available in most major distribution package repositories.
Answer: sudo 1.8.20 or higher has an iolog_flush setting that can be enabled.

Monitor root commands issued by users


SQL Server 2005 on 2008 DC - Cannot change service user

Question: I cannot start SQL Server 2005 transactional replication after I promoted my 2008 Server to a DC.

A required privilege is not held by
  the client.

This site suggests that I need to change the SQL Server service from my domain account to a local account then back again to the domain account:
http://support.microsoft.com/kb/911305
However I am getting an error upon changing:

Error Code: 0x80070534 No mapping between account names and
  security IDs was done.

I found this http://social.msdn.microsoft.com/forums/en-US/sqlsetupandupgrade/thread/bf0c1eae-a1fa-4a63-b6a8-c18e81498780/ that suggests I am to delete some registry entries -- however I don't want to delete willy-nilly if I am not sure it will work (also that is part of a Service Pack install). Any ideas?
Answer: Interesting problem. I haven't spun up a test instance to reproduce this on my own box, but it looks like there are three registry values stored at the key below that refer to SIDs of groups created by the SQL Server 2005 install:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.x\Setup

The values are AGTGROUP, FTSGROUP, and SQLGROUP. The groups that had the SIDs used to populate these values were (substituting in your server computer's name and SQL instance name):
SQLServer2005MSSQLUser$SERVER-NAME$INSTANCE-NAME
SQLServer2005MSFTEUsers$SERVER-NAME$INSTANCE-NAME
SQLServer2005SQLAgentUsers$SERVER-NAME$INSTANCE-NAME

I'm guessing that you promoted this box to being a domain controller in an existing domain, rather than creating a brand new domain seeded from this box's own Local Users and Groups (SAM) database.
From what I can see (again, w/o repro'ing this myself), you need to create new groups in the domain for this server, then obtain the SIDs for the new groups and put them into the registry. It looks like a "repair" of the SQL Server install would do this. Have a look at this article from Microsoft Connect: http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=202561
Search that article for the phrase "One or more SQL security groups were somehow deleted" and read thru the workaround there. It looks like clearing out the old groups and running setup in repair mode will do what you want. I'd trust that better than trying to re-create them by hand like some blog posts and forum posts I've found suggest.
Having said all that, backup, at minimum, that portion of the registry and your databases before you start changing things. Having good backups makes things "just work"... <smile>


Getting a list of companies with dual share classes using cusip

Question: I am a beginner in R, and I have a table that consists of two columns. The first column is the ID. The second column is the label (actually CUSIP in CRSP data). The label is the eight-digit number where the first six digits identify the ID, and the last two-digit may differ by certain attributes of the ID.
I would like to have a list of IDs that has two different labels where one of the two labels ends with a different two-digit number.
for example, if the table looks as follows,

ID
label

1
11223330

1
11223341

2
11224430

3
11225530

3
11225531

4
11226630

5
11227730

5
11227753

in this case, I hope to see

ID
label

1
11223330

1
11223341

3
11225530

3
11225531

5
11227730

5
11227753

Thank you very much in advance!
Answer: If you've only got these two columns or you have other variables, but not ID-label pair is repeated you could use this
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union

dat <- structure(list(ID = c(1L, 1L, 2L, 3L, 3L, 4L, 5L, 5L), label = c(11223330L,
11223341L, 11224430L, 11225530L, 11225531L, 11226630L, 11227730L,
11227753L)), row.names = c(NA, 8L), class = "data.frame")

dat <- dat %>%
  mutate(var3 = 8:1)

dat %>%
  group_by(ID) %>%
  filter(n() >= 2)
#> # A tibble: 6 × 3
#> # Groups:   ID [3]
#>      ID    label  var3
#>   <int>    <int> <int>
#> 1     1 11223330     8
#> 2     1 11223341     7
#> 3     3 11225530     5
#> 4     3 11225531     4
#> 5     5 11227730     2
#> 6     5 11227753     1

However, if you've got duplicated ID-label pairs and other variables that you want to retain and you only want one row per ID-label pair, you could turn the other variables into list columns:
dat <- structure(list(ID = c(1L, 1L, 2L, 3L, 3L, 4L, 5L, 5L), label = c(11223330L,
11223341L, 11224430L, 11225530L, 11225531L, 11226630L, 11227730L,
11227753L)), row.names = c(NA, 8L), class = "data.frame")
dat <- bind_rows(dat, dat)
dat <- dat %>%
  mutate(var3 = 16:1)

out <- dat %>%
  group_by(ID, label) %>%
  summarise(across(everything(), ~list(.x))) %>%
  ungroup %>%
  group_by(ID) %>%
  filter(n() >= 2)
#> `summarise()` has grouped output by 'ID'. You can override using the `.groups`
#> argument.

out
#> # A tibble: 6 × 3
#> # Groups:   ID [3]
#>      ID    label var3
#>   <int>    <int> <list>
#> 1     1 11223330 <int [2]>
#> 2     1 11223341 <int [2]>
#> 3     3 11225530 <int [2]>
#> 4     3 11225531 <int [2]>
#> 5     5 11227730 <int [2]>
#> 6     5 11227753 <int [2]>

out$var3
#> [[1]]
#> [1] 16  8
#>
#> [[2]]
#> [1] 15  7
#>
#> [[3]]
#> [1] 13  5
#>
#> [[4]]
#> [1] 12  4
#>
#> [[5]]
#> [1] 10  2
#>
#> [[6]]
#> [1] 9 1

Created on 2022-04-25 by the reprex package (v2.0.1)
Comment: Thank you very much!! I was just wondering what would happen to the code if I do the same thing, but there are three columns, say (1st column= ID, 2nd column = a new variable 'return', and 3rd column = label). My guess is that something in the last row, inside the filter, needs to change and specify that I am dealing with 3rd column in specific. Is this correct?
Comment: @dodobirdy I updated the answer with a couple of other options.


Is there any existing model of ResNet for tensorflow

Question: I'm seeking the trained model of ResNet or ResNetXt for tensorflow.
Can anyone offer me a link to download it?
Thanks in advance.
Answer: Here it is. article, code, link to pre-trained model and the accuracy on ImageNet test set.
https://github.com/tensorflow/models/tree/master/research/slim#pre-trained-models


Should rand be used for an IV?

Question: CBC mode for AES specifies that to make each message unique, an IV should be used. The IV should be random and only used once, otherwise it may allow people to decrypt other cipher texts which used the same key.
Is the rand() function in C suitable for generating this IV? Does the fact that it is normally seeded with the current time make it vulnerable to some sort of attack?
Comment: No; `rand()` is not cryptographically random.  It is extremely unlikely to be useful if you want any security.  The chances are it only yields 31 bits of pseudo-randomness, and that simply isn't enough to be useful for security.
Comment: The IV needs to be unpredictable for CBC mode. If `rand` really only uses the current time as a seed, then this might not be secure (depending on the overall protocol).
Comment: @JonathanLeffler i thought it only had to be random enough to stop replay attacks?
Comment: Use something more decent like libsodium, or hardware random generator. You can also use online generators
Comment: Yes, but that means cryptographically random enough — and `rand()` is not anywhere near random enough.  Reading from `/dev/random` or `/dev/urandom` might be OK; it would certainly be better than `rand()`.  Remember, unless you call `srand()`, using `rand()` will generate the same 'random' number sequence each time it is used.  Calling `srand()` requires a value to kick things off.  But the internals of `rand()` are known to your attackers; they can predict what's happening.
Comment: And don't trust online generators (if i interpreted this advice correctly as: use some online-service to ask for randomness).
Answer: The quick answer is NO.  Don't use a non cryptographically-secure random generator for initialization vectors.  The initialization vectors are sent unencrypted, so one could think they can be generated by one of these functions.  But this should lead to weakness, and I'll explain:  If you use a poor (and rand() is such a weak random routine) you'll narrow the space of possible IVs you are generating.  An example will suffice:
Let's suppose you are using a 8 bytes IV in some encrypted message.  But the random function you use has a 8 bit seed, there are only 256 possible byte sequences to be generated from such a poor random function, so probably there will be only a maximum of 256 possible IVs generated (even if they show pure randomness, or a wide spread hash values over the whole space)  An attacker knowing this, can reproduce the whole 256 space of possible IV making them completely useless.
Comment: The IV is sent in the clear, so the attacker doesn't need to reproduce it.  And while an 8-bit seed makes for only 256 different streams, having an unknown position within those streams makes for more possible 8 byte subsequences (though if the assertion is it's being reseeded every call then, yeah, it'd be only 256).
Comment: @bartonjs, The IV is sent in the clear, you are right, but it has a size and must be made of equally probable bits with maximum entropy.  Almost all these requirements are met by a small seed good entropy random generator, but the last.  Maximum entrophy cannot be achieved if the seed has only 8 bits, you'll have maximum 256 IVs, and this is no entrophy at all.  If the seed is reseeded, then what entrophy generation are you using? are you reseeding it from another random generator?  Do you see my approach?

Should rand be used for an IV?


Characterization of the space of integrable functions stable under multiplication

Question: Let $Ω = (Ω,Σ_Ω,μ)$ be a measure space and let $L(Ω)$ be the space of integrable functions on $Ω$.
For $f ∈ L(Ω)$, set $L_f(Ω) = \{φ ∈ L(Ω);~f·φ ∈ L(Ω)\}$.
Has the space of all integrable functions stable under multiplication by integrable functions
$$\bigcap_{f ∈ L(Ω)} L_f(Ω)$$
a nice characterization when $Ω$ is an Euclidean space $ℝ^n$ equipped with the Lebesgue measure, say in terms of continuity? Are there characterizations for more general $Ω$?
Answer: Assuming $\mu(\Omega)<\infty$, this intersection is $L^\infty(\Omega)$, the set of bounded measurable functions.
It is clear that $L^\infty(\Omega)\subset L_f(\Omega)$ for any $f\in L(\Omega)$.
The other direction is trickier.
Let us denote the intersection by $I$.
If $f\in I$, then $f\in L_f(\Omega)$ and so $f^2\in L(\Omega)$.
But $f\in I\subset L_{f^2}(\Omega)$, so $f^3\in L(\Omega)$.
Carrying on like this, we have that $f^k\in L(\Omega)$ (or $f\in L^k(\Omega)$) for any $k\in\mathbb N$.
This implies that $f\in\bigcap_{p\in\mathbb N} L^p(\Omega)=L^\infty(\Omega)$.
Even if $\Omega$ has infinite measure, the argument above shows that $L(\Omega)\cap L^\infty(\Omega)\subset I\subset\bigcap_{p\in\mathbb N} L^p(\Omega)$.


Acrescentando elementos a um dicionário somente se a chave não existir

Question: Tenho que criar uma função que acrescenta os dados de um novo aluno em um dicionário.
Entrada:

alunos: dicionario com os dados dos alunos
nome: nome do aluno (chave)
notas: lista com as notas de um aluno (valor)

Retorno:

A função deve retornar o dicionário com as modificações realizadas*

Observação: Caso a chave já exista no dicionário, deve retornar o dicionário sem nenhuma alteração.
Esse é meu código, que retorna "já cadastrado", sendo que o valor foi inserido pela primeira vez:
alunos = dict()

def adicionar_aluno ( alunos , nome , notas ):
    alunos[nome]=[notas]
    if nome in alunos:
        return 'já cadastrado'
    else:
        return alunos

nome = input ( 'nome: ' )
notas = float ( input ( 'nota: ' ) )
a=adicionar_aluno(alunos, nome, notas)
print(a)

Answer: Isso acontece por causa da ordem em que as coisas são feitas (e que poderia ser detectado fazendo um teste de mesa).
Primeiro você adiciona o aluno no dicionário:
alunos[nome]=[notas]

Depois você verifica se esse aluno está no dicionário:
if nome in alunos:

Ou seja, esse if sempre será verdadeiro, porque o aluno que você está verificando já foi adicionado na linha anterior.
O que você deve fazer é cadastrar o aluno somente se ele não existir no dicionário (ou seja, dentro do else):
def adicionar_aluno ( alunos , nome , notas ):
    if nome in alunos:
        return 'já cadastrado'
    else:
        alunos[nome] = [notas]
        return alunos

Se bem que os requisitos dizem que deve sempre retornar o dicionário, então basta modificar a condição para só acrescentar o aluno se ele não existir:
def adicionar_aluno ( alunos , nome , notas ):
    if nome not in alunos:
        alunos[nome] = [notas]
    return alunos

Ou seja, se o aluno não existe no dicionário, adiciona (repare no not in, que verifica se o aluno não está no dicionário). Se ele já existir, não precisa fazer nada (por isso nem precisa do else).
No final, retorne o dicionário. Se ele entrou no if, ele terá o novo aluno. Se ele não entrou no if, será retornado sem modificações.

Só achei estranho a sua função retornar uma mensagem ou o próprio dicionário. Talvez seja melhor ela retornar True ou False, indicando se o aluno foi ou não cadastrado. Não precisa retornar o próprio dicionário porque o mesmo é modificado dentro da função:
alunos = dict()

def adicionar_aluno ( alunos , nome , notas ):
    if nome in alunos:
        return False
    else:
        alunos[nome] = [notas]
        return True

nome = input('nome: ')
nota = float(input('nota: ' ))
if adicionar_aluno(alunos, nome, nota):
    print(f'aluno {nome} adicionado')
else:
    print(f'aluno {nome} já cadastrado')

Comment: cara muito obrigado, deu uma luz aqui no meu problema, to começando na linguagem e ai algumas coisas são meio confusas, obg!
Answer: Basta colocar a atribuição das notas dentro do bloco if e utilizar um not antes para verificar se o aluno não está registrado.
Também não é necessário um else já que de qualquer maneira, o dicionário será retornado. Veja o código abaixo:
def adicionar_aluno ( alunos, nome, notas ):

    if not nome in alunos:
        alunos[nome] = [notas]
    return alunos

Como a função adicionar_aluno altera o objeto de dicionário diretamente sem criar um novo dicionário, acho que não seria necessário retornar o dicionário e sim um valor bool como True ou False para informar se o dicionário foi modificado.
def adicionar_aluno ( alunos, nome, notas ):

    if not nome in alunos:
        alunos[nome] = [notas]
        return True

    return False

Comment: obg pela atenção!


Retorno errado do comando ping

Question: Levando em conta que a ${parameters} é um array que pode conter endereços IPs válidos ou não, escrevi o seguinte código:
  for ((i=0; i<$#; i++)); do
        eval "arg=\${$i}"
        ping ${parameters[i]} -c1 -q &>/dev/null
        if [ $? == 0 ]
            then
            echo "ok"
        else
            echo "fail"
        fi
    done

Acontece que o retorno $? parece sempre conter o valor 0, mesmo quando o IP passado na ${parameters[i]} não é válido.
Alguma ideia?
Comment: O `for` está iterando sobre o número de argumentos do script `$#`, não seria `${#parameters[@]}` para iterar sobre o `array`? Acho que o `eval...` não é necessário.
Comment: Nesse caso, não faz diferença se estamos iterando sobre os parâmetros ou sobre o array. Mas, mesmo fazendo essa alteração, o erro persiste.
Comment: O script aqui funcionou, que IP por exemplo não é válido e mesmo assim retorna "ok"?
Comment: qualquer Ip, tipo 8.8.8.asdf
Comment: O código de erro pode variar conforme o resultado do `ping`: Sucesso: 0; Sem Resposta: 1; Outros Erros: 2.
Answer: O código de erro retornado pelo utilitário ping pode variar dependendo do ocorrido:

Sucesso: 0
Timed-out: 1
Host Inalcançável: 2

Sendo assim, segue exemplo (testado) de um script capaz de solucionar o seu problema:
#!/bin/bash

IP_LIST=( 0.0.0.0
          255.255.255.255
          xxx.xxx.xxx.xxx
          127.0.0.1
          220.127.116.11
          188.8.131.52
          18.104.22.168
          184.108.40.206 )

for ((i = 0; i < ${#IP_LIST[@]}; i++)); do

    ping -q -c1 "${IP_LIST[i]}" &>/dev/null

    case "$?" in
        '0') STATUS="OK" ;;
        '1') STATUS="TIMEOUT" ;;
        '2') STATUS="INALCANCAVEL" ;;
          *) STATUS="ERRO" ;;
    esac

    echo "IP: ${IP_LIST[i]} [${STATUS}]"

done

Saída:
IP: 0.0.0.0 [OK]
IP: 255.255.255.255 [INALCANCAVEL]
IP: xxx.xxx.xxx.xxx [INALCANCAVEL]
IP: 127.0.0.1 [OK]
IP: 126.96.36.199 [TIMEOUT]
IP: 188.8.131.52 [TIMEOUT]
IP: 188.8.131.52 [TIMEOUT]
IP: 126.96.36.199 [TIMEOUT]

Um método mais confiável e robusto para solucionar o seu problema seria por meio da taxa de disponibilidade de cada IP da lista.
Segue exemplo capaz de calcular a taxa de disponibilidade dos IPs de uma lista:
#!/bin/bash

IP_LIST=( 220.127.116.11
          127.0.0.1
          10.1.1.19
          220.127.116.11
          18.104.22.168
          184.108.40.206
          126.96.36.199 )

for ((i = 0; i < ${#IP_LIST[@]}; i++)); do

    PCKT_LOSS=$(ping -q -c5 "${IP_LIST[i]}" | grep -oP '\d+(?=% packet loss)')

    echo "IP: ${IP_LIST[i]} [Disponibilidade: $[100 - ${PCKT_LOSS}]%]"

done

Saída:
IP: 184.108.40.206 [Disponibilidade: 0%]
IP: 127.0.0.1 [Disponibilidade: 100%]
IP: 10.1.1.19 [Disponibilidade: 100%]
IP: 18.104.22.168 [Disponibilidade: 0%]
IP: 220.127.116.11 [Disponibilidade: 0%]
IP: 184.108.40.206 [Disponibilidade: 0%]
IP: 18.104.22.168 [Disponibilidade: 0%]

Espero ter ajudado!

Retorno errado do comando ping