Independent Samples T-test vs Paired Samples T-test for hypothesis testing (machine learning algorithms comparison)

Question: The scenario is as follows: I have 1 dataset and I want to compare the performance of different algorithms. Let's say A, B, C.
I train each algorithm a 1000 times in one training loop. At the beginning of each loop the dataset will be split into a train-test split (random split). At the end I will have 3 distributions, each containing 1000 scores (e.g., AUC scores).
Question: Which T-test should I perform? A independent samples t-test or a paired-samples t-test. I'm struggling with the difference in independence, and also an indepedent samples-test assumes that variance between is roughly the same.
Could someone please help me?
Gr
Answer: You need to clearly state your hypothesis.  For some reason, this is a step that is commonly overlooked by people who wish to make some kind of statistical inference, and instead the focus is on "what test do I use" as if all that anyone needs to do is crunch numbers through some statistical procedure to get at the answer.  The choice of hypothesis directly informs the appropriate testing procedure.
In your case, I don't know if what you want is to make an inference about the mean scores, the median scores, or the shape of the distribution of the scores, or some other distributional property of the scores; you have not specified this.
Moreover, you have not specified whether you are interested in an omnibus test or a pairwise comparison between algorithms.
Both of the above are necessary to specify, in the sense that not doing so means you cannot choose an appropriate test.
Furthermore, there are assumptions about the parameter(s) for which you wish to make such an inference.  For instance, if the inference is on the mean scores, we might reasonably say that the mean will be approximately normally distributed, but this may not be the case.  Extreme deviations from normality would change your choice of test statistic.
I was going to provide examples of specific tests; e.g., a one-way ANOVA, or a pairwise nonparametric test like Mann-Whitney, but realized that such information would be liable to be misused in the absence of an inadequate description of your hypothesis.


Error message when import package with Miniconda environment

Question: I have installed Miniconda and create from this a env named data.
Then I tried to do something simple:
import pandas as pd

but get this error message from Vscode.
Any idea ?
Échec du démarrage du Kernel.
Traceback (most recent call last):
  File "/Users/jacques/miniconda3/envs/data/lib/python3.10/runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/Users/jacques/miniconda3/envs/data/lib/python3.10/runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "/Users/jacques/miniconda3/envs/data/lib/python3.10/site-packages/ipykernel_launcher.py", line 15, in <module>
    from ipykernel import kernelapp as app
  File "/Users/jacques/miniconda3/envs/data/lib/python3.10/site-packages/ipykernel/kernelapp.py", line 19, in <module>
    from IPython.core.application import (  # type:ignore[attr-defined]
  File "/Users/jacques/miniconda3/envs/data/lib/python3.10/site-packages/IPython/__init__.py", line 54, in <module>
    from .terminal.embed import embed
  File "/Users/jacques/miniconda3/envs/data/lib/python3.10/site-packages/IPython/terminal/embed.py", line 15, in <module>
    from IPython.core.interactiveshell import DummyMod, InteractiveShell
  File "/Users/jacques/miniconda3/envs/data/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 73, in <module>
    from IPython.core.history import HistoryManager
  File "/Users/jacques/miniconda3/envs/data/lib/python3.10/site-packages/IPython/core/history.py", line 11, in <module>
    import sqlite3
  File "/Users/jacques/miniconda3/envs/data/lib/python3.10/sqlite3/__init__.py", line 57, in <module>
    from sqlite3.dbapi2 import *
  File "/Users/jacques/miniconda3/envs/data/lib/python3.10/sqlite3/dbapi2.py", line 27, in <module>
    from _sqlite3 import *
ImportError: dlopen(/Users/jacques/miniconda3/envs/data/lib/python3.10/lib-dynload/_sqlite3.cpython-310-darwin.so, 0x0002): Symbol not found: _sqlite3_enable_load_extension
  Referenced from: <1B6E2CAC-D818-304D-9C3C-B2E32B00D8B7> /Users/jacques/miniconda3/envs/data/lib/python3.10/lib-dynload/_sqlite3.cpython-310-darwin.so
  Expected in:     <567CDD63-191D-36E4-959B-7DE47C7AFD7A> /usr/lib/libsqlite3.dylib.
Pour plus d'informations, consultez Jupyter log.

Comment: @Wayne, thx it seems that `conda install libsqlite --force-reinstall -y` works fine and I don't get the error message anymore.
Comment: @wjandrea, you were right. Even a `print('hello')` did not work.
Comment: I'm not quite sure why your import of pandas is triggering that message. I wonder if you didn't troubleshoot well enough to get at the specific cause there or if in truncating your shared traceback, you left out pertinent info. Anyway, [this post](https://stackoverflow.com/q/74837553/8508004) looks pertinent to your error. (Perhaps, the answer in the link in blue [here](https://stackoverflow.com/q/77446827/8508004) might help you in understanding what happened to trigger what you are seeing, too.)
Comment: Please [edit] to add a translation. I'm not fluent in French, but it's something like: "Error starting the kernel. ... For more information, see Jupyter log."
Comment: Notice that the traceback doesn't show your `import` line or even mention `pandas`, so this error has nothing to do with the import; if you did `print('hello')` instead, you'd get the same error. (FYI @Wayne) If you want to [edit] in light of that, please do. And to be clear, the kernel that it's referring to is IPykernel, which is the backend you're using with Jupyter.
Answer: For the record...
From the commennts, this solution to a similar traceback helped in this case:
conda install libsqlite --force-reinstall -y


Inequality proof with sequences - showing $x_n<x_{n+1}$ for $x_{n+1}=x_n^2 + 1/4$, $x<1/2$

Question:
So I was doing part 2 of this question and I wanted to know if my approach is correct.
$x_{n+1} - x_n = x_n^2 + 1/4 - x_n$
Now since it is a sequence of positive terms
$x_n$ > 0
Therefore $x_n^2 + 1/4 > 1/4 > x_n$
Hence  $x_n^2 + 1/4 - x_n > 0$
$x_{n+1} - x_n > 0$
$x_n < x_{n+1}$
Comment: I think your reasoning is not so good. See my post.
Comment: The same idea from [my answer](https://math.stackexchange.com/a/2880997/291201) to your other question works here as well: $\;x_{n+1}-x_n=x_n^2-x_{n-1}^2\,$.
Comment: In case it helps, here is another question about the same recurrence: [$a_{n+1}=\frac{1}{4}+a_n^2$ is converging and have a limit](https://math.stackexchange.com/q/246688). Drawing [cobweb plot](https://en.wikipedia.org/wiki/Cobweb_plot) might help to get some intuition in problems like this, you can see some examples [here](https://chat.stackexchange.com/rooms/14150/conversation/pictures-illustrating-iterations-for-x-n1fx-n) and [here](https://math.stackexchange.com/q/1884302). In this case, the function is $f(x)=x^2+\frac14$.
Answer: (i).
Because by assumption of the induction  $$x_{n+1}=x_n^2+\frac{1}{4}<\frac{1}{4}+\frac{1}{4}=\frac{1}{2}.$$
$(ii).$
$$x_{n+1}-x_n=x_n^2-x_n+\frac{1}{4}=\left(x_n-\frac{1}{2}\right)^2>0.$$


Calculate standard deviation of given data

Question: I want to find the standard deviation of the following data:
18: 200 times
19: 200 times
20 : 120 times
21: 340 times.
Is this the correct formula:
$\sqrt{\frac{18^2 \times 200+19^2 \times 200 + 20^2 \times 120 + 21^2 \times 340}{200+200+120+340}- (\frac{18 \times 200+19 \times 200 + 20\times 120 + 21 \times 340}{200+200+120+340})^2}$  ?
Thanks!
Answer: This is correct as long as you are not using Bessel's correction to calculate sample variance (which is dividing by $n-1$ instead of $n$ to obtain an unbiased estimator). If you are using Bessel's correction, you'll need to multiply your final answer by $\sqrt{\frac{200+200+120+340}{200+200+120+340-1}}$.


What is the probability a person leaves via a certain exit?

Question: <code>             | Exit 1 |             | Exit 4 |
             |        |             |        |
             |        |             |        |
             |        |             |        |
_____________|        |_____________|        |________

Exit 2           S1                    s2         Exit 6
_____________          _____________          ________
             |        |             |        |
             |        |             |        |
             |        |             |        |
             | Exit 3 |             | Exit 5 |

</code>
Hopefully the above diagram is clear. There are 6 exits. There is a bug that starts at S1, we equal probability he can go to Exit1, Exit2, Exit3, or s2. Once at S2, he can go to S1 Exit6, Exit5, Exit4 with equal probability. Once you go to an exit, you are no longer able to return and you are done. What is the probability the person leaves via Exit 6.
I've tried solving this with a markov matrix, but I think there is a simpler solution. Any hints / how to approach this more directly?
Comment: There are only two  active states, just consider what happens at $S_1, S_2$.
Comment: $3a+3b=1$, $a$ being the probability of leaving through exit 1, 2 or 3, $b$ 4, 5 or 6. And $a=1/4+b/4$, by symmetry.
Comment: $a = 1/4 + b/4$?
Comment: To leave through exit 1, you have a quarter chance to leave on first turn, plus the chance of going to S2 on first turn ($1/4$) and eventually leaving through exit 1, which is the odd of leaving through one of the doors of the opposite side, i.e. $b$.
Comment: I don't see that, what do you mean by: "which is the odd of leaving through one of the doors of the opposite side, i.e. b"
Comment: Assuming you went to S2 at the end of first turn, E1, E2 and E3 now have the law that E4, E5 and E6 had on the first turn.
Answer: For $i\in \{1,2\}$, let  $P_i$ denote the probability that you will  eventually leave by Exit $6$ given that you are currently in state $S_i$.  Thus $P_1$ is the answer you want.
We note that $$P_1=\frac 34\times 0 +\frac 14\times P_2\implies 4P_1=P_2$$
and  $$P_2=\frac 14\times 1 +\frac 12\times 0 +\frac 14\times P_1\implies 4P_2=1+P_1$$
this system is easily solved and yields $$\boxed {P_1=\frac 1{15}}$$.
Comment: Pretty simple solution...Thanks! How can I think of this in context of markov matrix? How did you see this solution?
Comment: $P(E_8|S_1) = \frac{1}{4}P(E_8|S_2)$ and $P(E_8|S_2) = \frac{1}{4} + \frac{1}{4}P(E_8|S_1)$ (just rewriting with some easier notation for me)
Comment: This is a pretty standard approach to Markov processes that have a small number of states.  You can see quickly that either you end the process after a couple moves or you find yourself back at the start.  That's all that the method says.
Answer: I think your Markov matrix idea is quite simple and effective. Either raise it to a large power or look at its Eigenvalues and the steady-state should become quite clear.
Another option is to use a directed graph/network with 8 nodes but this would likely then lead to an adjacency matrix and be very similar to your Markov approach.
Answer: Let $P_n$ be the probability of exiting by exit 6 in $n$ steps, $n$ must be even.
$$ P_2 = P(S_1 \to S_2)\times P(S_2 \to E_6) =\frac 1{16}$$
$$P_4 = P(S_1 \to S_2)\times P(S_2 \to S_1)\times P(S_1 \to S_2)\times P(S_2 \to E_6)= \frac 1{16} \times P_2$$
So the total probability of leaving by $E_6$ is given by the sum of the geometric series...
$$ P = \sum_{k=1}^\infty \left( \frac 1{16} \right )^k = \frac 1{15}
$$


UIScrollView for infinite slideshow

Question: I am having a set of images.How can i use them to set an infinite slide show.The images should continue as a loop.I want to use only horizontal scroll in both directions.
Answer: Infinite Paging View
i think this is what you want.
Answer: You can set this using this
<code> self.scrollviewImageList.contentSize = CGSizeMake((self.imgTab.frame.size.width*no_of_images),self.imgTab.frame.size.height);
</code>
Comment: scrollviewImageList is your scrollview and imgTab is your image view.
Comment: What is imgTab object.How can i define it?
Comment: Also what is scrollviewimagelist object?? can you give an example.

UIScrollView for infinite slideshow


When is there a ring structure on an abelian group $(A,+)$?

Question: Given an abelian group $(A,+)$, what are conditions on $A$ that ensure there is or isn't a unitary ring structure $(A,+,*)$? That is, an associative bilinear operation $* : A^2 \to A$  with an identity $1_A \in A$.
A possible follow-up question would be conditions for a nontrivial rng structure on $A$ (indeed, the multiplication $ab = 0$ always gives a rng structure).
For example, if $A$ is finitely generated, then by the structure theorem on finite type abelian groups, $A \simeq \mathbb Z^r \times \prod \mathbb Z/p_i^{a_i} \mathbb Z$ and it has a product ring structure.
On the other hand, $\mathbb Q / \mathbb Z$ doesn't: if it did, the unit $u=[p/q]$ would have finite order $q$, and $\forall x \in \mathbb Q / \mathbb Z, qx = q(u*x) = (qu)*x = 0$, but $q(1/2q) = 1/2 \neq 0$. More generally, by this question, if every element has finite order but the orders are not bounded, then there is no ring structure on $A$.
Is this condition also necessary? I doubt it: I have trouble envisioning a ring structure on $(\mathbb R / \mathbb Z, +) = (S^1, \cdot)$, but not every element has finite order in $S^1$. The argument also completely fails for rngs.
(Note that my question is different from the one I linked: this one simply asked for a counterexample, I'm asking for general conditions)
Comment: Weak evidence that this is an open problem: http://mathoverflow.net/questions/92557/is-the-class-of-additive-groups-of-rings-axiomatizable
Comment: A partial answer is given in *Infinite abelian groups* by Kaplansky: An abelian group of bounded order is a direct sum of cyclic groups (theorem 6 page 17).
Comment: @QiaochuYuan: I don't know if this says anything about openness, they are talking about first-order axiomatization, not recognition in general. But it's possible that the problem is much more difficult than expected.
Comment: @Seirios: Thanks for the reference.
Comment: @nik: I'd be more likely not to see an answer to that MO question in worlds where this is an open problem than in worlds where it's not (e.g. in some worlds it's a very easy problem, the answer can be first-order axiomatized, and someone knew that and posted an answer to the MO problem). Are you familiar with the Bayesian definition of evidence?
Comment: Here is an argument for $\mathbb{R}/\mathbb{Z}$: If $(\mathbb{R}/\mathbb{Z},*)$ were a ring with unit $u$ then since $\mathbb{R}/\mathbb{Z}$ is divisible there would exist an element $v$ such that $2v=u$, but then $1/2 = u*(1/2) = 2v*(1/2) = v*1 = 0$, a contradiction.
Answer: In a unitary ring you always have the fundamental concept of "characteristic". If you have a torsion Abelian group $G$, and you want a unitary ring structure on $G$, then first of all you need to choose a unit. If $g\in G$ is such a unit, then you are forced to have a ring of characteristic $n=|g\mathbb Z|$. This tells you that $nh=0$ for all $h\in G$, so if $G$ does not have a finite exponent, you cannot have a ring structure on $G$.
If you want a source for many torsion-free counterexamples you can proceed as follows. You can use a famous theorem of Saharon Shelah to find, for any infinite cardinal $\alpha$, $2^\alpha$ many non-isomorphic torsion-free abelian groups of cardinality $\alpha$ and whose endomorphism ring is a subring of the rationals. In particular, given such a $G$, $\operatorname{End}(G)$ is countable. Notice that, if you have a ring structure on $G$, then there is an injection $G\to\operatorname{End}(G)$ sending $g$ to left-multiplication by $g$.
Let me add that these matters are nicely discussed in Chapter XVII of the second volume of Infinite Abelian Groups by Laszlo Fuchs (the title of the chapter is "Additive groups of rings").
EDIT: I briefly sum up some of the matters treated by Fuchs. Let me start by quoting his final "note".

The problem of defining ring structures on an additive group was raised by Beaumont who considered rings on direct sums of cyclic groups. Nearly at the same time, Szele investigated zero-rings, and Ridei and Szele and Beaumont and Zuckerman described the rings on subgroups of the rationals. A rather systematic study of constructing rings on a group appeared in Fuchs where the fundamental role of the basic subgroup was pointed out. More satisfactory results have been obtained for torsion-free groups of finite rank by Bedumont and Pierce [...].
It would be a serious mistake to expect too much from a study of the additive structures of rings, as far as ring theory is concerned. In many important cases the additive structures are too trivial [e.g., torsion-free divisible or an elementary $p$-group] to give any real information about the ring structure. This especially applies to the torsion-free case, where a close interrelation between the additive and the multiplicative structures can be expected only if the additive group is more complicated. One should, however, remember that there are intriguing questions even if the additive group is too easy to describe; for instance, we do not know of any uncountable Noetherian ring whose additive group is free.

Let me say that your question is open in general but there are answers for particular classes of groups, such as torsion-free groups of rank one, where one can not only say when a ring structure exists but also encode somehow all the possible ring structure, even non-associative or non-unitary. The fact is that one of the tools for studying ring structures on a group $G$ is the group of multiplications on $G$, $\operatorname{Mult}(G)$. This is a group in general only if you include non-associative multiplications.
The chapter starts studying general properties of $\operatorname{Mult}(G)$ (for example one can show that $\operatorname{Mult(G)}\cong\operatorname{Hom}(G\otimes G,G)$). After that it passes to general conditions on torsion and torsion-free groups (especially divisible, or finite rank, or even rank $1$ for the best results). Notice that the main focus is not exactly on your question but it is on an even more delicate matter, that is, given a group $G$ try to classify all the rings that have $G$ as underlying group. Proceeding with the chapter more particular questions are investigated. For example, one can give a very precise form for the additive groups of Artinian rings (see Theorem 122.4). There are also precise results for regular rings and the chapter ends (as all the chapters of this book) asking some intriguing questions on the matter.
It may happen that this classical book is not up to date as it goes back to 1973 but, in my experience, you can be quite sure that, if something related to Abelian groups was known before 1973, then it is in this book. I was looking for more recent information about your question something like 3 years ago but, as far as I remember, I could not find anything relevant after Fuchs' book.
Comment: Regarding the Noetherian uncountable example, [this](http://www.ams.org/journals/proc/1977-066-02/S0002-9939-1977-0450426-2/S0002-9939-1977-0450426-2.pdf) paper settles the question in the affirmative.
Comment: @nik if you read all the paragraph you can see that I'm speaking about torsion Abelian groups... $\mathbb Z$ is obviously not in there.
I can edit to make it clearer if you think it is the case
Comment: Ah yes, I missed the adjective torsion, sorry. I was confused since I already cover this in my question.
Comment: yes, you are right, I just wanted to be complete... to show some counter-example in the torsion case but to show that there exist also many examples in the torsion-free case. The real answer is the reference to the book of Fuchs.
Comment: I don't have access to the book right now, unfortunately. Could you possibly sum up the gist of it, so that I can accept your answer?


Reasons socket.io emit not receiving messages?

Question: I'm working on an angular/node app where people can have many 1:1 chats with other users (like Whatsapp without groups) using socket.io and btford's angular-socket module (https://github.com/btford/angular-socket-io). Right now A) a client joins a socket.io room using emit. The client code is:
mySocket.emit('joinroom', room);

Server code is:
socket.on('joinroom', function (room){
  socket.join(room);
});

B) chat messages are sent to server via emit. Client code is
mySocket.emit('sendmsg', data, function(data){
  console.log(data);
});

and C) the server should send messages to others in the room via broadcast. Server code is:
socket.on('sendmsg', function (text, room, sender, recipient, timestamp) {
  // Some code here to save message to database before broadcasting to other users
  console.log('This works');
  socket.broadcast.to(room).emit('relaymsg', msg);
});

Client code is
$scope.$on('socket:relaymsg', function(event, data) {
  console.log('This only sometimes works');
  // do stuff to show that message was received
});

A and B seem to work fine, but C seems to be very unreliable. The server code seems to be ok, but the client does not seem to receive the message. Sometimes it works, and sometimes it does not. ie 'This works' always shows up, but 'This only sometimes works' does not always show up.
1) Any thoughts on what could be causing this issue? Are there any errors in my code?
2) Is broadcast and rooms the right way to be setting this up if there are many users, all of which can have multiple 1:1 chats with other users?
In case it helps, this is the factory code for the angular-socket module
.factory('mySocket', function (socketFactory, server) {
  var socket = socketFactory({
    ioSocket: io.connect(server)
  });
  socket.forward('relaymsg');
  return socket;
});

Appreciate any help you can provide!! Thanks in advance!
Comment: Are you sure client code after `C` is correct, isn't the `$` a typo  ?
Comment: What part of your angular code is emitting the "socket:relaymsg" message?
Comment: @MaximePiraux, not sure exactly which part you're referring to, assume you mean the "$scope.$on"... I'm basically following the examples here: https://github.com/btford/angular-socket-io
Comment: @laggingreflex (lol on the username btw), the line under part C should be emitting, ie
socket.broadcast.to(room).emit('relaymsg', msg);
Comment: If you use `DEBUG=* node app.js` do you see C connecting or disconnecting?
Answer: Thanks everyone for the comments, I believe I found the main issues. There were two things I think causing problems:
1) The bigger issue I think is that I'm use node clusters, and as a result users might join rooms on different workers and not be able to communicate with each other. I've ended up adding sticky sessions and Redis per the instructions here: http://socket.io/docs/using-multiple-nodes/
Sticky sessions is pretty useful, just as an FYI since the docs don't mention it, the module automatically creates workers and re-spawns them if killed
I couldn't find a ton of examples of how to implement sticky+redis since socket.io 1.0 is relatively new and seems to deal with Redis differently from prior versions, but these were very helpful:
https://github.com/Automattic/socket.io-redis/issues/31
https://github.com/evilstudios/chat-example-cluster/blob/master/index.js
2) Every time the user closed their phone it would disconnect them from the chat room, even if the chat room was the last screen open on the phone
Hope that helps people in the future!


Como fazer com que o :hover pegue em todas as LI

Question: Negócio é o seguinte, tenho um div que segura minhas li, e dentro dessas li tem uma imagem e três li com textos, meu objetivo é fazer com que, quando o mouse for passado em cima dessa li, a imagem mude dando um efeito hover e os texto também mudem a cor, mesmo não passando o mouse sobre eles, bom e assim para a imagem também quando passado o mouse pelos textos, dando o efeito hover nas imagens

FUNDOS

FUNDOS PARA XAT

VER MAIS

Comment: postei o pedaço do código que estou com dificuldade
Comment: na li pai no caso `li > a > box`, que quando a pessoa passar o mouse nela, mude o hover da imagem e as cores dos h1, span e a
Answer: Use o coringa * para alterar a cor de todo o texto dos elementos filhos da div .box:

$('.box').on('mouseover mouseleave', function(e){
  $(this).find('img').attr('src', e.type == 'mouseover' ? 'https://images-na.ssl-images-amazon.com/images/I/41n3kSb1zvL.jpg' : 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/48/Basketball.jpeg/220px-Basketball.jpeg');
});
ul li{
   float:left;
}
ul li .box{
   width: 200px;
   height:200px;
}
ul li .box ul li img{
   width: 100%;
   height:100%;
}

.box:hover * {
   color: red;
}

FUNDOS

FUNDOS PARA XAT

VER MAIS

Como a imagem não é um background, para alterá-la, você terá que usar JavaScript ou jQuery.
Comment: achei um exemplo aqui no site mesmo, que fazia o efeito hover em imagem com after, até fiz o exemplo aqui e funcionou, porém sem oque eu preciso, que é quando passar o mouse pela li pai mudar o back da imagem e as cores ao mesmo tempo, você poderia dar um exemplo de como fazer com jquery ?
Comment: @Mayron Atualizei a resposta.. Mas se quiser eu posso fazer o :after.
Comment: perfeito, é isso mesmo que eu preciso, você é 10 valeu!!!
Comment: @Mayron Valeu!!


How to use reflection to cast a control as its type in order to modify properties?

Question: Here's an example of what I currently do:
book enable = false;
foreach (Control c in controlList)
{
    if (c is MyTextBox)
    {
        (c as MyTextBox).Enabled = enable;
    }
    if...
    ...
}

Instead of having multiple if statements for every type of control, is there a way to get the type of the control in order to cast and then be able to access and set a property of that control?
Comment: Enabled is a property of the base Control class, so why cast it at all, just set c.Enabled = enable, unless there are other reasons?
Comment: By the way, I'll assure you that using reflection to do this is going to be a lot more verbose. If you need to cast, you've already verified the type, so you should use a straight cast, not the "as" operator since it has additional overhead.
Comment: I have edited your title. Please see, "[Should questions include "tags" in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not".
Answer: This is a great example of when not to use reflection.
The Control class contains an Enabled property that you can use for all descendants of Control to change their enabled state.  So the simple way to change the enabled state of a collection of controls is:
bool enable = false;
foreach (Control c in controlList)
    c.Enabled = enable;

Or (now that you've mentioned the System.Web.UI namespace) you can do this for your WebControl-derived objects, assuming that the controlList collection can contain things that derive from Control but no necessarily from WebControl:
foreach (WebControl c in controlList.OfType<WebControl>())
    c.Enabled = enable;

Reflection is handy in some situations and you can do some pretty cool things with it.  It's verbose and kind of tough to get your head around sometimes, and often it can be done more simply other ways.
Where it would be useful is if you had a collection of arbitrary objects of different types, some of which may have a bool Enabled property that you can set, but that there is no guarantee that they have a common base class that you can access the Enabled property on.  Then you could do something like this:
bool enabled = false;
foreach (var obj in objectList)
{
    var tObj = obj.GetType();
    PropertyInfo piEnabled = tObj.GetProperty("Enabled", typeof(bool));
    if (piEnabled != null && piEnabled.CanWrite)
        piEnabled.SetValue(obj, enabled);
}

A lot more complex, a bit more opaque, and much, much slower than simply accessing the property via the Control parent class.
Comment: Thanks this was my initial thought but even though I am referencing System.Web.UI, it won't recognize the enabled property. Is there something else I need to do?
Comment: @Tom Oh, you should have specified that you were using web controls rather than form controls.  What you want then is `WebControl` rather than `Control`.  That's where the `Enabled` property is located in the `System.Web.UI` classes.  If you go to the MSDN page for any of the controls you are using and show all the inherited properties it will tell you which base class it inherits that property from.


Dealing with heteroscedasticity when dependent variable is already log-transformed

Question: I have already log-transformed the dependent variable but there is still heteroscedasticity in the residual-fitted plot. What one usually does in situations like this? My current regression technique in linear regression.

The data I am experimenting with is from a Kaggle competition: Santander Value Prediction
Comment: Would you please post a link to the raw "un-transformed" data?
Comment: If you have not yet done so, I suggest adding an offset term to the fit.
Answer:
you could try other transformations. In R, https://stat.ethz.ch/R-manual/R-devel/library/MASS/html/boxcox.html looks for an optional power transformation
If you can't remove the heteroscedasticity by a suitable transformation, you have to fit a model that accounts for changes in the variance. In R, this can be done with the weights option in the gls function.


Allegro 5 drawing to buffer

Question: I am making a program that will draw balls bouncing around the screen. I am currently working on the part that draws the balls.
My code consists of the following:

BallEngine Class - Manage all the Allegro functions/objects
BallManager Class - Manages all of the balls
Ball Class - Hold information about a ball
main.cpp - Game loop, etc.

BallEngine.h:
#pragma once
#include <allegro5\allegro.h>
#include <allegro5\allegro_font.h>
#include <allegro5\allegro_ttf.h>
#include "BallManager.h"

ALLEGRO_DISPLAY *display;

class BallEngine
{
private:

    bool fullScreen;
    int fps;
    bool running;

public:
    BallManager BManager;
    bool getFullScreen();
    bool getIsRunning();
    void updateFullScreen();
    void setFullScreen(bool value);
    void setIsRunning(bool value);
    int getFPS();

    //Allegro Objects
    ALLEGRO_FONT *deafault_font_12;
    ALLEGRO_EVENT_QUEUE *event_queue;
    ALLEGRO_TIMER *timer;

    //Colors
    ALLEGRO_COLOR RED;
    ALLEGRO_COLOR GREEN;
    ALLEGRO_COLOR BLUE;
    ALLEGRO_COLOR YELLOW;
    ALLEGRO_COLOR PINK;
    ALLEGRO_COLOR LIGHT_BLUE;
    ALLEGRO_COLOR WHITE;
    ALLEGRO_COLOR BLACK;

    //Debug
    bool showDebug;
    void drawBallInfo(int x, int y, int id); //Draws information about a certain ball

    BallEngine(int width, int height);
    ~BallEngine(void);
};

BallEngine.cpp:
#include "BallEngine.h"

BallEngine::BallEngine(int width, int height)
{
    running = true;
    showDebug = false;
    fps = 60;
    al_init();
    if(!al_init())
    {
        printf("Failed to initalize Allegro \n");
    }
    al_install_keyboard();
    if(!al_install_keyboard())
    {
        printf("Failed to initalize keyboard \n");
    }
    al_init_font_addon();

    al_init_ttf_addon();

    fullScreen = false;
    updateFullScreen();

    deafault_font_12 = al_load_font("arial.ttf", 12, 0);
    event_queue = al_create_event_queue();
    al_register_event_source(event_queue, al_get_keyboard_event_source());
    timer = al_create_timer(1.0/fps);
    al_register_event_source(event_queue, al_get_timer_event_source(timer));
    display = al_create_display(width, height);

    //Define engine colors
    RED = al_map_rgb(255,0,0);
    GREEN = al_map_rgb(0,255,0);
    BLUE = al_map_rgb(0,0,255);
    YELLOW = al_map_rgb(255,255,0);
    PINK = al_map_rgb(255,0,255);
    LIGHT_BLUE = al_map_rgb(255,255,0);
    WHITE = al_map_rgb(255,255,255);
    BLACK = al_map_rgb(0,0,0);
}

BallEngine::~BallEngine(void)
{
}
bool BallEngine::getFullScreen()
{
    return fullScreen;
}
bool BallEngine::getIsRunning()
{
    return running;
}
void BallEngine::updateFullScreen()
{
    if ( fullScreen == true )
    {
        al_set_new_display_flags(ALLEGRO_FULLSCREEN);
    }
    else
    {
        al_set_new_display_flags(ALLEGRO_WINDOWED);
    }
}
void BallEngine::setFullScreen(bool value)
{
    fullScreen = value;
}

int BallEngine::getFPS()
{
    return fps;
}

void BallEngine::drawBallInfo(int x, int y, int id)
{
    if(BManager.isBallExist(id))
    {
        al_draw_textf(deafault_font_12, RED, x, y, 0, "X: %i Y: %i Velocity: %i Angle: %i Radius: %i Color %ALLEGRO_COLOR ", BManager.getBall_X(id), BManager.getBall_Y(id), BManager.getBall_Velocity(id), BManager.getBall_Angle(id), BManager.getBall_Radius(id), BManager.getBall_Color(id));
    }
    else
    {
        printf("Failed to draw ball %i information: Ball selceted out of range \n", id);
    }
}

BallManager.h:
#pragma once
#include <iostream>
#include <vector>
#include "Ball.h"
#include <allegro5\allegro.h>
class BallManager
{
private:
    std::vector<Ball*> List;
public:
    //Get functions
    int getBall_X(int id);
    int getBall_Y(int id);
    int getBall_Velocity(int id);
    int getBall_Angle(int id);
    int getBall_Radius(int id);
    ALLEGRO_COLOR getBall_Color(int id);

    //Set Functions
    void setBall_X(int id, int value);
    void setBall_Y(int id, int value);
    void setBall_Velocity(int id, int value);
    void setBall_Angle(int id, int value);
    void setBall_Radius(int id, int value);
    void setBall_Color(int id, ALLEGRO_COLOR value);

    bool isBallExist(int id); //Returns true if a ball at index id exists. Else returns false.

    void CreateBall(int x, int y, int velocity, int angle, int radius, ALLEGRO_COLOR color);
    void DeleteBall(int id);

    void drawBall(int id);
    void drawBalls();

    void updateBalls(); //NOT YET DONE

    BallManager(void);
    ~BallManager(void);
};

BallManager.cpp:
#include "BallManager.h"

BallManager::BallManager(void)
{
}

BallManager::~BallManager(void)
{
}
//Get Functions:
int BallManager::getBall_X(int id)
{
    return List[id]->getPos_X();
}
int BallManager::getBall_Y(int id)
{
    return List[id]->getPos_Y();
}
int BallManager::getBall_Velocity(int id)
{
    return List[id]->getVelocity();
}
int BallManager::getBall_Angle(int id)
{
    return List[id]->getAngle();
}
int BallManager::getBall_Radius(int id)
{
    return List[id]->getRadius();
}
ALLEGRO_COLOR BallManager::getBall_Color(int id)
{
    return List[id]->getColor();
}

//Set functions:
void BallManager::setBall_X(int id, int value)
{
    List[id]->setPos_X(value);
}
void BallManager::setBall_Y(int id, int value)
{
    List[id]->setPos_Y(value);
}
void BallManager::setBall_Velocity(int id, int value)
{
    List[id]->setVelocity(value);
}
void BallManager::setBall_Angle(int id, int value)
{
    List[id]->setAngle(value);
}
void BallManager::setBall_Radius(int id, int value)
{
    List[id]->setRadius(value);
}
void BallManager::setBall_Color(int id, ALLEGRO_COLOR value)
{
    List[id]->setColor(value);
}

void BallManager::CreateBall(int x, int y, int velocity, int angle, int radius, ALLEGRO_COLOR color)
{
    Ball* ball = new Ball(x, y, velocity, angle, radius, color);
    List.push_back(ball);
}
void BallManager::DeleteBall(int id)
{
    if(isBallExist(id))
    {
        delete List[id];
        List.erase(List.begin()+id);
    }
    else
    {
        printf("Failed to delete ball %i information: Ball selceted out of range \n", id);
    }
}
bool BallManager::isBallExist(int id)
{
    if((id+1) > List.size() || id < 0)
    {
        return false;
    }
    return true;
}
void BallManager::drawBall(int id)
{
    List[id]->Draw();
}
void BallManager::drawBalls()
{
    int total = List.size();
    for(int index = 0; index < total; index++)
    {
        List[index]->Draw();
    }

}
void updateBalls()
{
    //TODO
}

Ball.h:
#pragma once
#include <allegro5\allegro.h>
#include <allegro5\allegro_primitives.h>

class Ball
{
private:
    int x;
    int y;
    int velocity; //Positive is left side of screen, Negitive is right side of screen
    int angle; // Angle derived from the positive vertical
    int radius;
    ALLEGRO_COLOR color;

public:
    //Get Functions
    int getPos_X();
    int getPos_Y();
    int getVelocity();
    int getAngle();
    int getRadius();
    ALLEGRO_COLOR getColor();

    //Set Functions
    void setPos_X(int value);
    void setPos_Y(int value);
    void setVelocity(int value);
    void setAngle(int value);
    void setRadius(int value);
    void setColor(ALLEGRO_COLOR value);

    //Draws to screen
    void Draw();

    //Constructor
    Ball(int Start_X, int Start_Y, int Start_Velocity, int Start_Angle, int Start_Radius, ALLEGRO_COLOR Start_Color);

    //Desctructor
    ~Ball(void);
};

Ball.cpp:
#include "Ball.h"

Ball::Ball(int Start_X, int Start_Y, int Start_Velocity, int Start_Angle, int Start_Radius, ALLEGRO_COLOR Start_Color)
{
    x = Start_X;
    y = Start_Y;
    velocity = Start_Velocity;
    angle = Start_Angle;
    radius = Start_Radius;
    color = Start_Color;
}

Ball::~Ball(void)
{
}

//Get functions
int Ball::getPos_X()
{
    return x;
}
int Ball::getPos_Y()
{
    return y;
}
int Ball::getVelocity()
{
    return velocity;
}
int Ball::getAngle()
{
    return angle;
}
int Ball::getRadius()
{
    return radius;
}
ALLEGRO_COLOR Ball::getColor()
{
    return color;
}

//Set functions
void Ball::setPos_X(int value)
{
    x = value;
}
void Ball::setPos_Y(int value)
{
    y = value;
}
void Ball::setVelocity(int value)
{
    velocity = value;
}
void Ball::setAngle(int value)
{
    angle = value;
}
void Ball::setRadius(int value)
{
    radius = value;
}
void Ball::setColor(ALLEGRO_COLOR value)
{
    color = value;
}

void Ball::Draw()
{
    al_draw_filled_circle(x, y, radius, color);
}

main.cpp:
#include <allegro5\allegro.h>
#include "BallEngine.h"
int ScreenWidth = 620;
int ScreenHeight = 480;

int main()
{
    BallEngine Engine(ScreenWidth, ScreenHeight);

    //Test balls
    Engine.BManager.CreateBall(10, 20, 0, 0, 5, al_map_rgb(0,0,255));
    Engine.BManager.CreateBall(11, 21, 1, 1, 5, al_map_rgb(0,0,255));
    Engine.BManager.CreateBall(12, 22, 2, 2, 5, al_map_rgb(0,0,255));
    Engine.BManager.CreateBall(13, 23, 3, 3, 5, al_map_rgb(0,0,255));

    ALLEGRO_EVENT events;
    int selected = 0; //Used to show which ball is selected

    al_start_timer(Engine.timer);
    while(Engine.getIsRunning())
    {
        al_wait_for_event(Engine.event_queue, &events);
        if(events.type == ALLEGRO_EVENT_KEY_DOWN)
        {
            //Keyboard Input
            switch(events.keyboard.keycode)
            {
                case ALLEGRO_KEY_ESCAPE:
                    Engine.setIsRunning(false);
                    break;
                case ALLEGRO_KEY_RIGHT:
                    Engine.showDebug = !Engine.showDebug; //Toggles the selected balls info
                    break;
                case ALLEGRO_KEY_UP:
                    selected++;
                    break;
                case ALLEGRO_KEY_DOWN:
                    selected--;
                    break;
                case ALLEGRO_KEY_DELETE:
                    Engine.BManager.DeleteBall(selected); //Deletes a certain ball
                    break;
            }
        }
        else if(events.type == ALLEGRO_EVENT_TIMER)
        {
            //Update

        }

        //Draw
        Engine.BManager.drawBalls();
        //Show debug
        if(Engine.showDebug == true)
        {
            Engine.drawBallInfo(10, 10, selected);
        }

        al_flip_display();
        al_clear_to_color(al_map_rgb(0,0,0));
    }
    return 0;
}

I am having trouble drawing the balls. In allegro 4, you would pass a buffer on which to draw to and then draw the buffer to the screen. With the code that I have above I am getting an error at the draw() function in the Ball class.
The error reads:
Debug Error!
R6010 -abort() has been called
I also get some information the command prompt:
Assertion failed: addon_initialized, file allegro-git\addons\primitives\primitives.c, line 79
I think I am getting an error because the draw function doesn't have anywhere to draw to because the display was created in the BallEngine Class, but how do I fix it?
Comment: Can you be more specific about your question? You say you have error in draw() function - what type of error? If compile-time, please give complete compiler message. If run-time - tell what is wrong. For now the code has also non-related problems (undeclared printf, private `BallEngine::running`).
Comment: Okay I added the error information, there is nothing wrong with printf, and I just forgot to edit the use of running.
Answer:
Assertion failed: addon_initialized, file allegro-git\addons\primitives\primitives.c, line 79

That's precisely the problem. You haven't initialized the primitives addon.
al_init_primitives_addon()
Also, you should use forward slashes as part of paths (e.g., <allegro5/allegro.h>) because it is cross platform.
Comment: Thank you! I don't know how I forgot to initialize it.. And now I know what that error message means!
Comment: As Matthew answerd the question already, maybe just a tip. If you are going to use lots of balls (primitives), you can prerender them into a surface (buffer) in the ballclass and on in the draw method, just blit the surcafe, on resize and so on, just rerender the buffer... this will improve the speet a lot on many not changing balls.

Allegro 5 drawing to buffer


How to motion deblur an image using OpenCV and Python?

Question: So I have been asked to motion deblur a frame captured from a video, I am kind of new to this deblur filters so need help. The video does not contain any noise, just a vertical motion blur. I am not allowed to use skimage, or any other library except cv2. It would be a great help even if what technique or function I have to use comes to know. Thanks!
Comment: https://docs.opencv.org/master/d1/dfd/tutorial_motion_deblur_filter.html
Comment: @nathancy thank you for the suggestion but it's not working for me
Answer: I think that for this kind of problem you have to use the recent deep learning techniques. They outperform the classical approaches. I recommend to look on github for a repository that would already provide a trained network that can deblur the same kind of blur that you have.
I never tried it, but this could be a nice candidate.
Answer: You can use the Motion Deblur Filter of opencv, if you specifically want to use opencv.
Following is the link to its documentation, which is fairly easy to understand:
http://amroamroamro.github.io/mexopencv/opencv/weiner_deconvolution_demo_gui.html
You can go for skimage as well. It has many function like deconvolution which can help in deblurring images.


Is  optional for a servlet in the Java Web application deployment descriptor?

Question: Is element <load-on-startup> optional for a <servlet> definition in the Java Web application deployment descriptor (WEB-INF/web.xml)?
Answer: Yes...
For example, http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd says
<xsd:element name="load-on-startup"
       type="j2ee:xsdIntegerType"
       minOccurs="0">
<xsd:annotation>
  <xsd:documentation>

    The load-on-startup element indicates that this
    servlet should be loaded (instantiated and have
    its init() called) on the startup of the web
    application. The optional contents of these
    element must be an integer indicating the order in
    which the servlet should be loaded. If the value
    is a negative integer, or the element is not
    present, the container is free to load the servlet
    whenever it chooses. If the value is a positive
    integer or 0, the container must load and
    initialize the servlet as the application is
    deployed. The container must guarantee that
    servlets marked with lower integers are loaded
    before servlets marked with higher integers. The
    container may choose the order of loading of
    servlets with the same load-on-start-up value.

  </xsd:documentation>
</xsd:annotation>
  </xsd:element>


Cannot assign  to an implicitly-typed local variable

Question: I want to to select a field from Data table dt_branches_global in such a way that, if radioButton_QP is Checked then the Data table will contain a string field otherwise the Data Table contain an int field. This is what I am doing. But I am getting error while initializing the variable Var.
var AllBranch_IDs = null;

if (radioButton_QP.Checked == true)
AllBranch_IDs = dt_branches_global.AsEnumerable().Select(x => x.Field<string>("BusinessSectorID")).ToArray();
else

AllBranch_IDs = dt_branches_global.AsEnumerable().Select(x => x.Field<int>("BusinessSectorID")).ToArray();

Comment: That is because the type if `var` needs to be inferred by the compiler at compile time, `null` alone cannot yield an inferred type. Either don't use `var` or include a cast on the null: `var AllBranch_IDs = (string[])null;` - either results in telling the compiler what the type is. Though it seems you are then going to run into the issue that one result is a `string[]` and the other appears to be an `int[]`?
Answer: The compiler is still strongly typed so it needs to figure out the type. It is impossible for the compiler to infer the type of you assign it to null. Then you later on try to assign it to two different types. An array of ints and an array of strings.
Try something like:
string[] AllBranch_IDs = null;

if (radioButton_QP.Checked == true)
AllBranch_IDs = dt_branches_global.AsEnumerable().Select(x => x.Field<string>("BusinessSectorID")).ToArray();
else

AllBranch_IDs = dt_branches_global.AsEnumerable().Select(x => x.Field<int>("BusinessSectorID").ToString()).ToArray();

Comment: +1 for guessing it's for display purposes and converting from int to string
Answer: As it stands, the type cannot be inferred from null - null could be any reference type.
i.e. The problem here
var AllBranch_IDs = null;

is that the compiler would need to scan to the following lines of code to deduce the type of AllBranch_IDs (which isn't possible in C# anyway), and wouldn't work due to the dynamic nature of the type - you assign it either IEnumerable<string> or IEnumerable<int>).
You could use IEnumerable<object> and then box the ints:
e.g.:
     IEnumerable<object> AllBranch_IDs = null;

     if (new Random().Next(10) > 5)
     {
        AllBranch_IDs = new [] {1,2,3,4}.Cast<object>().ToArray();
     }
     else
     {
        AllBranch_IDs = new [] {"hello", "world"}.ToArray();
     }

Declaring it as dynamic would also compile, viz dynamic AllBranch_IDs = null, although the consumer of the result would need to be aware that the type is dynamic.


Typing Probability

Question: The old printer in the computer room skips 1 character in 20 (chance of 1/20 of skipping a character)
From the beginning of a new line, how many characters can the old printer be expected to print correctly before the first character is skipped?
Assuming that half a line (40 characters) has been printed correctly, from this point how many correct characters can be expected before the first character is skipped?
So, my thinking is
$$E(w)=1/p$$
$$E(w)=20$$
It can be expected to print 20 characters before the first one is skipped.
As for the second part, using the result from the first part, if 40 were printed correctly then 0 more correct characters can be expected before the first character is correct?
Really unsure about this problem, especially the second part.
Comment: If 40 characters were printed correctly then 20 more correct characters can be expected before the first character is skipped, just like after 0 character or after 2014 correct characters or after whatever correct characters. This is the independence of the places where one skips a character.
Answer: We model the situation by assuming independence. Let $X$ be the number of characters  up to and including the first character skipped. Then $X$ has geometric distribution with parameter $p=\frac{1}{20}$, so $E(X)=20$.
However, the question asked for the expected number of correctly printed characters before the first skip. This is $X-1$, and therefore has mean $19$.
As to the second question, we use the memorylessness of the geometric distribution.
The answer is again $19$.
Answer: If $X$ denotes the number of characters correctly printed until the first is skipped, $C$ denotes the event that the first character is printed correctly and $S$ the (complementary) event that the first character is skipped then:$$\mathbb{E}X=\mathbb{E}\left(X\mid C\right)P\left(C\right)+\mathbb{E}\left(X\mid S\right)P\left(S\right)=\left(1+\mathbb{E}X\right)\frac{19}{20}+0.\frac{1}{20}$$
and consequently: $$\mathbb{E}X=19$$
Here $\mathbb{E}\left(X\mid C\right)=1+\mathbb{E}X$ because after typing a correct character the same process starts again keeping in mind that $1$ correct character has allready been printed.

Typing Probability


$L^1$ and a.s. convergence

Question: it seems almost impossible to infer results about almost sure convergence from results about $L^1$ convergence.
I have the following problem:

Let $X$ be a $L^2$ random variable ($\int_\Omega X^2 d\mathbb{P} < \infty$). Let further $Z_k = \vert X \vert \mathbb{1}_{\{X^2 \geq 2^k\}}$ (where $\mathbb{1}$ shall denote the indicator function). I want to show that $2^{k/2} Z_k \to 0$ almost surely.

What I was able to show is that
$\sum_{k=1}^\infty 2^k \mathbb{P}(X^2 \geq 2^k) \leq \mathbb{E}(X^2) < \infty$ and also that $2^{k/2} \Vert Z_k \Vert_1 \to 0$.
My initial plan was to conclude from the latter one, that somehow also $2^{k/2} Z_k \to 0$ almost surely, but as I mentioned initially, this doesn't work.
Now I came up with the idea to use the Borel-Cantelli lemma: Let $\varepsilon > 0$, then
$\sum_{k=1}^\infty \mathbb{P}(2^{k/2} Z_k > \varepsilon)=\sum_{k=1}^\infty \mathbb{P}(2^{k/2} \vert X \vert \mathbb{1}_{\{X^2 \geq 2^k\})}> \varepsilon) \leq \sum_{k=1}^\infty \mathbb{P}(\vert X \vert^2 \geq 2^k) \leq \sum_{k=1}^\infty 2^k \mathbb{P}(X^2 \geq 2^k) < \infty$,
where the first inequality comes from the fact, that $Z_k = 0$ for $\vert X \vert^2 < 2^k$. This would then proof the statement in view of the Borel-Cantelli lemma.
Either, this works and I was on the wrong path with the $L^1$ convergence. Or there is an error in my reasoning and I'm still deadlost. I appreciate any help.
Comment: Yes, there's usually no clear-cut path from $L^1$ convergence to as convergence. Your second reasoning seems to work, but I think it's needlessly complicated. Indeed, $(Z_k(\omega))_k$ is stationary to zero if $|X|(\omega) < \infty$ for any $\omega \in \Omega$. As $X$ is $L^2$, this condition occurs for almost every $\omega$.
Comment: We have pointwise that $Z_k = 0$ for $k$ large since $1_{\{X^2 \geq 2^k\}} = 0$ for $k$ large. Hence $Z_k \to 0$ a.s..
Answer: We have $\omega$-wise $$
2^{k/2} Z_k \not\to 0 \iff Z_k\not=0\quad \forall k\in\Bbb N \iff X^2 \ge 2^k \quad\forall k\in\Bbb N \iff X^2 = +\infty
$$
and so:
$$
\Bbb P(2^{k/2}Z_k \not\to 0) =  \Bbb P( X^2 = +\infty) = 0$$ hence $\Bbb P(2^{k/2}Z_k \to 0) = 1$ so a.s.

$L^1$ and a.s. convergence


Add item to a sql databse by pressing a button

Question: Im trying to add something to a list and at the same time add it to a database. This is done by pressing a button. This worked fine when I just add the item to the list, but when I added the database function, it stop working. The error starts at:
db.execSQL(createTable);
public class ItemDAO extends SQLiteOpenHelper {

        private static final String DATABASENAME = "ItemsDB";
        private static final Integer DATABASEVERSION = 1;

        private static final String TABLEITEM = "Table";
        private static final String ITEM = "name";
        private static final String ID = "id";

        private Context context;

        public ItemDAO(Context context) {
            super(context, DATABASENAME, null, DATABASEVERSION);
            this.context = context;
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            String createTable = "CREATE TABLE " + TABLEITEM + "("
                    + ID + " INTEGER PRIMARY KEY, "
                    + ITEM + " TEXT" + " )";

            db.execSQL(createTable);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        }

        public void addItemToDatabase(Item item){

            ContentValues fila = new ContentValues();

            fila.put(ID, item.getId());
            fila.put(ITEM, item.getName());

            SQLiteDatabase database = getWritableDatabase();

            database.insert(TABLEITEM, null, fila);

            database.close();
        }

        public List<Item> getItemsFromDatabases(){

            String selectQuery = "SELECT * FROM " + TABLEITEM;

            SQLiteDatabase database = getReadableDatabase();

            Cursor cursor = database.rawQuery(selectQuery, null);
            List<Item> itemList = new ArrayList<>();

            while(cursor.moveToNext()){

                Item item = getItem(cursor);
                itemList.add(item);
            }

            cursor.close();
            database.close();
            return itemList;
        }

        private Item getItem(Cursor cursor){
            Item item = new Item();

            Integer itemID = cursor.getInt(cursor.getColumnIndex(ID));
            item.setId(itemID);

            String itemName = cursor.getString(cursor.getColumnIndex(ITEM));
            item.setName(itemName);
            return item;
        }
    }

//Another class
public class ItemController {

    public void addItemToDB(Item item, Context context){
        ItemDAO itemDAO = new ItemDAO(context);
        itemDAO.addItemToDatabase(item);
    }

    public List<Item> getItemsFromDB(Context context){
        ItemDAO itemDAO = new ItemDAO(context);
        return itemDAO.getItemsFromDatabases();
    }

}

//Another class
public class FragmentMyList extends Fragment {
    private EditText editTxt;
    private Button btn;
    private ListView list;
    private ArrayAdapter<String> adapter;
    private ArrayList<String> arrayList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View vistaADevolver = inflater.inflate(R.layout.fragment_my_list, container, false);

        editTxt = (EditText)vistaADevolver.findViewById(R.id.editText);
        btn = (Button) vistaADevolver.findViewById(R.id.button);
        list = (ListView) vistaADevolver.findViewById(R.id.recyclerView);
        arrayList = new ArrayList<>();

        // Adapter: You need three parameters 'the context, id of the layout (it will be where the data is shown),
        // and the array that contains the data
        adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, arrayList);

        // Here, you set the data in your ListView
        list.setAdapter(adapter);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ItemController itemController = new ItemController();

                String itemName = editTxt.getText().toString();
                Item item = new Item();
                item.setName(itemName);
                item.setId(0);
                itemController.addItemToDB(item, getActivity());

                // this line adds the data of your EditText and puts in your array
                arrayList.add(itemName);
                // next thing you have to do is check if your adapter has changed
                adapter.notifyDataSetChanged();
            }
        });
        return vistaADevolver;
    }
}

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.segunfamisa.sample.bottomnav, PID: 2792
                  android.database.sqlite.SQLiteException: near "Table": syntax error (code 1): , while compiling: CREATE TABLE Table(id INTEGER PRIMARY KEY, name TEXT )
                      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                      at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                      at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
                      at android.database.sqlite.SQLiteStatement.(SQLiteStatement.java:31)
                      at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1677)
                      at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1608)
                      at com.segunfamisa.sample.bottomnav.ItemDAO.onCreate(ItemDAO.java:45)
                      at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
                      at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
                      at com.segunfamisa.sample.bottomnav.ItemDAO.addItemToDatabase(ItemDAO.java:63)
                      at com.segunfamisa.sample.bottomnav.ItemController.addItemToDB(ItemController.java:15)
                      at com.segunfamisa.sample.bottomnav.FragmentMyList$1.onClick(FragmentMyList.java:52)
                      at android.view.View.performClick(View.java:5637)
                      at android.view.View$PerformClick.run(View.java:22429)
                      at android.os.Handler.handleCallback(Handler.java:751)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Comment: I think it would help if you add error message...
Comment: There is the error
Comment: Do you already have a table called `Table` that you haven't cleared?
Comment: The only table I have is TABLEITEM
Comment: `Table` is a reserved word for most DBMS (ie, you can't use it). You will enclose the name within backticks to make this work...
Answer: Table is a reserved keyword in SQLLite, you cannot use it as a table name.
http://www.sqlite.org/lang_keywords.html
Also watch out with the column name TEXT. This is not reserved in SQLLite, but in MySQL for example it is. Using this column name prevents you from making a switch to another database vendor in the future.
Comment: @MatiasNagore Nope! Happy to help!
Answer: Try some other name for table as it is a keyword and use \'table name here\' or \"table name here\"
Answer: I would guess you have to put name of table which is Table into some kind of escape char (google says its " - double quote)
in ItemDAO:
 private static final String TABLEITEM = "\"Table\"";

Table is reserved keyword in SQLLite so usually it is bad (practice) idea to use reserved keywords as table and columns names. However if you have to you have to escape those names: reference
Comment: I'm not sure if this is working, I have not tested it, but it is possible. But please don't do this, using Table as a table name is a BAD practice.


Redirect all urls except one in .htaccess

Question: I am trying to redirect all URLs on my site (let's call it www.site1.com) except one in my .htaccess file. I currently have the following in my .htaccess file:
<code>  RewriteEngine on
  RewriteCond %{REQUEST_URI} !^/my/page$ [NC]
  RewriteRule (.*) https://www.site2.com [R=302,L]
</code>
With the above, all requests to www.site1.com are redirected to www.site2.com, including the one that I do not want to redirect.
After some experimentation, I have found that the following works to redirect only a specific page:
<code>  RewriteEngine on
  RewriteCond %{REQUEST_URI} ^/my/page$ [NC]
  RewriteRule (.*) https://www.site2.com [R=302,L]
</code>
I'm not sure why the ! operator isn't working as I expect. Perhaps there is an error in my regex?
Some additional bit of information. This is a Drupal site running on a dedicated cPanel host. But I have been sure to put this new redirect rewrite rule before all the other Drupal-specific rewrite rules.
Any help would be greatly appreciated.
Comment: Isn't it better to first create a condition for that single page and because it doen't match for the other pages, have another one for the rest?
Comment: Your first version is correct, it works (assuming the requested URL actually _is_ `/my/page`). Question is why it does not work _in your specific case_ ... First guess: you are looking at cached results from earlier attempts?
Comment: @onlineThomas - I am certainly open to taking a different approach. If you could present your idea in more detail as an answer I would be happy to try it.
Comment: @arkascha - I have been sure to clear the cache and I have triple checked that the urls are correct. I am seeing www.site1.com/my/page getting redirected, along with all others.
Comment: Then I suggest you enable rewrite logging inside your http server to be able to observe the steps taken inside your rewriting engine. The documentation explains how to do that.
Comment: That is an excellent suggestion. However in the interest of time, I chose to just redirect certain pages, instead of all pages except one.
Answer: <code>RewriteCond %{REQUEST_URI} !/(index.php) [NC]

RewriteRule ^(.*)$ index.php [NC,QSA,L,END]
</code>
You need to make sure you exclude the page you redirect to from you list of possible url that get redirected(to avoid the loop) and then you can add more before the RewriteRule.
RewriteCond %{REQUEST_URI} !/(index.php) [NC]
RewriteCond %{REQUEST_URI} !/(index_new.php) [NC]
RewriteRule ^(.*)$ index.php [NC,QSA,L,END]
Comment: This is what the OP tries to do and it does not work according to him. What point is there in telling him he has to do what he indeed tries to do? Especially using an example which is inconsistent in itself and does not match the details in the answer.
Comment: He does not negate  the destination site2 and then he ends up redirecting site2 to site2 and he does not want that. It is a common mistake in .htaccess redirecting you always have to negate the destination to avoid going in a loop.
Comment: Maybe you should read the question again. All of it.


How does an Access Point handle broadcast packets from the wired side?

Question: I have an Cisco AP 1242AG autonomous AP connected to L2 switches.
Let's say I have 100 wired devices each sending 2 broadcast UDP packets per second.
Obviously these packets will reach the Access Point switch port, but will the AP actually send these packets (200 pps) into the air?
Thanks
Comment: Good question. I'm assuming that since a WAP is a layer 2 device that it will behave the same as any other layer 2 device and will handle unicast, broadcast and multicast traffic just as any other layer 2 device would.
Answer: The access point has to send some broadcast packets into the air, otherwise the network wouldn't work. As long as the wireless interface isn't congested, there is little reason not to send them all. In case of congestion it has to decide which packets goes through and which are dropped. At that point it may handle broadcast packets differently from other packets.
A switch has to transmit a broadcast packet on all ports except from the one it was received on. An access point should not have to send the packet once to every device associated with that access point. Instead it should be sufficient to send it once and have all devices simultaneously receive the packet being broadcast just once.
Comment: The issue with 802.11 is how this happens when the AP<->Client connections are separately encrypted which should (now) be the normal case. The "same" signal can't be broadcast, each client has to get a version encrypted just for it. So broadcasts become a set of unicasts.
Comment: I don't know exactly how 802.11 implements it. But one way it could have been implemented would be to use one key for broadcast and a set of different keys for unicast.
Comment: What if there is no associations to the AP? will the broadcast packets be sent then? I'm getting high duty-cycle values for the 2.4 GHz channel when a client is associated to the AP. If no clients are associated, the duty-cycle drops. It looks like the AP is smart enough to not send any data (except for management frames) when there is nothing associated to it.


What are 'modal rhythm' and 'mensural rhythm'?

Question: The following is from Harvard Dictionary of Music 2nd Edit.
From the definition of 'Discant' (bold added):

[...] The ideal of contrary motion was mentioned in the 13th-century "Tractatus de Discantu" (in J.-A.-L. de la Fage, Essais, i, 358; CS i, 311) but became an essential characteristic of discant theory only at the end of the 13th century, when modal rhythm was replaced by
mensural rhythm.

Full page of context:

I've never heard these two terms: mensural and modal rhythm. Google gave nothing, neither did Britannica.
What do these two terms mean?
Comment: I unfortunately don't have the time to answer right now, but the phrases "rhythmic modes" and "mensural notation" may help guide you.
Comment: That seems like it would supply the basis for a good answer. In case you aren't already familiar, it's permitted to answer your own question.
Comment: Orhan Torun: the link in your previous comment does not work for me.  I join @Aaron in encouraging you to write an answer describing what you've found.
Comment: @Richard Thank you, rhytmic modes gave results, I edited the question thank you for the suggestion.
Comment: Did you read the referenced section "[Modes, rhythmic]"?
Comment: Near the bottom of the first column: "but with the emphasis on strict measurement in modal rhythm [see **Modes, rhythmic**]."  Did you look up "Modes, rhythmic" in the same dictionary?
Comment: @Aaron and phoog; yes there's a brief definition. Let me make you a copy paste: Modal rhytm: 'A rhythm based on the rhythmic  modes.' But I really don't understand what this means (before opening the question)
Comment: Well, for certain the book's description isn't very helpful!
Comment: @Aaron also from the same book: Modal rhythm: Not until shortly before
1200 did isometric rhythm become definitely
established through the modal rhythm [see
Modes, rhythmic] of the organa, clausulae, etc.,
of the school of Notre Dame. Credit for this important innovation must be ascribed to Leoninus. (and it goes on; it actually more or less answers the question). It's too long so I uploaded it https://ibb.co/m4yt338
Comment: @Aaron I'll, as soon as I feel confident to provide one; I'm still working on that topic.
Answer: Modal rhythm used note linkage to indicate length. Various patterns of notes indicated how to play the following notes.
Mensural rhythm used note forms (minim, breve, semibreve, etc.); using like 2 semi-breves vs a breve to indicate binary rhythm and 3 semi-breves vs a breve to indicate ternary rhythm schemes.
These are well-described in Wikis and various music history books.


Oracle SQL: Conditionally update a table based on comparison with a SQL statement

Question: I have a table (TABLE1) which has 4 columns:
UID | PID | VALUE1 | VALUE2
I have another SQL statement (STMT) which returns 3 columns from some other tables:
UID | PID | VALUE1
Now here are the condition of how I want to update TABLE1:
First, compare UID and PID pair from STMT with those in TABLE1,

for all new UID and PID pair not in TABLE1, insert new row from STMT into TABLE1, set TABLE1.VALUE2 = 0 (I've already done this one)
for existing UID and PID pair in both STMT and TABLE1, do:
a. if TABLE1.VALUE2 > 0, update TABLE1.VALUE1 = STMT.VALUE1
b. if TABLE1.VALUE2 = 0 and if TABLE1.VALUE1 != STMT.VALUE1, update TABLE1.VALUE1 = STMT.VALUE1, otherwise do nothing.

I'm having trouble coming up with a solution for condition 2. Any help is appreciated!
Comment: The end result after step 2 is that all cases of table1.value1 = stmt.value 1.  Do you specifically need to avoid updating rows to the same values they already are so that triggers don't fire?
Comment: @evilotto it's fine, the ultimate purpose is to make TABLE1 always up-to-date.
Answer: UPDATE (
    SELECT table1.UID
           ,table1.PID
           ,table1.value1 AS table1_value1
           ,table1.value2 AS table1_value2
           ,stmt.value1 AS stmt_value1
    FROM table1
    INNER JOIN (SELECT ? AS UID
                       ,? AS PID
                       ,? AS value1
                FROM whatever) stmt
        ON stmt.UID = table1.UID
        AND stmt.PID = table1.PID
) x
SET x.table1_VALUE1 = CASE WHEN (x.table1_VALUE2 > 0) OR
                              (x.table1_VALUE2 = 0 AND x.table1_VALUE1 <> x.stmt_VALUE1)
                              THEN x.stmt_VALUE1
                         ELSE x.table1_VALUE1
                    END

Comment: Thanks for your answer cade, however i have a question that might be stupid: how do you cast sql statement into STMT so you can use it as STMT.value1 in your update statement?
Comment: Thanks again for your help. I'm now getting "ORA-01779: cannot modify a column which maps to a non key-preserved table" error. Any idea why it happens?
Comment: @AlanHan Just Oracle being difficult.  I could be as simple as just adding table1.UID and table1.PID to the x subquery to get the keys.  Otherwise refactor the query to remove the inner subquery by combining it or use a MERGE INTO technique instead.
Answer:  You can use below query
MERGE INTO TABLE1 T
USING STMT S
ON (T.UID  = S.UID AND T.PID = S.PID)
WHEN MATCHED THEN
UPDATE
SET
T.VALUE1 = CASE WHEN T.VALUE2 > 0 OR (T.VALUE2 = 0 AND T.VALUE1 <> S.VALUE1) THEN S.VALUE1 END
WHEN NOT MATCHED THEN
INSERT INTO T (COLUMNS) (SELECT COLUMNS FROM S);


Change in proportion in two populations over time

Question: I have a data set composed of two groups which had two different treatments.  They are treated over 8 weeks.  The endpoint is binary - either they respond or not during each week.  Thus, for any given week, I can use a chi-square to compare the proportions of each group that responds.  However, what I really need to know is the trend:  does one group improve, in terms of proportion of responses, over the 8 weeks more than the other?
Comment: Did you try logistic regression?  There is a lot of information on that at this site, search for "logistic regression".
Answer:
However, what I really need to know is the trend: does one group
  improve, in terms of proportion of responses, over the 8 weeks more
  than the other?

So you want to know how risk ratio changes over time (alternatively you can use odds ratio). Risk ratio is defined as $RR = p_1/p_2$, where $p_1$ is proportion of participants that responded to treatment in the first group (number of those who responded divided by the number of treated patients) and $p_2$ is proportion of participants that responded to treatment in the second group.
What you want to observe is risk ratio at time $t$. If I understand you correctly, you have two groups with sample sizes $n_1$ and $n_2$. At each time $t$ you observe some number of patients that responded to the treatment up to this time ($x_1^{(t)}$ and $x_2^{(t)}$), so the cumulative proportions of patients who responded to treatment are $p_1^{(t)} = x_1^{(t)}/n_1$ and $p_2^{(t)} = x_2^{(t)}/n_2$. Risk ratio at time $t$ is $RR^{(t)} = p_1^{(t)} / p_2^{(t)}$.
After having defined new variable for risk ratio over time, you can use different tools for assessing the trend. You can plot it, use regression, but also time-series analysis tools, changepoint analysis etc. depending on your needs. You can even use some multivariate model so to try to predict what influences the changes in the risk ratio over time.


Problema em Configurar API Google Maps

Question: Galera não consigo configurar a API do Google Maps, já coloquei minhas keys e tudo mais mas não vai.
<!DOCTYPE html>

      <title>Simple Map</title>
      <meta name="viewport" content="initial-scale=1.0">
      <meta charset="utf-8">

Comment: Matheus, algumas perguntas (podem ser bem ingênuas).

1. Você trocou a palavra `KEY` pela sua chave dentro do arquivo de importação?
2. Está mostrando algum erro no console? (ele pode ser um grande aliado para resolver)
3. Você liberou o acesso para qualquer requisição(referente as plataformas) dentro da interface da GCP?
Comment: @JoãoPedroSchmitz foi eu que troquei a chave pela palavra.
Comment: Ah, ok. Não visualizei o conteúdo da edição. Obrigado por avisar.
Comment: E qual é o erro?
Answer: Sugiro que verifique sua conta de faturamento para obter uma key válida.
Ao utilizar key's de terceiros, pode acabar não funcionando.
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Problema em Configurar API Google Maps


how to minimize the code using python django

Question: i have a nested if condition to check the conditions.how can i minimize the code?what should i do shorten the code?
I have created a funtion and inside thet function i am checking the id of meter which the user has given and updating the table in the database.
def updatereport(meterdetails_id, indicator='inr'):
if meterdetails_id == 1:

    happycount1 = Report.objects.filter(date = timezone.datetime.today()).values("happycount")

    if len(happycount1)<=0:
        Report.objects.create(date = timezone.datetime.today(),happycount=0)
    else:

        if indicator == 'inr':

            Report.objects.filter(date=timezone.datetime.today()).update(happycount=happycount1.get()["happycount"]+1)
        else:

            Report.objects.filter(date=timezone.datetime.today()).update(happycount=happycount1.get()["happycount"] - 1)
elif meterdetails_id == 3:
    disappointedcount1 = Report.objects.filter(date = timezone.datetime.today()).values("disappointedcount")
    if len(disappointedcount1) <= 0:
        Report.objects.create(date=timezone.datetime.today(), disappointedcount=0)

    else:

        if indicator == 'inr':
            Report.objects.filter(date = timezone.datetime.today()).update(disappointedcount = disappointedcount1.get()["disappointedcount"] + 1)

        else:

            Report.objects.filter(date = timezone.datetime.today()).update(disappointedcount = disappointedcount1.get()["disappointedcount"]-1)
elif meterdetails_id == 2:
    depressedcount1 = Report.objects.filter(date = timezone.datetime.today()).values("depressedcount")
    if len(depressedcount1) <= 0:
        Report.objects.create(date = timezone.datetime.today(), depressedcount=0)
    else:
        if indicator=='inr':
            Report.objects.filter(date = timezone.datetime.today()).update(depressedcount = depressedcount1.get()["depressedcount"] + 1)
        else:

            Report.objects.filter(date = timezone.datetime.today()).update(depressedcount = depressedcount1.get()["depressedcount"] - 1)

elif meterdetails_id == 5:
    okcount1 = Report.objects.filter(date = timezone.datetime.today()).values("okcount")
    if len(okcount1) <= 0:
        Report.objects.create(date = timezone.datetime.today(), okcount=0)
    else:
        if indicator =='inr':
            Report.objects.filter(date = timezone.datetime.today()).update(okcount = okcount1.get()["okcount"] + 1)
        else:

            Report.objects.filter(date = timezone.datetime.today()).update(okcount = okcount1.get()["okcount"] - 1)

    elif meterdetails_id == 6:
    sadcount1 = Report.objects.filter(date = timezone.datetime.today()).values("sadcount")
    if len(sadcount1) <= 0:
        Report.objects.create(date = timezone.datetime.today(), sadcount=0)
    else:
        if indicator =='inr':
            Report.objects.filter(date = timezone.datetime.today()).update(sadcount = sadcount1.get()["sadcount"] + 1)
        else:

            Report.objects.filter(date = timezone.datetime.today()).update(sadcount = sadcount1.get()["sadcount"] -1)
      elif meterdetails_id == 7:
    angrycount1 = Report.objects.filter(date = timezone.datetime.today()).values("angrycount")
    if len(angrycount1) <= 0:
        Report.objects.create(date = timezone.datetime.today(), angrycount = 0)
    else:
        if indicator =='inr':
            Report.objects.filter(date = timezone.datetime.today()).update(angrycount = angrycount1.get()["angrycount"] + 1)
        else:
            # print ('here')
            Report.objects.filter(date = timezone.datetime.today()).update(angrycount = angrycount1.get()["angrycount"] - 1)

models.py
 class Report(models.Model):
happycount=models.IntegerField(default=0,null=True,blank=True)

disappointedcount=models.IntegerField(default=0,null=True,blank=True)
depressedcount=models.IntegerField(default=0,null=True,blank=True)
okcount=models.IntegerField(default=0,null=True,blank=True)
sadcount=models.IntegerField(default=0,null=True,blank=True)
angrycount=models.IntegerField(default=0,null=True,blank=True)
date=models.DateField('date',default=timezone.datetime.today(),null=True,blank=True)

def __unicode__(self):
    return '%s' % self.date

ordering = ["date"]
verbose_name = "report"
verbose_name_plural = "reports"

Answer: def updatereport(meterdetails_id, indicator='inr'):
    if meterdetails_id == 1:
        proper_function_name('happycount', indicator)
    elif meterdetails_id == 3:
        proper_function_name('disappointedcount', indicator)
    elif meterdetails_id == 2:
        proper_function_name('depressedcount', indicator)
    elif meterdetails_id == 5:
        proper_function_name('okcount', indicator)
    elif meterdetails_id == 6:
        proper_function_name('sadcount', indicator)
    elif meterdetails_id == 7:
        proper_function_name('angrycount', indicator)

def proper_function_name(count_name, indicator):
    count = Report.objects.filter(date=timezone.datetime.today()).values(count_name)
    if len(count) <= 0:
        Report.objects.create(date=timezone.datetime.today(), **{count_name: 0})
    else:
        if indicator =='inr':
            Report.objects.filter(date=timezone.datetime.today()).update(**{count_name: count.get()[count_name] + 1})
        else:
            Report.objects.filter(date=timezone.datetime.today()).update(**{count_name: count.get()[count_name] - 1})

I called the function proper_function_name but you should come up with something better :P Also consider using Enum instead of hardcoded meterdetails_ids, like:
class MeterDetail(Enum):
    happycount=1
    disappointedcount=3
    ...

So later in the code you would have
if meterdetails_id == MeterDetail.happycount:
   ...

Instead of:
if meterdetails_id == 1:
    ...

Comment: Also I am not sure what is your intention here:
Report.objects.filter(date = timezone.datetime.today()).values("okcount")?
Comment: i am getting the count of ok in database table like
 id | happycount | disappointedcount | depressedcount | okcount | angrycount |    date    | sadcount
----+------------+-------------------+----------------+---------+------------+------------+---------
 15 |          6 |                 1 |              1 |       1 |          1 | 2019-04-05 |        1
Comment: i am new to python ..can you tell me why you used  ** inside the function Report.objects.create(date=timezone.datetime.today(), **{count_name: 0}) but not here def proper_function_name(count_name, indicator): ?@marke
Comment: In the first one the, whatever string is in the variable count_name will be passed as a name of a keyword argument and with whatever comes after ":" as a value of this keyword argument. In the second function you can use positional argument, there is no need for keyword argument. The **{...} notation is called keyword unpacking, google it out :P


Machine learning method to determine continuous values from discrete and continuous parameters

Question: I watched online courses about multivariable linear regression which addresses the problem of determining values from numeric inputs. Like, predict prices for houses based on age, size, number of floors...
I also learned about things like logistic regression which concerns classification problems based on numerical inputs. Like, predict if an email is spam or not spam.
But I'm having trouble to find informations about predicting continuous values (like a price) based on a mix of discrete and continuous parameters.
For example, if I have several models of laptops classified with these categories:
[discrete] color: gray, blue, black...
[discrete] backlit_keyboard: yes, no
[discrete] material: plastic, aluminium
[continuous] weight: (numeric)
[discrete] brand: apple, sony, lenovo...

Now, assuming that the price will be a function of all these variables, and that I have a large training set of actual prices for each described object, I want to determine this function so that I'll be able to tell an estimated price for an object which has no previous example in the training set.
Which machine learning methods could/should be used to fit such a purpose?
Answer: One standard thing to do is to use one-hot encoding, and then run any regression algorithm you'd like (e.g. a variant of linear regression, or maybe kernel ridge regression). That is, the first dimension can be color_is_gray (which would be 1 if the color is gray, and 0 if not); the second color_is_blue, and so on. Then concatenate features for the other attributes.
If you have some notion of distance between the discrete attributes, you can instead perform multidimensional scaling and use the features it obtains.
Answer: Adding to what was already said:
A simple approach to represent categorical features in a model (whatever model you use) is one-hot-encoding. This translates the categories to indicators and the representation is again numeric.
A rather novel idea is to apply feature embeddings. The idea is to go beyond simple indicator vectors of zeros and ones. Rather, the aim is to represent relations between the levels of the categorical feature.
In this blog post Exploring Embeddings for Categorical Variables with Keras the 7 days of the week (+ a level for "missing") are embedded in a lower dimensional space with the result of improved generalization. The embedding uses the target (bike count data) and the position of e.g. Saturday is closer to Sunday (and close to Tuesday) than to Wednesday. It is debatable whether this is true but one-hot-encoding would not be able to achieve this.


Utilização de Append - Python

Question: Qual a necessidade de usar a função "Append" no meu código? Dizem que ele pode ser utilizado para adicionar outro elemento na minha lista Python, porém não seria mais simples eu adicionar esse outro elemento de forma tradicional? O Append só serve para essa "adição"?
Comment: Qual seria a "forma tradicional"?
Comment: Apenas escrevendo o elemento junto com os outros que fazem parte.
Answer: Adicionar um elemento em uma lista de forma dinâmica e existem diversas razões para isso ser possível:

Não conhecer previamente o valor a ser adicionado;
Garantir que sua lista tenha espaço para o novo valor;

E possivelmente outros motivos.

Não conhecer previamente o valor a ser adicionado

Digamos que eu precise solicitar ao meu usuário uma lista com 5 valores inteiros. Como eu poderei criar essa lista se eu não sei quais os valores que o usuário digitará? Assim, eu preciso criar a minha lista e inserir os valores dinamicamente:
numeros = []

for _ in range(5):
    numeros.append(int(input('Digite um número: '))

print(numeros)

Com isso, não importa quais os valores que o usuário digitar, o programa irá adicionar na lista da mesma forma.
>>> Digite um número: 1
>>> Digite um número: 2
>>> Digite um número: 3
>>> Digite um número: 4
>>> Digite um número: 5
[1, 2, 3, 4, 5]

Isso significa que sempre utilizarei o append? Não. Muitos problemas podem ser resolvidos de outras maneiras. Cabe a você, como desenvolvedor, avaliar qual é a ideal. Se você quer uma lista com 5 valores lidos do usuário, poderia fazer:
numeros = [int(input('Digite um número: ')) for _ in range(5)]

O resultado é exatamente o mesmo que o anterior, sem utilizar o append. Se eu quero apenas os valores pares, como citado na outra resposta, você poderia fazer:
pares = [numero for numero in range(20) if numero % 2 == 0]

Mesmo resultado sem utilizar o append.
Inclusive, muitas vezes é mais viável você fazer sem o append, pois ele gasta memória a toa.

Garantir que sua lista tenha espaço para o novo valor

Se a minha lista possui 5 elementos, ela ocupará em memória o equivalente a 5 vezes a memória que é demandada por aquele tipo de objeto. Se eu necessito adicionar um sexto elemento na lista, o que me garante que existe memória disponível? O método append irá garantir isso para você pois ele realizará o que chamamos de alocação dinâmica da memória. Sempre que for inserir um novo elemento ele ficará responsável por alocar memória para que seja possível guardar o novo valor.
Essa alocação dinâmica do append, inclusive, busca funcionar de uma forma otimizada. Como fazer a alocação de memória para cada novo valor pode ser custoso para aplicação, ao invés de alocar apenas um novo espaço serão alocados vários, para caso seja adicionados mais valores já exista memória disponível. Isso é interessante se a sua lista sofre muitas modificações, mas é ruim em casos contrários, pois pode ser alocado muito mais memória do que realmente era necessário.
Eu comentei sobre esse comportamento em:

Por que essas duas formas de inicializar a mesma lista em Python geram estruturas de tamanhos diferentes?

Por esse motivo é comum você ler que é melhor você utilizar a list-comprehension (soluções acima sem o append) do que as soluções que usam o append. Porém nem sempre isso é válido; há problemas que é melhor utilizar o append - senão ele nem existiria.
Answer: É recomendado usar o append quando você utiliza um laço para gravar esses dados em uma lista, exemplo:
Neste exemplo quero apenas os números pares de 0 até 20
lista_par = []
for i in range(20):
   if i%2 == 0:
      lista_par.append(i)
print(lista_par)

Saida = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Comment: A resposta não está errada, mas me senti obrigado a votar contra por achar que falta embasamento. Se você editar a resposta e complementar com os argumentos que defendem a sua resposta, terei o prazer de reconsiderar o voto. Nos comentários você até cita alguns motivos, então isso deveria estar na resposta. Seria interessante explicar também porque sobrescrever o objeto é pior que alterá-lo. Sempre isso é verdade?
Comment: Quem recomenda? Por que é recomendado?
Comment: Quando você utiliza o sinal de atribuição você sobrescreve o objeto, quando você utiliza o  *append* você adiciona o elemento no final da lista, o controle de índice é realizada automaticamente, já quando você utiliza apenas o sinal de atribuição simples, o igual "=" , você que deverá realizar este controle, adicionando um indicie e incrementando, no exemplo a cima caso utilize o "=" ficaria assim "lista_par[i] = i" dentro do bloco for.
Comment: Eu sou novo aqui no stack overflow com um dos que ajuda a solucionar dúvidas, ainda estou pegando a manha de explicar as coisas, principalmente programação. Obrigado pelo feedback, vou melhorar e da próxima vez  espero fazer corretamente!
Comment: Seja bem-vindo, então :D Qualquer coisa, sempre estamos online no [chat](https://chat.stackexchange.com/rooms/11910/estouro-de-pilha) da comunidade caso queira tirar alguma dúvida.
Comment: Muito obrigado !

Utilização de Append - Python


Can I host webhook for my lex bot on my own server instead of AWS Lambda?

Question: Seems like AWS Lex supports using AWS Lambda for hosting my application logic. Can I provide my own custom webhook instead of using AWS Lambda?
I would like to host my own server and use it to handle the webhook requests.
Answer: This is not currently possible, Lex can only integrate with Lambda functions to run some back-end logic.
If you have to run code off your own server, you could make a request to the server from the Lambda function to fetch the response and then return it back to Lex. However, if you want to do this to minimize Lambda associated costs, this wouldn't help.


Como gerar UUID's/GUID's com Javascript?

Question: Preciso criar UUID's/GUID's com Javascript, porém não achei nenhuma função na documentação. Conhecem/recomendam alguma biblioteca existente, que gere UUID's válidos e satisfatoriamente aleatórios?
Answer: Versões baseadas em crypto.getRandomValues() podem garantir uma menor taxa de colisão do que Math.random().

function uuid() {

    // Retorna um número randômico entre 0 e 15.
    function randomDigit() {

        // Se o browser tiver suporte às bibliotecas de criptografia, utilize-as;
        if (crypto && crypto.getRandomValues) {

            // Cria um array contendo 1 byte:
            var rands = new Uint8Array(1);

            // Popula o array com valores randômicos
            crypto.getRandomValues(rands);

            // Retorna o módulo 16 do único valor presente (%16) em formato hexadecimal
            return (rands[0] % 16).toString(16);
        } else {
        // Caso não, utilize random(), que pode ocasionar em colisões (mesmos valores
        // gerados mais frequentemente):
            return ((Math.random() * 16) | 0).toString(16);
        }
    }

    // A função pode utilizar a biblioteca de criptografia padrão, ou
    // msCrypto se utilizando um browser da Microsoft anterior à integração.
    var crypto = window.crypto || window.msCrypto;

    // para cada caracter [x] na string abaixo um valor hexadecimal é gerado via
    // replace:
    return 'xxxxxxxx-xxxx-4xxx-8xxx-xxxxxxxxxxxx'.replace(/x/g, randomDigit);
}

console.log(uuid());

Você pode perceber que a string de retorno possui 2 valores fixos, 4 para o 3o bloco e 8 para o 4o. Isso é parte da especificação para GUIDs randômicas versão 4.
Fonte.
Comment: Tem como dar uma explicada sobre o funcionamento do algoritmo?
Comment: Como funciona direito o `crypto.getRandomValues`? É compatível com vários browsers?
Comment: @jbueno Explicação em comentários, obrigado pela sugestão.
Comment: @ArturoTemplário A maioria dos browsers modernos suporta a biblioteca `crypto`.
Comment: Ótimo +1 @OnoSendai
Comment: @OnoSendai acho que melhor que isso só fazendo uma chamada AJAX e gerando server side kkkk muito obrigado, acho que serve perfeitamente pros meus propósitos
Answer: Realizei algumas pesquisas e encontrei algumas funções que podem lhe ajudar.
Para gerar o UUID você pode usar a função abaixo:
function create_UUID(){
    var dt = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (dt + Math.random()*16)%16 | 0;
        dt = Math.floor(dt/16);
        return (c=='x' ? r :(r&0x3|0x8)).toString(16);
    });
    return uuid;
}
console.log(create_UUID());

Para gerar o GUID pode ser feito conforme abaixo:
function S4() {
    return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}

function create_GUID(){
    return (S4() + S4() + "-" + S4() + "-4" + S4().substr(0,3) + "-" + S4() + "-" + S4() + S4() + S4()).toLowerCase();
}

console.log(create_GUID());

Referências:
http://www.w3resource.com/javascript-exercises/javascript-math-exercise-23.php
http://guid.us/GUID/JavaScript
Comment: E como isso funciona?
Comment: As funções create_UUID() e create_GUID() retornam uma string. Então é só você chamar a função conforme fiz em console.log(create_UUID()) que ela já irá gerar o código aleatório.
Comment: Quero saber como funciona o algoritmo que cria o UUID.
Comment: Nos links que passei nas referências tem mais detalhes sobre o algoritmo.
Comment: Mas eu não falo inglês.


$\varepsilon$ in $\int_{-\varepsilon}^\infty e^{-x}\delta(\sin{x})\;dx$

Question: Why is $\varepsilon$ in the following integral and not just $0$ instead? My teacher said he didn't have time to explain it; however, I am curious about that.
$$\int_{-\varepsilon}^\infty e^{-x}\delta(\sin{x})\;dx$$
where
$$0 \lt \varepsilon \ll 1$$
Answer: It depends on how the delta function $\delta(\cdot)$ is defined.  To be sure to get "all" of the contribution at $x=0$, the support of the integral extends a little to the left of zero.
The integral will evaluate to $\sum_{k=0}^\infty e^{-\pi k x} = \frac{1}{1-e^{-\pi}}$ because $\sin x$ has zeros at $\pi k x$.