What is an unambiguous way to represent two different valid interpretations of what "total" might mean in this context

Question: Sorry for the unspecific title, but my lack of a way to accurately describe the problem is part an parcel of the problem itself.  I'll try and demonstrate clearly through example, as I'm not confident in my describe the problem clearly.
In a very simplified example, let's say I have a company which ships some products to 4 countries.

Representing how those products are distributed countrywise, I might produce a table like so:

However it seems there are 2 perfectly valid ways to describe a "total".  I could say 14, in that there are 14 products unique products sold per country.
Or I could say 8, in that there are 8 different products sold worldwide.
My problem is that both are useful, valid numbers for different purposes.  While perhaps the second is the more obvious, intuitive answer for what "total" would mean here, it's not hard to imagine why I might want to know the number 14: Let's say I must register a product with a made up "European fruit registry".  To know how many of those registrations I'd want to make, the answer would be 14.
What is a clear, unambiguous way to present what the numbers 14 and 8 are to this data?
My actual data involves 1000s of rows and 10s of columns
Answer: A good way to discuss this would be to talk about a frequency table with interesting marginal frequencies.  Your overall table looks like this:
          Product
Country    Apple Banana Melon Orange Peach Pear Plum Pomegranate
  Austria      1      1     0      1     0    1    1           0
  Belgium      1      0     0      0     0    1    0           1
  Bulgaria     1      0     0      0     0    1    0           0
  Croatia      1      0     1      1     1    0    0           0

A potentially useful way to discuss your 14 is that there are 14 unique Product-Country combinations.  You can also discuss the frequencies of the margins, which is to say how frequent are the categories in each of the two dimensions without concern for the other dimension.  Along the Product dimension, the marginal frequencies are:
Product
      Apple      Banana       Melon      Orange       Peach        Pear        Plum Pomegranate
          4           1           1           2           1           3           1           1

For this, I would say there are 8 unique Products where the most frequently appearing products are apples, pears, and oranges.  You already have this for the Country dimension:
Country
 Austria  Belgium Bulgaria  Croatia
       5        3        2        4

There are 4 unique Countries, and Austria has the most diverse fruit, followed by Croatia.
To make it clear, I would present the results alongside the appropriate tables.
Comment: In my source data a frequency table like the above would be a little impenetrable; the dataset is a little too large to comprehend with all the raw data presented (akin to 1000s of fruit in 10s of countries). I've pulled out some summaries to give an "overall feel" of the most important aspects of the data. I've also included a table much the above with a list of all countries sold for each product (to save width from 0s), just in case anyone wants to inspect specific products in more detail; so it's good to know a stranger on this forum had the same intuition as me in that regard.
Comment: Thanks for the pointer about marginal frequencies, and the phrasing of unique product country combinations, that's given me some interesting reading and a good direction to go in.
Comment: With the info on the data scale and if countries are really countries, you might consider plotting the marginal frequencies on a choropleth map with color intensity as frequency.  If they aren't countries, you might consider a spineplot where you plot the "countries" against the fraction of total "fruit".  If the fruit can be further categorized, you can incorporate that into a spineplot as well.


Differences between methods of reporting variance

Question: I am a neuroscience researcher without too much background in statistical theory.
I have multi recordings from different samples and I want to precisely report the variation across the samples, and I wanted to understand the differences between methods of doing this:

(arithmetic) Average of variances of the different samples
(arithmetic) Average of standard deviation of the different samples
(arithmetic) Average of SEM of the different samples
The variance of the average histograms of the different samples
The standard deviation of the average histograms of the different samples
The SEM of the average histograms of the different samples

The average histogram would be found by summing the percentage histograms of each samples in each histogram bin and then dividing the sample size.
I have a rough idea of the differences in each method, but not sure how to frame them in terms of statistical/probability theory. Thank you for your help as always!
Answer: First the obvious part. Variance and standard deviation are basically the same, the variance is simply the square of the standard deviation. I always prefer to use the standard deviation because it is easier to interpret, since it has the same units as your data.
The SEM (standard error of the mean) is the standard deviation of the sample mean. This just measures what is the expected error in your estimation of the mean of the population, since you don't have an infinite number of examples and you are using your sample to estimate the mean of the whole population.
You can of course, apply these measures for the same bin of several histograms...
The main question that you should answer is: What do you really want to show? Once you know this the choice should be obvious.
For example, if you want to show that all samples are very consistent/inconsistent, you could simply calculate the average sample standard deviation as well as the standard deviation of the samples' standard deviations. This could allow you to conclude something like, all samples have a very similar standard deviation of X, or, for instance, that all samples have in average a low standard deviation, but the sample standard deviation changes a lot between samples...
From your question I am not sure, but maybe an ANOVA analysis can be interesting for your case. https://en.wikipedia.org/wiki/Analysis_of_variance
There's a nice episode of the Data Skeptic podcast explaining it in very simple terms: https://dataskeptic.com/blog/episodes/2016/anova
Comment: Thank you for the answer; I am literally just trying to see the average. Then I will compare the average to a average of recording under different condition in each sample.
Comment: Also, arithmetic average of the std is different from the arithmetic mean variance (e.g. take std =3,4,5 avg var= 16; var = 9 16 25; avg std = 16.67); Is there a probabilistic interpretation of these differences?
Comment: "Then I will compare the average to a average of recording under different condition in each sample." then maybe what you need to do is a paired t-test. You calculate the standard deviation for each group for conditions 1 and 2. One pair will correspond to the 2 std. deviation values obtained for the 2 different conditions for the same group. You can calculate this with R or even with Excel. This way you will answer your question, whether the different measurement conditions have a significant impact on the standard deviation of the samples.
Comment: Regarding your example, I don't know exactly what you mean with probabilistic interpretation. The variance is the square of the std dev BUT the mean variance of different samples is NOT the square of the mean standard deviation over those samples.


Using System.Diagnostics C++.Net 2003 fx1.1

Question: When ClickOnce deploys apps, it generates an .application file that allows you to execute the application, so the main application is builded on C++.Net 2003 using Fx1.1, when I told him that call the first file (.application file from ClickOnce Deployment C# 3.0 app) he didnt know how ¿?!
I trying to write some code snippet, the code below cant "open" the .application file generated from ClickOnce.. Thanks
private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
             System::Diagnostics::Process app ;
             app.StartInfo->FileName = "C:\INFORME\SRIMedico.application";
             app.StartInfo->Arguments = "";
             app.Start();

         }

Answer: It's not very clear to me what is it exactly that you're looking for but as far as I know ClickOnce it not meant to be used to deploy VC++ applications.
See ClickOnce Deployment For Visual C++
Edit:
There's one thing that jumps out at me in your code example: You have not escaped the "\" character (which is a special character in C++) and in which case the path you supplied would be invalid. Please re-try it like this:

    // .. rest of code in your sample ommited
    app.StartInfo->FileName = "C:\\INFORME\\SRIMedico.application";
    // .. rest of code in your sample ommited

Another thing that I overlooked earlier is that while you may use System::Diagnostics::Process to launch a ClickOnce application installer, it only works using the location where you originally installed the application from, not the location where the application was installed.  See the Remarks section in the Process.StartInfo documentation.
You may also use the .appref-ms application reference file to launch the application, if you have it installed on the computer. Assuming this file is located in C:\INFORME\ you may write something like this:

    System::Diagnostics::Process^ app = gcnew System::Diagnostics::Process()
    app->StartInfo->FileName = "C:\\INFORME\\SRIMedico.appref-ms";
    app->StartInfo->Arguments = "";
    app->StartInfo->CreateNoWindow = "false";
    app->Start();

I hope this helps!
Comment: SRIMedico is and .application file generated by Deploying a C# 3.0 Application with ClickOnce


Unknown syntax with multiplication?

Question: So I have an assignment and this formula showed up:
$$\prod_{i<j} \;[\,p(j) - p(i)\,]$$
I have seen the multiplication sign before, I know what it is, but I don't know what '$i<j$' means in this context.
EDIT: I've looked all around the web for it, and I haven't found anything.
Answer: It means "the product over all pairs $i, j$ where $i < j$."  For example, if $p(i)$ is defined for $i = 1, 2, 3$, then
$$
\prod_{i<j} \;[\,p(j) - p(i)\;] = [ p(2) - p(1) ] [p(3) - p(1)] [p(3) - p(2)].
$$
Comment: Ha, logical indexing!
Answer: It means the product of every version of the expression in which $i <j $ and $i $ and $j $ are in some set implied from context.
Comment: Then you can also think of it as
$$\prod_{j=1}^8 \prod_{i=1}^{j-1} (p(j)-p(1))$$
Comment: @kccu, $p(1)$ should be $p(i)$ in your expression. And it might be more intuitive to have $j$ start at $2$.
Comment: They are in the set {1,2,...,8}
Comment: @MarkS. Right, that's a typo. Unfortunately it's too late to edit. Thanks.
Comment: @kccu Moderators can edit any comments any time. If you feel it's too embarrassing or misleading, you can ask them in chat or raise a flag to ask for correction. (I'm not sure how mods on this site take such flags, though.) And of course there is the option of deleting and recommenting.
Comment: @JoonasIlmavirta Thanks for the tip. Hopefully anyone who reads the comment will see the one below it correcting my typo.
Answer: The notation indicates that you just should take the product for indices $i$ strictly less than some other index $j$. Surrounding context should indicate what $j$ is.
For example:
$j=4$
$$\prod_{i<j} p(i) = p(1) \times p(2) \times p(3)$$
Assuming your indexing starts from $i=1$.
Hard to say more without context where the formula appears.
Comment: This is possible, but in my experience it is more common that such a product is actually over both indices *i* and *j*. As is often the case, context determines what notation means.

Unknown syntax with multiplication?


Add together simple equations

Question: I have three equations
$$
x = 20 \\
-x+a = 10 \\
y = 2
$$
Can I add these equations and get
$$
x-x+a+y = 20+10+2 \\
a+y = 32?
$$
If yes, what is the name of the rule applied?
Answer: You can definitely do this. I doubt that there is any name that is in general use. Its done so often in so many different contexts.

Add together simple equations


Função javascript não executa

Question: Tenho uma verificação em c# que caso ela seja verdadeira, executa a seguinte função em javascript:
@{
    if (!string.IsNullOrEmpty(TipoPecaController.MsgExcluir))
    {
        if (TipoPecaController.MsgExcluir == "3")
        {

        }
    }
}

Mas mesmo que a verificação seja verdadeira, o código em javascript não é executado
Comment: isso está numa pagina `.cshtml`, MVC?
Answer: Tente utilizar o ScriptManager
ScriptManager.RegisterStartupScript(this, GetType(), "YourUniqueScriptKey", "alert('This pops up');", true);

Mais detalhes:
http://msdn.microsoft.com/en-us/library/bb359558.aspx
Answer: O .ready(), vai realizar a ação assim que terminar de carregar a página, contando que você usa JQuery por estar com códigos .Net:

Ou você pode tentar sem atribuir um nome à sua função usando apenas Javascript puro:

Função javascript não executa


Multivariate Finite Difference Chain Rule in $GF(2)$ Polynomials

Question: In this question, user Yrogirg explains that it is possible to derive a chain rule for $GF(2)[\mathbf{x}]$. That is, there exists a finite difference chain rule for $GF(2)^n\to GF(2)$ functions, where the finite difference is given by the notation:
$$(D_u g)(\mathbf{x}) = g(\mathbf{x}+\mathbf{u})+g(\mathbf{x})$$
This rule then takes the form:
$$(D_u f\circ g) (\mathbf{x}) = (D_u f)(g(\mathbf{x}))\cdot (D_u g)(\mathbf{x})$$
At the end of their answer, they mention a problem that I would also like to know the answer to, is there a similar chain rule for functions $GF(2)^n\to GF(2)^m$?
Answer: So, I don't have time to work out the details, but I strongly believe that if a similar rule holds for functions from $GF(2)^n$ to $GF(2^m)$ it should be possible to verify under the idea of Hasse derivatives.
https://en.wikipedia.org/wiki/Hasse_derivative
Let $k[X]$ be a polynomial ring over a field $k.$ The r-th Hasse derivative of $X^n$ is
$${\displaystyle D^{(r)}X^{n}={\binom {n}{r}}X^{n-r},}$$
if $n \geq r$ and zero otherwise.
There is a nice discussion below:
https://math.fontein.de/2009/08/12/the-hasse-derivative/
Notes:
If you are only interested in first derivatives things are simpler.
You do have vectors, not scalars. In that case, the univariate representation under which the above quantities are defined may not be directly usable unless $m$ divides $n,$ i.e., we have a subfield relationship between the domain and range.
Also every function over finite fields is uniquely representable as a polynomial by Lagrange interpolation. So perhaps polynomials can play a role in any case.
Comment: Yes, I am only interested in the first derivative - I see a Faa di Bruno rule for univariate - but in Part II, the multivariate has no Faa di Bruno but what is really required: a kind of Jacobian. I think your hunch is fundamentally correct, however, all that is required is a multivariate Faa di Bruno's rule and then that can be applied to the coordinate functions that define the output above.

https://math.fontein.de/2009/10/02/the-hasse-derivative-part-ii-multivariate-partial-hasse-derivatives/


NFS export an overlay of ext4 and btrfs

Question: I have 2 data sources. One is btrfs (raid) and one is a simple ext4 partition. Those should be transparently displayed as one. This is a simple read only example, but the lower/upper/workdir version produces the same problem, with btrfs as upper and ext4 as lower.
manual mount:
mount -t overlay overlay -o lowerdir=/mnt/raid/folder1/:/mnt/ext4/folder1 -o comment=merge  -o nfs_export=on /data/merged

fstab mount:
overlay /data/merged overlay defaults,lowerdir=/mnt/raid/folder1/:/mnt/ext4/folder1,comment=merge,nfs_export=on 0 0

this is my nfs export:
/data/merged 192.168.0.0/255.255.255.0(ro,fsid=1,async,insecure,crossmnt)

exportfs -ra produces: exportfs: /data/merged does not support NFS export
My configuration:
Ubuntu 18.04 LTS with HWE kernel  4.18.0-13-generic
This is my main source for the config: https://www.kernel.org/doc/Documentation/filesystems/overlayfs.txt
Maybe I am missing some NFSv4 stuff (which is needed for nfs exporting an overlayfs) ?
edit: as requested, my mounts for the sourcecs:
UUID=d138b8fa-83e1-4df7-80dc-c1ed7d866f77       /mnt/raid       btrfs   defaults        0       2
UUID=6bb8f391-0872-40cf-8aff-8bdb32632098       /mnt/ext4        ext4    errors=remount-ro 0 2

edit2:
grep -H . /sys/module/overlay/parameters/*
/sys/module/overlay/parameters/nfs_export:N

Comment: result `/sys/module/overlay/parameters/nfs_export:N` --- so no support?
Comment: @BrianTheLion the comment option is an fstab feature: http://man7.org/linux/man-pages/man5/fstab.5.html
Comment: What kernel do you run? The message indicates that NFS exports are not supported with your kernel yet.
Comment: @Thomas uname -a = "4.18.0-13-generic #14~18.04.1-Ubuntu SMP Thu Dec 6 14:09:52 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux"
how can I find out if the kernel supports it? The feature is "availble" since 4.16
Comment: That kernel version should support it. You may want to add the kernel version and the output of `grep -H . /sys/module/overlay/parameters/*` to your question.
Comment: There does not appear to be an overlay option called "comment=". Please advise.
Answer: From kernel.org and from dmesg while trying to reproduce the error you also have to specify

-o index=on
-o index=on -o redirect_dir=nofollow when there is no upperdir

Your mount command then should be as follows.
mount -t overlay overlay -o lowerdir=/mnt/raid/folder1/:/mnt/ext4/folder1 -o comment=merge -o nfs_export=on -o index=on -o redirect_dir=nofollow /data/merged

The output of
/sys/module/overlay/parameters/nfs_export:N

shows the default of the mountoption and verifies that it is actually available.
Comment: From dmesg: overlayfs: NFS export requires "index=on", falling back to nfs_export=off.

NFS export an overlay of ext4 and btrfs


Banner animado com HTML5

Question: Boa tarde Pessoal, Recebi um pedido para criar um banner animado em HTML5. criei o banner utilizando o HTML e CSS, e funcionou corretamente. O cliente foi tentar implementar em seu site, que provavelmente é em wordpress, e não deu certo. Poderiam verificar o código e ver se o que eu fiz está correto, para eliminarmos a hipótese de erro no código? Desde já agradeço.

.box-banner{
    width: 300px;
    height: 250px;
    overflow: hidden;
    background: url("https://litens.com/wp-content/uploads/2018/09/fundo.png");
    position: relative;
    background-repeat: no-repeat;
  }

  @keyframes titulo-banner {
    0%   {left: -240px;}
    30%  {left: -240px;}
    40%  {left: -240px;}
    50%  {left: 15px;}
    90%  {left: 15px;}
    100% {left: 15px;}
  }

  .titulo-banner{
    width: 230px;
    padding: 5px;
    color: #fff;
    position: absolute;
    font-size: 30px;
    font-weight: bold;
    top: 18px;
    left: 15px;
    z-index: 1;
    line-height: 15px;

    animation: titulo-banner 3s ease-out 0s 1 normal;

    transition-timing-function: ease-in-out;
  }

  @keyframes logo-banner {
    0% {left: -170px;}
    30% {left: -170px;}
    40% {left: -170px;}
    50%{left: 20px;}
    90%{left: 20px;}
    100% {left: 20px;}
  }

  .logo-banner{
    position: absolute;
    bottom: 15px;
    left: 20px;
    animation: logo-banner 6s ease-out 0s 1 normal;
  }

  @keyframes fundo-logo-banner{
    0% {right: -300px;}
    30% {right: -300px;}
    40% {right: -300px;}
    50%{right: 0px;}
    90%{right: 0px;}
    100% {right: 0px;}
  }

  .fundo-logo-banner{
    position: absolute;
    bottom: 0px;
    right: 0;
    animation: fundo-logo-banner 5s ease-out 0s 1 normal;
  }

  @keyframes peca-banner{
    0% {right: -170px;}
    30% {right: -170px;}
    40% {right: -170px;}
    50%{right:  0px;}
    90%{right: 0px;}
    100% {right: 0px;}
  }

  .peca-banner{
    position: absolute;
    top: 43.5px;
    right: 0;
    animation: peca-banner 4s ease-out 0s 1 normal;
    z-index: 1;
  }

Answer: Eu testei seu HTML na ferramente de validação de HTML da W3C e nenhum erro foi encontrado (a não ser imagens sem o atributo alt). Vc mesmo pode testar aqui e mostrar pro seu cliente: https://validator.w3.org/#validate_by_input

Eu testei seu CSS na ferramente de validação de CSS da W3C e nenhum erro foi encontrado, passou com 100%. Vc mesmo pode testar aqui e mostrar pro seu cliente: https://jigsaw.w3.org/css-validator/#validate_by_input

No console do Chrome Dev Tools também não apareceu erro algum.
Agora vamos ao que eu acho que pode ser o seu problema. vendor prefix
Certifique-se que seu CSS tem os prefixos para funcionar em todos os browser. Se o browser do seu cliente não der suporte a @keyframes por exemplo certamente o código vai dar problema lá
Aqui tem uma ferramente de "auto prefixar" o CSS. As vezes pode te ajudar: https://autoprefixer.github.io/
Aqui já tem seu CSS prefixado:

.box-banner{
    width: 300px;
    height: 250px;
    overflow: hidden;
    background: url("https://litens.com/wp-content/uploads/2018/09/fundo.png");
    position: relative;
    background-repeat: no-repeat;
  }

  @-webkit-keyframes titulo-banner {
    0%   {left: -240px;}
    30%  {left: -240px;}
    40%  {left: -240px;}
    50%  {left: 15px;}
    90%  {left: 15px;}
    100% {left: 15px;}
  }

  @keyframes titulo-banner {
    0%   {left: -240px;}
    30%  {left: -240px;}
    40%  {left: -240px;}
    50%  {left: 15px;}
    90%  {left: 15px;}
    100% {left: 15px;}
  }

  .titulo-banner{
    width: 230px;
    padding: 5px;
    color: #fff;
    position: absolute;
    font-size: 30px;
    font-weight: bold;
    top: 18px;
    left: 15px;
    z-index: 1;
    line-height: 15px;

    -webkit-animation: titulo-banner 3s ease-out 0s 1 normal;

            animation: titulo-banner 3s ease-out 0s 1 normal;

    -webkit-transition-timing-function: ease-in-out;

         -o-transition-timing-function: ease-in-out;

            transition-timing-function: ease-in-out;
  }

  @-webkit-keyframes logo-banner {
    0% {left: -170px;}
    30% {left: -170px;}
    40% {left: -170px;}
    50%{left: 20px;}
    90%{left: 20px;}
    100% {left: 20px;}
  }

  @keyframes logo-banner {
    0% {left: -170px;}
    30% {left: -170px;}
    40% {left: -170px;}
    50%{left: 20px;}
    90%{left: 20px;}
    100% {left: 20px;}
  }

  .logo-banner{
    position: absolute;
    bottom: 15px;
    left: 20px;
    -webkit-animation: logo-banner 6s ease-out 0s 1 normal;
            animation: logo-banner 6s ease-out 0s 1 normal;
  }

  @-webkit-keyframes fundo-logo-banner{
    0% {right: -300px;}
    30% {right: -300px;}
    40% {right: -300px;}
    50%{right: 0px;}
    90%{right: 0px;}
    100% {right: 0px;}
  }

  @keyframes fundo-logo-banner{
    0% {right: -300px;}
    30% {right: -300px;}
    40% {right: -300px;}
    50%{right: 0px;}
    90%{right: 0px;}
    100% {right: 0px;}
  }

  .fundo-logo-banner{
    position: absolute;
    bottom: 0px;
    right: 0;
    -webkit-animation: fundo-logo-banner 5s ease-out 0s 1 normal;
            animation: fundo-logo-banner 5s ease-out 0s 1 normal;
  }

  @-webkit-keyframes peca-banner{
    0% {right: -170px;}
    30% {right: -170px;}
    40% {right: -170px;}
    50%{right:  0px;}
    90%{right: 0px;}
    100% {right: 0px;}
  }

  @keyframes peca-banner{
    0% {right: -170px;}
    30% {right: -170px;}
    40% {right: -170px;}
    50%{right:  0px;}
    90%{right: 0px;}
    100% {right: 0px;}
  }

  .peca-banner{
    position: absolute;
    top: 43.5px;
    right: 0;
    -webkit-animation: peca-banner 4s ease-out 0s 1 normal;
            animation: peca-banner 4s ease-out 0s 1 normal;
    z-index: 1;
  }

E aqui tem um saite onde vc pode consultar o suporte dos browsers ao estilos de CSS como por exemplo o @keyframes: https://caniuse.com/#feat=css-animation

Em último caso o problema não é com seu código, é na forma como o cliente está fazendo a implantação ao meu ver!
Comment: Agradeço o feedback e toda ajuda com os diversos meios em que testou meu código. Realmente, faltou a parte dos prefix. Fiz essa inclusão e mandei novamente para o cliente. Vamos ver o que ocorre. Se caso o erro persista, acredito também que o problema esteja na implementação. Mais uma vez, muito obrigado!
Comment: @WelkerZigante pois eh, da parte do seu código vc pode ficar tranquilo, inclusive com esses links vc pode provar pro cliente que o problema não eh com o seu trabalho! De qq forma boa sorte ai!

Banner animado com HTML5


Flutter:Instance of 'SharedPreferences'

Question: I was using shared_preferences plugin in my Flutter application, I want to save data when the user selects the city.
But when I try to print it just says;

Instance of 'SharedPreferences' Unhandled Exception: setState()
callback argument returned a Future

. (Even if I remove my setState part I get the same error)in my console.
does anyone know the reason??
My text in the in card widget
<code> Padding(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 8.0),
                                child: Text(
                                  snapshot.data.name,
                                  style: TextStyle(fontSize: 16),
                                ),
                              ),
</code>
and when clicked where I saved it
<code>   onTap: () {
                            setState(() async {
                              final country =
                                  await SharedPreferences.getInstance();
                              String name;
                              name=snapshot.data.name;
                              country.setString('name', name);
                              print('here $country');

                            });
                          },
</code>
Answer: Try
<code> onTap: () async {
  final country =
      await SharedPreferences.getInstance();
  setState(() {
  String name;
  name=snapshot.data.name;
  country.setString('name', name);
  print('here $name);

  });
},
</code>
Comment: To add some explanation to this answer, the callback of `setState` cannot be async. This is mentioned in the documentation: https://api.flutter.dev/flutter/widgets/State/setState.html
Comment: this time it only writes Instance of 'SharedPreferences'
Comment: not getting what you mean? can you explain little bit?
Comment: no, I mean nothing changed when I wrote the solution you said. I still have the same output on my console, it only says Here Instance of 'SharedPreferences' no more
Comment: could you restart the application and re-run app again
Comment: i did but still the same
Comment: You are getting this because you are printing the instance of SharePreference which is country.  Use country.getString('name');
Comment: I don't know how I made such a mistake.:) thank you so much!

Flutter:Instance of 'SharedPreferences'


Yoneda's lemma: group morphisms give Hopf-algebra morphisms

Question: Let $k$ be a commutative ring. Let $\text{Alg}$ be the category of commutative $k$-algebras and $\text{CHopf}$ the category of commutative Hopf-algebras. Let us also write $[\text{Alg}, \text{Grp}]$ for the category of representable functors $\text{Alg} \to \text{Grp}$ (the morphisms are natural transformations between such functors).
We have an obvious functor
$$\text{CHopf}^{op} \to [\text{Alg}, \text{Grp}]: H \mapsto \text{Hom}_{\text{Alg}}(H,-)$$
since the sets $\text{Hom}_{\text{Alg}}(H,A)$ obtain a group structure via convolution for every algebra $A$. Concretely, the multiplication is defined by
$$f \star g := \mu(f \otimes g)\Delta$$ where $\mu$ is the multiplication on $A$ and $\Delta$ is the comultiplication on $H$. On the level of morphisms, the above functor is defined using the Yoneda lemma.
I'm trying to show that this functor is fully faithful. For this, I need to show that if $\lambda: \text{Hom}_{\text{Alg}}(H,-) \to \text{Hom}_{\text{Alg}}(H',-)$ is a natural transformation that consists of group morphisms and where $H,H'$ are commutative Hopf-algebras, then the morphism
$$\lambda_H(\text{id}_H) \in \text{Hom}_{\text{Alg}}(H',H)$$
is a Hopf-algebra morphism. In particular, I try to check that
$$(\lambda_H(\text{id}_H) \otimes \lambda_H(\text{id}_H))\Delta_{H'}= \Delta_H \lambda_H(\text{id}_H).$$
First of all, is this true? If it is true, how can I show it? I have tried to exploit the fact that $\lambda_H$ is a group morphism but could not conclude.
Comment: Isn't this a general fact about group objects? See for instance the stuff at the end of https://math.fontein.de/2009/08/16/fun-with-representable-functors-or-why-i-like-yondeas-lemma/  .  You can apply this in the category of affine group schemes rather than Hopf algebras in order to only deal with group objects rather than co-group objects.
Comment: I'm not too sure about the specifics regarding Hopf algebras, but shouldn't a simple categorical argument showing both sides are the same after applying $p_1$ and $p_2$ respectively (where $p_1$ and $p_2$ are the standard projection morphisms $H \times H \to H$ on the first and second factor) do the trick?
Comment: @Rushy I don't quite see how that works. Can you maybe elaborate?
Comment: Ah sorry, I spoke a bit too soon, I forgot for a moment the tensor product is a coproduct so that approach doesn't work. I'm not quite sure how to show it then
Comment: @Rushy No worries, I'm not sure either ;)
Comment: @babu_babu I'm not too familiar with the language used there. If you want, you can try to write an answer.
Answer: The condition that $\lambda$ preserves the group structure is equivalent to saying that, for any $A \in \text{Alg}$, the diagram
$\require{AMScd}$
\begin{CD}
\text{Hom}_{\text{Alg}}(H \otimes_{k} H, A) @>{- \circ \Delta_{H}}>> \text{Hom}_{\text{Alg}}(H,A) \\
@V{- \circ (\lambda_{H}(\text{id}_{H}) \otimes \lambda_{H}(\text{id}_{H}))}VV @VV{- \circ \lambda_{H}(\text{id}_{H})}V\\
\text{Hom}_{\text{Alg}}(H' \otimes_{k} H' ,A) @>>{- \circ \Delta_{H'}}> \text{Hom}_{\text{Alg}}(H',A)
\end{CD} commutes ("$- \circ f$" means "precomposition by $f$"). Take $A := H \otimes_{k} H$ above, and consider the image of $\text{id}_{H \otimes_{k} H} \in \text{Hom}_{\text{Alg}}(H \otimes_{k} H,H \otimes_{k} H)$ in $\text{Hom}_{\text{Alg}}(H',H \otimes_{k} H)$; via the bottom-left corner, the image is $(\lambda_{H}(\text{id}_{H}) \otimes \lambda_{H}(\text{id}_{H})) \circ \Delta_{H'}$, and via the top-right corner, the image is $\Delta_{H} \circ \lambda_{H}(\text{id}_{H})$.


volume of a solid with a cylindrical hole

Question: A sphere of radius 'a' has a cylindrical hole of radius 'b' bored from it. The axis of the cylinder coinciding with the diameter of the sphere. find the volume of the remaining part of the sphere.
 I am having problem in calculating the volume of the cylinder.
Answer: In order to go about this problem, we need to look at it in terms of two parts: the top and the bottom of the sphere where the cylinder intersects the sphere.
Here is what the sphere and cylinder hole would look like on a cartesian plane
These interception points will be your bounds as they define where exactly the cylinder will be drilling into the sphere
Keeping those bounds in mind, you can then construct the two equations (the sphere and the cylinder). Remember which one is on top, which in this case is the sphere.
Top function (sphere/circle) $$ f(y) = \pm \sqrt{(a^2 - y^2)} $$
Bottom function (cylinder) $$ g(y) = x = b $$
Now you have all you need in order to create your integral! Since the volume also includes an extrusion, you are doing the difference of two equations!
$$ V = \int_{\sqrt{(a^2 - b^2)}}^{-\sqrt{(a^2 - b^2)}}π[f^2(y) - g^2(y)] dy $$
Just to make it look less messy, I'm going to replace the square root of a^2 - b^2 as u
$$ V = \int_{u}^{-u}π[a^2 - y^2 - b^2] dy $$
With this integral, just integrate it like you normally would and you should get the following equation:
$$ V = (4/3)(π)(a^2 - b^2)^{3/2}  $$
And if you think about it, if there was no cylinder to begin with (b = 0), you get the equation for the volume of a sphere!
Please let me know if anything needs clarifying!


"$L/K$ forms of each other"

Question: In section $4$ of these notes, the author says two algebraic groups $G$ and $H$ defined over a field $K$ are "$L/K$ forms of each other" if they are "isomorphic over $L$", where $L$ is a finite field extension of $K$.  I'm trying to understand what this means.
Given an algebraic group $G$ defined over $K$, is the product of varieties $G\times L$ an algebraic group over $L$?  Here, we consider $L$ to be $\mathbb{A}_K^n$ where $[L:K]=n$.  If this is true, does this phrase "isomorphic over $L$" mean that $G\times L\cong H\times L$ as algebraic groups over $L$?  If so, can someone give me an example of two non-isomorphic algebraic groups $G$ and $H$ defined over $\mathbb{R}$ such that $G\times\mathbb{C}\cong H\times\mathbb{C}$?  Examples in positive characteristic would be great too if they are readily available.
If I'm way off track, please help me understand section $4$ of the linked notes.  Thanks!
Comment: Your putative definition isn't quite right; for one thing. it doesn't take into account the structure of $L$ as a $K$-algebra. Instead the right thing to do is to use _base change_. You can read about this in generality in a textbook about algebraic geometry, but as a concrete example, suppose $G$ is an affine algebraic group over $K$. Then base change means that if $G$ has coordinate ring $K[x_1,\ldots,x_n]/I$, we look at the ring $L[x_1,\ldots,x_n$ instead; the corresponding variety is then the base change $G_L$. (Note: this doesn't have anything to do with $G$ being a group; it could be...
Comment: any variety over $K$.) Unfortunately I don't have a good example to hand of groups over $\mathbf{R}$ which are $\mathbf{C}/\mathbf{R}$-forms of each other, but you can try googling "nonsplit torus" and see where it leads!
Answer: This is not quite right. Instead of the product $G\times \mathbf A^1_L$, you should take the base-change $G_L:=G\times_{\operatorname{Spec}K}{\operatorname{Spec}L}$. The algebraic group structure carries over to $G_L$, which makes it into an algebraic group over $L$.
For example, consider the elliptic curves
$$E: \quad y^2=x(x+1)(x+2),$$
$$E': \quad -y^2=x(x+1)(x+2).$$
They are both defined over $\mathbf R$, but they are not isomorphic over $\mathbf R$. However, over $\mathbf C$, we have an isomorphism $E_\mathbf C \to E_\mathbf C'$ given by $(x,y) \mapsto (x,iy)$:
$$-y^2=x(x+1)(x+2)\quad \Rightarrow \quad(iy)^2=x(x+1)(x+2).$$
Thus, $E$ and $E'$ are $\mathbf C/\mathbf R$-forms of each other.
Of course, there are many other examples.
Answer: For an example in positive characteristic, let $k$ be a finite field and let $k^\prime$ be an extension of degree $d>1$. The restriction of scalars $T=\mathrm{Res}_{k^\prime/k}(\mathbf{G}_m)$ of the multiplicative group over $k^\prime$ is an algebraic group over $k$ characterized up to $k$-isomorphism by the equality $T(R)=(R\otimes_kk^\prime)^\times$ for all $k$-algebras $R$. It is an example of a non-split torus. More precisely, $T$ becomes isomorphic to $\mathbf{G}_m^d$ after base change to $k^\prime$, but it is not isomorphic to $\mathbf{G}_m^d$ over $k$, as can be seen by the Galois action on the character groups (the character  group of $\mathbf{G}_m^d$ has trivial $\mathrm{Gal}(\bar{k}/k)$-action, while the character group of $T$ is isomorphic to $\mathbf{Z}[\mathrm{Gal}(k^\prime/k)]$ as a $\mathrm{Gal}(\bar{k}/k)$-module).
This example works more generally with $k^\prime$ a non-trivial finite separable extension of any field $k$ ($T$ will then become isomorphic to a product of copies of $\mathbf{G}_m$ over any extension of $k$ containing a normal closure of $k^\prime$).
A different sort of example arises from a finite-dimensional central simple algebra $B$ over a field $k$ of dimension $n^2$. Such an algebra satisfies $B\otimes_k\bar{k}\cong\mathrm{Mat}_n(\bar{k})$, and in fact becomes isomorphic to the $n\times n$ matrix algebra after base change to an appropriate finite extension of $k$. There is an algebraic $k$-group $G_B$ characterized up to isomorphism by the equality $G_B(R)=(R\otimes_kB)^\times$ for all $k$-algebras $R$, and if $k^\prime/k$ splits $B$, then $G_B\times_kk^\prime\cong\mathrm{GL}_n$.

"$L/K$ forms of each other"


How would I get actual values out of this equation?

Question: In trying to solve an equation $(8 \% x) \%3 = 2$, I used this:
$x \% a=b$ can become $x \equiv b + a \mathbb Z$, to get this:
$8 \% x \equiv 2 + 3 \mathbb Z$$2+3 \mathbb Z \in \mathbb Z_x$
I then used this:
$a\%x=b$ can become $x|(b-a)$, $x > b$, to get this:
$x | (2+3 \mathbb Z - 8)$$2+3 \mathbb Z \in \mathbb Z_x$
$x > 2+3 \mathbb Z$
I think a more appropriate way to write it is probably this way:
$x | (d - 8)$
$d = 2+3 \mathbb Z$
$d \in \mathbb Z_x$
$x > d$
Now, how do I actually get values for $x$ out of this beast?
I've tried plugging in some values for $x$ into this final equation and evaluating to see if they are true or not.  3 seems to be a valid answer, but i'm still just "hunting" for answers to $x$, which makes me feel like there must be a better way to actually unravel the thing and get a better description of what numbers actually solve the thing.
Comment: This ($d = 2+3 \mathbb Z$) may or may not be appropriate in your community; still, I'd rather go with $d=2+3k,\;k\in\mathbb Z$.
Comment: You can't really toss around that $\mathbb Z$ like just another number. Look at it the other way. $8\%x$ can't be more than 8; what can it be?
Comment: Interesting pov, it has to be in $\mathbb Z_8$.  Gotta chew on that a bit...  BTW i edited my question.  Do you approve of my usage of $\mathbb Z$ now? I think it ought to be more correct...
Comment: my community is "game programmers trying to learn enough math to do interesting things" hehe.  I will take your style over my improvised one, so I won't look like such a buffoon in the future.  Thank you (;
Answer: First, if $x>8$, then $8\% x=8$ so $(8\% x)\% 3 = 8\% 3 = 2$ so this is true for all $x>8$.
This just leaves us to check $1,2,\dots,8$.

$(8\% 1)\% 3 = 0 \% 3 = 0$
$(8\% 2)\% 3 = 0 \% 3 = 0$
$(8\% 3)\% 3 = 2 \% 3 = 2$
$(8\% 4)\% 3 = 0 \% 3 = 0$
$(8\% 5)\% 3 = 3 \% 3 = 0$
$(8\% 6)\% 3 = 2 \% 3 = 2$
$(8\% 7)\% 3 = 1 \% 3 = 1$
$(8\% 8)\% 3 = 0 \% 3 = 0$

So I guess your solutions are $x=3$, $6$, or anything bigger than $8$.
Comment: So obvious now that you've said it.  Thank you so much!
Comment: Sure. No problem. I was trying to think of a "slick way" to tackle this problem, but somehow composing "mod" operators with a variable modulus is kind of a weird thing to be doing. Case-by-case seems like the easiest route to the answer. :)
Comment: I'm going to have to try and figure out a more symbolic solve at some point I think. I have multiple equations of this form that need to be solved simultaneously. Seems like it might be hard :/


Two identical files; Apache says one is forbidden

Question: I've got this one file, favicon.ico. It's actually a large group of nested files, but purely for example, just this one.
If I do cp favicon.ico favicon2.ico, Apache can read the second one just fine.
If I do mv favicon.ico favicon3.ico, Apache throws a 403 on favicon3.ico.
If I su apache, I can read the file as apache.
stat says both files are identical, except for the inode number.
Is there some hidden flag somewhere or something that I'm missing? I've never seen anything like this.
error_log says (13)Permission denied: access to /favicon3.ico denied
Comment: An answer to another question might offer assistance to others running across this question; it presents a more broad approach to dealing with SELinux issues and web servers : https://serverfault.com/a/551801/101931
Comment: Are you sure the `/favicon3.ico` path is OK?
Answer: SELinux is denying you access to the file, since you moved instead of copied it from somewhere else on the filesystem into its final location. Thus it kept its original security context, which didn't allow Apache to access it.
To resolve the issue, relabel the file (and probably all the rest of your files).
For example:
restorecon -r -v /var/www/html

To avoid the problem in future, copy files (and delete the original if necessary).


In feature selection, I came across a situation where NaN were filled by median of the column values

Question: Why median value is used for NaN? Why not something else like mean? What is the logic behind using median value?
Comment: Median belongs to so called "robust" statistics. If a mean may be a subject to outliers, median is not so sensitive to them. This is the logic behind using median for imputation more often than mean
Comment: This is off-topic for Stack Overflow as it's about statistics/data analysis, not programming; [here is a question on stats.SE](https://stats.stackexchange.com/questions/257672/can-i-replace-nas-based-on-response-variable/) about the options for how to replace missing values in a dataset which may be useful. Please see the [help page](https://stackoverflow.com/help/on-topic) about what is on-topic here.
Answer: The process you described is known as imputation. Whether it makes sense to impute missing values with mean or median depends entirely on the dataset and the context of your problem.
Usually, it does not hurt to impute missing values with the mean. However, if there are outliers in the dataset that adversely impact the mean, then it is probably a good idea to impute with the median, as the median is a metric that is not influenced by the presence of outliers in the dataset.


Laravel API: RegisterController set a default value on creating an User not working

Question: I started working on a Laravel API project.
I added a column to the users table to refer to the account id.
After updating the Model with the needed fillable key, the column value
stays empty after registring an user. I dont actually know where the problem is.
Also the return is not containing the new column.
User Model
<?php

namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $fillable = [
        'name', 'email', 'password', 'account_id',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    protected $table = 'api_users';
}

Register Controller: create function
protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'account_id' => time(),
    ]);
}

Database Migration
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('api_users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('account_id', 60)->unique();
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('api_users');
    }
}

Comment: What if you replace `User::create` with `User::forceCreate`? Are you using the correct User import in your controller? Did you modified and re-run your migrations? Could you post these as well?
Comment: Its creating the data entry. But the column is just staying empty. Its the only User import, so it must be correct. I modified the migrations, but is there an another command for remigrating ? Using 'artisan migrate' just prints: nothing to migrate
Comment: If you don't mind losing the data you have in your tables you can do: `php artisan migrate:fresh` (drop all tables and migrate) or `php artisan migrate:refresh` (rollback and rerun migrations)
Comment: Regarding the user import was just making sure you imported the `App\User` model and maybe not `Illuminate\Foundation\Auth\User` as a mistake
Comment: @mdexp i added the migration now. I think a migrate wouldnt work at all, because the column definition and migration was added to a fresh project before migrating it
Comment: As Im saying the User Creation works. Its passing the data fine except my custom created column in the table. This field stays empty without a reason
Comment: I found out that the register controller is somehow not even used.. When I remove the class, the user is still getting created - no errors. So where is the actual function of creating the User in the Model ?
Comment: The `create` method is called by the `Illuminate\Foundation\Auth\RegistersUsers` trait, but it's strange that if you remove that controller the code still works. Can you provide the ouput of `php artisan route:list`?
Answer: Probably the foreign account_id reference you are using is not valid.
Comment: its basically just the new column i have added before migrating the users table Edit: // Or do you mean the name itself i have chosen is not valid ?
Comment: Could you give more information about the error?  mayb using try and catch?
Comment: @ManuelEduardoRomero there is no error given. The column just stays empty so I dont know where to search for..
Comment: Could you paste the datatable definition?
Comment: @ManuelEduardoRomero its a string based field: varchar(60): Default value => empty | Allow Null: true
Comment: time() is an integer. Maybe is that. Please try with casting  'account_id' => (string) time(), or set your column as integer.
Comment: @ManuelEduardoRomero I found out that the register controller is somehow not even used.. When I remove the class, the user is still getting created - no errors. So where is the actual function of creating the User in the Model ?
Comment: Creating function is in the parent class so, in Model. Model has a lots of traits you can investigate.


Expectation of the MLE $e^{-\frac{1}{\overline{X}}}$

Question: I am having a bit of a problem with examining the properties of a maximum likelihood estimator. I feel like I am missing something simple, but I have been unable to find someone doing an example quite like this and keep getting a bit lost.
So, basically, I have this random sample $(X_1,\ldots,X_n)$ from an exponential distribution with parameter $\theta$.
EDIT: I forgot to mention, I am using this form of the exponential pdf:
$$f(x_i;\theta)=\frac{1}{\theta} \exp(-\frac{x_i}{\theta}).$$
That is, $\lambda=\frac{1}{\theta}$. Just realized I should specify before people get confused. The reasons for using this variant of the pdf are sort of convoluted, and it unfortunately isn't feasible to change at the moment.
Finding the MLE and its properties are, of course, trivial. The MLE is simply the sample mean ($\overline{X}_n$). However, it is not this MLE I am interested in.
I am interested in a parallel random sample ($Z_1,\ldots,Z_n$), where $Z_i=\mathbb{I}(X_i>1)$. Again, finding the MLE isn't terribly difficult, due to the invariance property. That is, if $\hat{\theta}_x$ is the MLE of $\theta$ with respect to $X$, then $\tau({\hat{\theta}_x})$ is the MLE of $\tau(\theta)$. So,
$$\tau(\theta)=P(X>1)= \exp(-\frac{1}{\theta})$$
$$\tau({\hat{\theta}_x}) = \exp(-\frac{1}{\overline{X}_n})$$
gives me the MLE of $\theta$ with respect to $Z$. (I think… does this look right to everyone?)
However, this is where I get stuck. I am trying to investigate the properties of this MLE. Specifically, its bias/variance/MLE/asymptotic distribution.
How do I evaluate $E[e^{-\frac{1}{{\overline{X}}_n}}]$? I don't even know what distribution to take this expectation in relation to via integration/MGFs. Is it the distribution of $X_i$? Of $X_1,\ldots,X_n$? $Z_i$? $Z_1,\ldots,Z_n$?
Searching around, there was a similar problem encountered by a poster here:
Maximum likelihood estimator of $P(X < y)$ for fixed $y$
However, the final solution isn't posted, and I find the advice given to be confusingly phrased, so it isn't terribly helpful.
Anyway, anyone have some pointers for me? I can't see an easy solution.
Comment: Updated post to reflect new developments
Comment: You need to be clear about what you mean by "MLE of $\theta$ with respect to $Z$":  do you mean, given only the data $(Z_1, \ldots, Z_n)$, what is the MLE of $\theta$?  In that case, the answer cannot be the expression you have, because that is a function of $(X_1, \ldots, X_n)$.
Answer: Suppose we are given only $\boldsymbol Z = (Z_1, \ldots, Z_n)$, and we wish to find the MLE for the parameter $\theta$.  Then each $Z_i \sim {\rm Bernoulli}(p_i)$, where $p_i = \Pr[Z_i = 1] = \Pr[X_i > 1] = e^{-1/\theta}.$  Consequently, the likelihood for $\theta$ given $\boldsymbol Z$ is $$L(\theta \mid \boldsymbol Z) = \prod_{i=1}^n p_i^{Z_i} (1-p_i)^{1-Z_i} = e^{-n\bar Z/\theta} (1-e^{-1/\theta})^{n(1-\bar Z)}.$$  The log-likelihood is $$\ell(\theta \mid \boldsymbol Z) = -\frac{n \bar Z}{\theta} + n(1-\bar Z) \log(1-e^{-1/\theta}).$$  Taking the derivative with respect to $\theta$ and finding the critical points gives $$0 = \frac{n(\bar Z - e^{-1/\theta})}{\theta^2 (1 - e^{-1/\theta})},$$ or $$\hat \theta_Z = - \frac{1}{\log \bar Z}, \quad 0 < \bar Z < 1.$$  Note that if $\bar Z = 0$, then $\hat \theta_Z = 0$.  More problematically, if $\bar Z = 1$, then $\hat \theta_Z = + \infty$.  Equivalently, we could have immediately obtained this result from the familiar MLE of an IID Bernoulli sample, which is $\hat p = \bar Z$, and the transformation $$\hat \theta_Z = \tau(\hat p) = -\frac{1}{\log \hat p}.$$  What is its bias?  It is obviously infinite:  since $n \bar Z \sim {\rm Binomial}(n, p = e^{-1/\theta})$, there is a positive probability that $\bar Z = 1$ for any $\theta > 0$.  Therefore, ${\rm E}[\hat \theta_Z]$ cannot be finite.  This also means the variance of the estimator is undefined.


Make a smooth transition to items inside a container

Question: I would like to bring "Hello world" inside a white container from left to right but I don't want the container to move.
Need to move just text and the text flashes from left to right like a quick slider movement pleasing to the eye.
How to achieve this using CSS animation?

body {
  background: red
}

.container {
  background: white;
  color: black;
  padding: 20px;
  margin: 20px;
}

Hello world

Answer: for making the animation use @keyframes
and for making the text not visible if outside use overflow
forwards for saving the last keyframes of animation.

body {
  background: red
}

.container {
  background: white;
  color: black;
  padding: 20px;
  margin: 20px;
}

.container {
  overflow: auto; /* use "hidden" instead if it shows a unnecessary scrollbar. */
}

h1 {
  animation: toRight 0.2s ease-in forwards;
  transform: translateX(-50%);
}

@keyframes toRight {
  100% {
    transform: translateX(0);
  }
}

Hello world

Comment: @Indiestartupman yes, so the text not be show on red background, only white. this is working fine since the animation start from left to right, but if animation is right to left then use `overflow: hidden` so won't trigger a automatic scrollbar.
Comment: @Indiestartupman just change the seconds value, ❌`1s` ✅`0.2s` `animation: toRight 0.2s ease-in forwards;` hope it solve your bug. have a nice day!
Comment: This is what I wanted. Any reason why you are adding container overflow:auto?
Comment: How to speed up the movement from left to right. I want to make the movement quick?


Override Ext.Button OnRender event to enable/disable buttons

Question: I am trying to override onRender event in ExtJS 3.4.0 but this gives a script error: object does not support callParent. My objective is to enable or disable buttons based on the rights from session object.
Ext.override(Ext.Button, {
            onRender: function () {
                this.callParent();

                console.log('do something');
            }
        });

Answer: I have resolved with these lines of code:
Ext.onReady(function () {
Ext.QuickTips.init();
// get rights here

if (roles.length > 0) {
    Ext.override(Ext.Button, {
        initComponent: function () {
            //filter rights here with matching text
            // if length is greater than 0, then enable disable buttons
            if (buttonRights.length > 0) {
                if (this.text == buttonRoles[0].ItemText) {
                    this.setDisabled(!roles[0].IsAllowed);
                }
            }
        }
    });
}
});


Why does major 2nd have more harmonics than major 3rd?

Question: I was watching this video about Just-intonation tuning system. In this video he is explaining how the harmonics work.
He is explaining that the first harmonic is created by dividing a string into half, which has the lowest frequency. Then by dividing more, we will get higher frequencies.
He is also explaining that in the major 2nd the string is divided into 16 parts and has the 15th harmonic, and major 3rd is divided into 9 divisions and has the 8th harmonic. I understand that in a guitar, the closer the finger to the neck of the guitar, the lower the frequency would be. But I don't understand why major 2nd has more divisions than major 3rd? Shouldn't a major 3rd be higher in frequency than a major 2nd? Maybe he means that there is a major 2nd an octave higher than this major 3rd?
Answer: First, you seem to have associated the ratios with the wrong intervals: 16:15 is the ratio of a minor second, not a major second.  The major second is 9:8 or 10:9, and the major third is 5:4.
Second, you seem to be confused about how the intervals are derived from the harmonics.  Consider the 9:8 major second.  This is the ratio between the 9th harmonic and the 8th harmonic.  Now consider the 16:15 minor second, which is the ratio between the 16th and 15th harmonics.  Yes, the 16th harmonic is an octave higher than the 8th harmonic, but the 15th harmonic is also nearly an octave higher than the 8th harmonic, and the distance between the 16th and 15th harmonics is rather smaller than the distance between the 9th and 8th harmonics. Therefore, a minor second is smaller than a major second.
The fundamental of the overtone series that the ratio implies is not particularly important.  For example, suppose you want to calculate a 16:15 semitone above A=220. Hz. To do that, you multiply 220 Hz by 16 and divide by 15, yielding 234.67 Hz, which is roughly the same as the first-fret B♭ on a guitar.  To calculate a 9:8 whole tone above A=220 Hz, multiply by 9 and divide by 8, which gives 247.5 Hz, a higher pitch, roughly the same as a second-fret B.


Repository-UoW, EF POCO, RIA Services, ASP MVC & Silverlight cooperation possible?

Question: I 'm beginning a new web project and was wondering if i could benefit from the "magical" things RIA service can offer, but in a way i was used to develop until now.
This means i would like to architect the solution so that EF POCOs should be used, which are the basis for repositories (using IoC to resolve to concrete implementations), which the RIA service(s) use to be consumed by ASP MVC or Silverlight UI.
What concerns me a lot: will the Silverlight UI  have all the MVVM-infrastructure (change notification,...)?
Is this feasible or not?
Answer: It looks like  this has a lot of what i 'm willing to do.


${H}_0(X,A) = 0$ and $X=D^2, A = S^{1}$

Question: We know from Hatcher that ${H}_0(X,A) = 0$ iff $A$ meets every path component of $X$. A simpler case is that if $X$ is path-connected and $A$ is non-empty, then the first homology of the pair is zero.
I am not understanding where the following argument is wrong: $X=D^2$ is path-connected as contractible, $A=S^{1}$ is path-connected and meets the only path-component of $D^2$. Thus we should have $H_0(D^2, S^1)=0$ but we know that $D^2/S^1$ is homeomorphic to $S^2$, which has non-trivial $0-$th homology. Where do I go wrong?
EDIT: is it because the relative homology of a pair $(X,A)$ is not the homology of the quotient $X/A$?
Comment: See also https://math.stackexchange.com/q/2825944.
Comment: thanks, it helped a lot!
Answer: Under certain local niceness conditions (which are satisfied here), the relative homology of the pair $(X,A)$ is isomorphic to the homology of the quotient pair $(X/A,A/A)$ (an isomorphism is induced by the quotient map), which you can identify with the reduced homology of the space $X/A$, since $A/A$ is a point.
Comment: by local niceness, do you mean that the pair $(X, A)$ is good? am I correct to say the following: if the pair is good, then we can use an LES of reduced homologies to determine the homology of the quotient $X/A$. On the other hand,  if the pair is not good, then this LES does not hold. We must revert to the more general LES for any pair of spaces, where it is not true that $H_{i}(X,A)$ is the same as $H_{i}(X/A)$ in general. Thank you!
Comment: Yes, the condition is that the pair is good. The only difference between the reduced and unreduced homology of the space is in degree $0$, where reduced homology is free on one generator less. This discrepancy is what your example observes.

${H}_0(X,A) = 0$ and $X=D^2, A = S^{1}$


PingFederate TimeZone change option

Question: How to change/alter the timezone in PingFederate 6.10 version. So that it can be reflected in all SAML and OPENToken and in the receiver end, user will receive the token with newly updated date information.
Answer: Google is your friend! From the Ping support forums:
You can adjust this by editing the file: /pingfederate/etc/jetty-runtime.xml.
In this you will find a line <Set name="LogTimeZone">GMT</Set>
Adjust the Greenwich Mean Time(GMT) offset by adding or subtracting the number of hours you are from GMT.
For Example, for Eastern Standard Time(EST) with Daylight Savings Time(DST) offset it would be: <Set name="LogTimeZone">GMT-4</Set>

PingFederate TimeZone change option


Qual o mais recomendável "try" ou "if"

Question: {
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        double SalarioBase = 0, Descontos = 0, Vantagens = 0;
        try
        {
            SalarioBase = Convert.ToDouble(textBox1.Text);
            Vantagens = Convert.ToDouble(textBox2.Text);
            Descontos = Convert.ToDouble(textBox3.Text);
        }
        catch
        {
            MessageBox.Show("Valores Invalidos");
            return;
        }
        textBox4.Text = Convert.ToString (( SalarioBase + Vantagens ) - Descontos);
    }
}

Qual a diferença entre usar o if e o try
Comment: As duas respostas respondem bem a pergunta sobre `if` e `try..catch`, mas recomendo perguntar sobre arquitetura de software - tem tag especifica aqui no SO. No exemplo da sua pergunta a inteligência da sua aplicação está na "tela" ou *view*, e isso não é uma boa prática.
Answer:
Qual a diferença entre usar o if e o try

Bom, são bem diferentes entre si. if serve para fazer um fluxo condicional. try ... catch serve para pegar erros (ou exceções, no linguajar correto) e dar a esses erros o tratamento adequado.
Por exemplo, em seu código:
try
{
    SalarioBase = Convert.ToDouble(textBox1.Text);
    Vantagens = Convert.ToDouble(textBox2.Text);
    Descontos = Convert.ToDouble(textBox3.Text);
}
catch
{
    MessageBox("Valores inválidos");
    return;
}

Se houver um erro de conversão em qualquer um dos três campos, seu código irá para o catch, ou seja, imprimirá uma mensagem de erro e sairá da função.
Sobre o título da sua pergunta:

Qual o mais recomendável try ou if

Não existe isso de "mais recomendável" neste caso. Cada um serve a um propósito diferente, tanto que podem ser usados juntos. Por exemplo:
try
{
    if (!Double.TryParse(textBox1.Text, out SalarioBase))
    {
        MessageBox("Salário não está no formato correto.");
    }

    if (!Double.TryParse(textBox2.Text, out Vantagens))
    {
        MessageBox("Vantagens não está no formato correto.");
    }

    if (!Double.TryParse(textBox3.Text, out Descontos))
    {
        MessageBox("Descontos não está no formato correto.");
    }
}
catch
{
    MessageBox("Ocorreu algum erro não previsto.");
    return;
}

Answer: Eu não usaria nenhum dos dois, ou até usaria o if, mas de uma forma diferente:
using static System.Console;

public class Program {
    public static void Main(string[] args) {
        var textBox1 = "123.45"; //só para facilitar o teste
        var textBox2 = "10"; //só para facilitar o teste
        var textBox3 = "abc"; //só para facilitar o teste
        double SalarioBase;
        if (!double.TryParse(textBox1, out SalarioBase)) WriteLine("Salario Base foi digitado incorrentamente");
        double Vantagens;
        if (!double.TryParse(textBox2, out Vantagens)) WriteLine("Vantagens foi digitado incorrentamente");
        double Descontos;
        if (!double.TryParse(textBox3, out Descontos)) WriteLine("Descontos foi digitado incorrentamente");
        WriteLine(SalarioBase);
        WriteLine(Vantagens);
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Pra mim exceções só devem ser usadas em situações excepcionais (inclusive porque é lenta), o que não é o caso. Números digitados podem estar errados e é bem normal que a conversão não seja possível. Então prefiro o TryParse().
Alguém pode alegar que o try-catch pode resolver todos de uma vez só, só que normalmente não é o desejado, em geral para cada um precisa de um tratamento diferente. Uma função poderia simplificar esses casos.
Se estiver usando C# 7 pode simplificar cada bloco:
//note que não precisa declarar a variável aqui, ela fica disponível no escopo
if (!double.TryParse(textBox1, out var SalarioBase)) {
    WriteLine("Salario Base foi digitado incorrentamente");
}

Outro detalhe importante é não usar double para valor monetário, prefira decimal que funciona corretamente.
Answer: Quando você já espera por um erro, sempre utilizo o If, pois gera um código mais limpo.
Caso contrário, opte pelo try catch
Comment: Não sei porque tantos votos negativos. É simples: IF se o erro é esperado no fluxo do programa, caso contrário é uma exceção e deve ser usado o TRY/CATCH. O SOpt pune a objetividade e quem é conciso, e é inóspito pra iniciantes, que não entenderam ainda que aqui foge às regras de QA.

Qual o mais recomendável "try" ou "if"


Salvar dados de uma array em um banco de dados

Question: Preciso gravar o conteúdo de uma array que retornou de uma deserilização Json (retorno de um Json com mais de um nível), segue a linha com o método que extrai o array:
        Departmants dept = new Departmants();
        dept.Property1 = JsonConvert.DeserializeObject<Department[]>(json);

Classe com a estrutura da array:
   public class Departmants
    {
        public Department[] Property1 { get; set; }
    }

    public class Department
    {
        public int id { get; set; }
        public string name { get; set; }
        public bool temSub{ get; set; }
        public Sub[] subitem{ get; set; }
    }

    public class Sub
    {
        public int id { get; set; }
        public string name { get; set; }
        public bool temSub{ get; set; }
        public object[] subitem{ get; set; }
    }

Agradeço desde já a quem puder auxiliar.
Comment: Qual abordagem está usando? EntityFramework?
Comment: Rodrigo, estou utilizando o Framework 4.5.2.
Comment: A pergunta do Rodrigo é se você está usando algum ORM, tipo EntityFramework, Dapper ou se está usando ADO.NET no seu projeto.
Comment: só um detalhe, Departments e não Departmants ;)
Answer: Você tem algumas opções, usar EntityFramework, Dapper, ADO.Net ou qualquer outro.
Vou colocar aqui dois exemplos de insert utilizando o seu objeto.
Agora é só adaptar para as suas colunas e modelo da tabela e realizar o Insert, Update ou Delete. Eu particularmente gosto de trabalhar com o Dapper.
Com ADO:
using(SqlConnection connection = new SqlConnection("connectionstring")
{
    connection.Open();
    string sql =  "INSERT INTO Departmants (coluna1 ,coluna1) VALUES(@param1, @param2)";
        SqlCommand cmd = new SqlCommand(sql,connection);
        cmd.Parameters.Add("@param1", SqlDbType.Varchar, 50).value = Departmants.name;
        cmd.Parameters.Add("@param2", SqlDbType.Bool).value = Departmants.temsub;
        cmd.CommandType = CommandType.Text;
        cmd.ExecuteNonQuery();
}

Com Dapper:
Adicione o pacote no Nuget no Package Manager Console

Install-Package Dapper

using (var db = new SqlConnection(connstring))
{
    const string sql = @"INSERT INTO Departmants (coluna1 ,coluna1) VALUES(@param1, @param2)";

    db.Execute(sql, new { param1 = Departmants.name, param2 = Departmants.temsub }, commandType: CommandType.Text);
}

Comment: Obrigado pela dica!


Use .call when I instantiate a new class

Question: I try to call a function of classA inside my mainClass. And then I try to call functions of mainClass inside classA. I tried to use .bind() and .call() but it doesn't work. It only works if I use .bind(this) or .call(this) on functions, but not while I try to instantiate a new class.
index.js
let ClassA = require('./ClassA')

class mainClass {

    constructor() {
        this.doSomething()
    }

    doSomething() {
        let classA = new ClassA().call(this)
        classA.doSomething()
    }

    aFunction() {
        console.log('done')
    }

}

new mainClass()

classA.js
module.exports = class ClassA {

    constructor() {
    }

    doSomething() {
        console.log('doSomething')
        this.doSomething2()
    }

    doSomething2() {
        this.aFunction() // main Class
    }

}

TypeErrpr: this.doSomething2 is not a function
Comment: Side note: In general, calling instance methods from within a constructor is an anti-pattern. There *are* use cases for it, but in general, best avoided.
Comment: What are you trying to achieve with `.call(this)`? If you just removed it, your code would work...
Comment: How can I call aFunction() from classA then?
Answer: In a comment you've clarified what you're trying to do (it's also a code comment in the question):

How can I call aFunction() from classA then?

You'd do that by giving the code in ClassA access to your instance. You might pass it to the constructor which could save it as an instance property, or you might pass it to doSomething.
Here's an example passing it to the constructor:

class ClassA {

    constructor(obj) {           // ***
        this.obj = obj;          // ***
    }

    doSomething() {
        console.log('doSomething');
        this.doSomething2();
    }

    doSomething2() {
        this.obj.aFunction();    // ***
    }

}

class mainClass {

    constructor() {
        this.doSomething();
    }

    doSomething() {
        let classA = new ClassA(this);
        classA.doSomething();
    }

    aFunction() {
        console.log('done');
    }
}

new mainClass();


O notation verification?

Question: I see examples online that proves that if $f(n)\in O(h(n))$ and $g(n)\in O(h(n))$, then $f(n)+g(n)\in O(h(n))$ using the definition of O notation.
However, if given $f(n)\in O(h(n))$ and $g(n)\in O(h(n))$, then how can I prove/disprove:
$$f(n)*g(n)\in O(h(n))?$$
So far, I have gotten to defining (from the definition of O notation):
$$f(n)\ \le\ c_1h(n)\ for\ n\ \geq\ n_0^\prime$$
$$g(n)\ \le\ c_2h(n)\ for\ n\ \geq\ n_0^{\prime\prime}$$
where $c_1, c_2, n_0^\prime, n_0^{\prime\prime}$ are all positive constants, but I'm not quite sure what to do next. Do I multiply the constants together?
Any tips would be appreciated!
Comment: Of course this is not true. For example, $h(n)$ is $O(h(n))$ for obvious reasons, but $h(n) \times h(n)$ will definitely not be $O(h(n))$ if $h(n)$ is going to infinity, for example.
Answer: You cannot prove it, because it is false.
Counterexample: $f(n)=g(n)=h(n)=n$.
Then clearly $f(n)\in O(h(n))$, $g(n)\in O(h(n))$, but $f(n)g(n) = n^2 \not\in O(h(n)) = O(n)$.

O notation verification?


Are unidirectional vector fields conservative?

Question: There is no rotation for unidirectional (all the vectors pointing in the same direction whatever be their magnitudes) vector fields. Hence their curl must be zero. Hence all unidirectional vector fields MUST be conservative. Am I correct?
Comment: Notably, the field $(0,x,0)$ is neither curl-free nor conservative.
Answer: In addition to the computational answer of 'Lord Shark the Unknown', you can also look at this graphical example from Wikipedia:

Suppose we now consider a slightly more complicated vector field:
$${\mathbf{F}}(x,y,z) = - x^2 \hat{\mathbf{y}}$$
Its plot:

We might not see any rotation initially, but if we closely look at the right, we see a larger field at, say, $x = 4$ than at $x = 3$. Intuitively, if we placed a small paddle wheel there, the larger "current" on its right side would cause the paddlewheel to rotate clockwise, which corresponds to a curl in the negative $z$ direction. By contrast, if we look at a point on the left and placed a small paddle wheel there, the larger "current" on its left side would cause the paddlewheel to rotate counterclockwise, which corresponds to a curl in the positive $z$ direction. [...]
Answer: So one has a vector field, which in Cartesian coordinates is
$$(f(x,y,z),0,0).$$
So its curl is
$$\left(0,\frac{\partial f}{\partial z},-\frac{\partial f}{\partial y}\right).$$
Looks likely to be nonzero to me.


Joint distribution of discrete (Dirac) and continuous rvs

Question: so I have a discrete rv $Z \sim \frac{1}{2} \delta_{-1}+ \frac{1}{2} \delta_{1}$ and a continuous one $X \sim \mathcal{N}(0,1)$. Now I've tried to compute its joint distribution function $F^{(Z,X)}$ for $A=Z\cdot X,$ but the Dirac measure sort of puzzles me. I did end up with  a step function for $Z$ (cdf), but yet don't know how to incoperate $F_X$. Thanks in advance.
Answer: If you mean to find the joint distribution of $X$ and $Z$, it is simply$$f(x,z)={1\over 2\sqrt {2\pi}}e^{-{x^2\over 2}}\left[\delta(z-{1\over 2})+\delta(z+{1\over 2})\right]$$
because of independence.
If you mean to find the PDF of $A=X\cdot Z$, it could be written as $$\Pr\{A<a\}{=\Pr\{XZ<a\}
\\=\Pr\{XZ<a,Z>0\}+\Pr\{XZ<a,Z<0\}
\\=\Pr\{XZ<a|Z>0\}\Pr\{Z> 0\}+\Pr\{XZ<a|Z\le0\}\Pr\{Z\le 0\}
\\={\Pr\{XZ<a|Z=1\}\Pr\{Z> 0\}+\Pr\{XZ<a|Z=-1\}\over 2}
\\={\Pr\{X<a\}+\Pr\{X>-a\}\over 2}
\\={\Pr\{X<a\}}
}$$
which means that $A$ has the same distribution of $X$.
Comment: Thanks a lot. I'll try to find the exp. value of A, using f(x,z).


values of a variable for which a function attains its maximum

Question: I am given a function
$$f(x) = \begin{cases}
x^3 - x^2 + 10x - 5,  & \text{if x $\leqslant$ 1} \\[2ex]
-2x + log_2(b^2 - 2),  & \text{if x $\geqslant$ 1}
\end{cases}$$
I need to find the range of values of b so that f(x) has its maximum value at x = 1.
For this, I observe that the first part of the function is always increasing. Since it is not mentioned that the given function is continuous, and moreover the second function is continuously decreasing, hence I need to ensure that the value of the second function at x = 1 is less than the value of the first function at x = 1.
Am I correct? Or is there any flaw in my argument since I am getting the wrong answer according to my book.
Comment: Oh, I don't think the tag "functional analysis" is correct in this case, so you should remove or replace it with "maximum value of function" or something related to that.
Answer: You need to see the behavior of the function when $x<1$ and when $x>1$.
Observe the following case:

Case $x<1$
Note that for $x<1$, we have $f'(x) = 3x^{2} - 2x + 10$ which is strictly increasing and thus for any $x<1$, we know that $f(x)<f(1)$.
Case $x>1$
Now, for $x>1$, we know that $f'(x) = -2$ and therefore $f$ is strictly decreasing for any $x>1$.

Hence, the only possible solution for $f$ to have a maximum value is no other than $x=1$. However, from your definition, we know that $f(1)= 5 = -2+ \log_{2}(b^{2}-2)$. Therefore, you can get the result (by straightforward calculation) that either $b=\sqrt{130}$ or $b=-\sqrt{130}$.

I leave the detail of why $f'(x)$ is strictly increasing when $x<1$ but is strictly decreasing when $x>1$ as an exercise for you. The rest of the calculation is also easy so I am sure you can do it.


react lifecycle componentWillReceiveProps how to change getDerivedStateFromProps then send redux action

Question: componentWillReceiveProps as the warning lifecycle after react version 16.3, I am updating the old version to 16.4.2
The following are the common practices I used in the old version.
Receive actions in the componentWillReceiveProps cycle and call the function of this.props.xxxxActionsCreator dispatch redux action to drive itself and other component updates but after 16.3, getDerivedStateFromProps is static and cannot call this.
I would like to ask how to update the practice is the most appropriate?
import React from 'react';
import PropTypes from 'prop-types';
import Modal from 'antd/lib/modal';
import * as DeleteDialogActions from '../Actions/DeleteDialogActions';

export default class DeleteDialogView extends React.Component {
    constructor() {
        super();
        this.state = {
            showDialog: false
        };
    }

    componentWillReceiveProps(nextProps) {
        switch (nextProps.actionType) {
            case DeleteDialogActions.SHOW_DELETE_DIALOG:
            case DeleteDialogActions.HIDE_DELETE_DIALOG:
                this.showDialog();
                break;
            case DeleteDialogActions.DELETE_ITEM_SUCCESS:
                this.props.DeleteDialogActionsCreator.updateDialog();
                break;

            default:
                break;
        }
    }

    showDialog = () => {
        this.setState({showDialog: !this.state.showDialog});
        this.props.DeleteDialogActionsCreator.updateDialog();
    };

    handleOk = () => {
        this.props.DeleteDialogActionsCreator.doDeleteItem(this.props.deleteItemId);
        this.setState({showDialog: false});
    };

    handleCancel = () => {
        this.setState({showDialog: false});
    };

    render() {
        return (

                <Modal
                    title="Delete"
                    visible={this.state.showDialog}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    className="delete-dialog"
                >

Are you sure you want to delete the item with device ID {this.props.deleteItemId} ?

                </Modal>

        );
    }
}

DeleteDialogView.defaultProps = {
    deleteItemId: 0
};

DeleteDialogView.propTypes = {
    actionType: PropTypes.string.isRequired,
    deleteItemId: PropTypes.number.isRequired,
    DeleteDialogActionsCreator: PropTypes.object.isRequired,
};

Answer: Since you cannot access this inside the static getDerivedStateFromProps  method  you'll have to store or return a state by doing something like return { showDialog: true }; which is equivalent to this.setState({showDialog: true}). So you can check the state in componentDidUpdate life cycle method which will be only triggered if getDerivedStateFromProps returns a value which is not null.
  componentDidUpdate(prevProps, prevState) {
     if(this.state.showDialog){
           this.showDialog();
      }
     if(this.state.updateDialog){
      this.props.DeleteDialogActionsCreator.updateDialog();
     }
  }

   getDerivedStateFromProps(nextProps, prevState) {
          switch (nextProps.actionType) {
            case DeleteDialogActions.SHOW_DELETE_DIALOG:
            case DeleteDialogActions.HIDE_DELETE_DIALOG:
                 return { showDialog: true };
                break;
            case DeleteDialogActions.DELETE_ITEM_SUCCESS:
                 return { updateDialog: true };
                break;
            default:
                 return null;
                break;
        }
   }

Comment: Thank you this works, but every time you want to add a dispatch action, you have to add code in state and componentDidUpdate. It feels very complicated.


memory bandwidth bottle neck

Question: I have a python pandas program. When I run on AWS Ec2 with 8 cores. I got 100% CPU utilization and program finished in 8 minutes. Then if I go 16 cores, I can only get 50% CPU utilization and program still finish in 8 minutes. I suspect it hits memory bandwidth bottle neck so I selected X1,16xlarge instance which has 64 cores and claimed memory bandwidth of 300GB/s. However, it didn't help. the program used a tiny percentage of the 64 cores and didn't finished even after 10 minutes.
ec2 X1 instance
Any idea what's going on?
(by the way, the same program running on my old desktop tower with 4 cores finished in 16 minutes)
more details: the program uses GridSearchCV which then uses joblib to run multi-processing in parallel. Number of process always equals to the number of cores in the system.
Answer: Python has a "global interpreter lock" that limits its ability to utilize multiple threads efficiently. One responded on this site that you should consider writing time critical functions in C/C++.
If possible, consider breaking your analysis into smaller chunks and then run them as separate processes to avoid the global interpreter lock issue.
Comment: This is a great point but I am not sure it was what happened to me. Let me add more details to the original question. Thanks.
Comment: I checked every process that joblib starts. There is only one thread attached.

memory bandwidth bottle neck


Kafka Streams KTable store with change log topic vs log compacted source topic

Question: I'm building KTable on an input topic and I'm joining with KStream on two Kafka Stream application instances.
The input topic for KTable is already a log compacted topic. So when one of my application instance goes down, another instance state store seems to be refreshed with whole state by reading from the input log compacted topic.
So there is no need to enable logging (change log) for my KTable store?
My source input log compacted topic could have millions of records, so if i enable logging on that KTable state store will it improve my state store refresh time in case of failure or it will not have an effect as the source topic is already log compacted? Thanks!
Answer:
So there is no need to enable logging (change log) for my KTable store?

That's correct. Kafka Streams will not create an additional changelog topic, but will use the input topic for recovery (no need to duplicate data).

so if i enable logging on that KTable state store

How would you do that?

will it improve my state store refresh time in case of failure or it will not have an effect as the source topic is already log compacted?

In general, you would not gain anything. As you stated correctly, the input topic is compacted anyway, so both topics would contain roughly the same data.
If you want to decrease fail over time, you should configure StandbyTasks via StreamsConfig parameter num.standby.replicas (default is 0, so you could set it to 1). Cf https://docs.confluent.io/current/streams/developer-guide.html#state-restoration-during-workload-rebalance
Comment: Thanks! State restoration mentions abt using changelog and it was not clear in the doc, if the source topic itself is sufficient.
Comment: It's don't documented explicitly because it's an internal implementation detail / optimization and users don't need to worry about it.


FormData.append() is empty iterating over a FileList

Question: I have difficulty figuring out why formData is returning an empty object when iterating over a list of files and appending them to an empty instance FormData() using formData.append().
MDN https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

component.html
<input type="file" name="image" id="image" multiple accept="image/*" (change)="onImageSelect($event)"/>

component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-image-uploader',
  templateUrl: './image-uploader.component.html',
  styleUrls: ['./image-uploader.component.css']
})
export class ImageUploaderComponent {
  fileList: File[] = [];

  onImageSelect(files: any) {
    const formData = new FormData();

    this.fileList = files.target.files;

    for (const file of this.fileList) {
      formData.append('images[]', file, file.name);
      console.log(file, file.name);
    }
    console.log(formData); // returns an empty {}
  }
}

Comment: I think when iterating over an array you should use `for (const file in this.fileList)`
Comment: I can't get it working using for...in.

And funny enough although FileList is an Object and iterate over it using for...of and `console log(file, file.name) ` as the example above it logs what I think I need. A File object, the the File.name.

I'm confused
Answer: Always prefer typed alternatives. In this case you could use
<input #filePicker type="file" ... (change)="onImageSelect(filePicker.files)" />

And then, in the Component class
onImageSelect(files: FileList): void {
  ...

  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    formData.append('images[]', file, file.name);
  }
}

That's it.
Remember you cannot loop a FileList with a for-of as it lacks the Iterator Symbol.
Comment: Right. And you can't `console.log(formData)` you have to `console.log(formData.getAll('images[]')`


grab more results from DB as the user scrolls down the page...what's that called?

Question: I'm looking to implement something like Facebook's news feed, where when you load the page 'x' number of results are shown. As the user scrolls down, more results are brought back from the database. What is that called? ....are there any good tutorials out there on it? I'd prefer something in jquery but am open to other suggestions (I am using html, php, jquery, mysql)
Comment: Lazy Loading and infinite scroll are two terms to look for
Answer: its called 'infinite scroll'
here's a jquery library to do that
http://www.infinite-scroll.com/


making 2 digit month and day columns in R

Question: I'm very new to R, so this might seem straightforward. But I have a data frame with an original date column that has values that look like this: 4-02-91, 5-29-93 (i.e. m-d-y). I am trying to separate this column into 3, where months, days, and years are separate. Then I need to combine them again to this format 19910402, 19930529 - I need it this way in order to compare it to another dataset with similar dates.
Here is what I've been trying to do:
# Make DATE an actual date column
dataframe$DATE <- as.Date(used$DATE, format="%m-%d-%Y")
# This changes the original date column into something that looks like this: 1991-04-02, 1993-05-29

# Separate DATE into multiple columns
dataframe$year <- year(dataframe$DATE)
dataframe$month <- month(dataframe$DATE)
dataframe$day <- day(dataframe$DATE)

# Combine dates again to get string
dataframe$raster_date<-paste(dataframe$year, dataframe$month, dataframe$day, sep = "")

The last step looks great except where the months or days are single digits. It's coming out as 199142 and 1993529 instead of 19910402 and 19930529. How do I insert zeros when the month and day values are 1 digit?
Answer: Here, we can use sprintf instead of paste as the year, month, day from lubridate extracts those as numeric values and numeric class would drop the 0 padded as prefix.  We add those prefix with 0s in sprintf
sprintf("%04d%02d%02d", dataframe$year, dataframe$month, dataframe$day)


Extrair valores de uma string em javascript

Question: Tenho uma página que apresenta informações através de AJAX. Cada vez que eu faço uma pesquisa, tenho o valor da pesquisa e página no URL, da seguinte forma:

/Material/Index??palavraChave??numPagina

Eu consigo buscar esses valores através do .split("??"), mas queria implementar algo mais intuitivo:

/Material/Index?qw=palavraChave&pag=numPagina

Como faço para guardar numa variável só a palavraChave e noutra a numPagina e o mais importante: a palavra chave pode faltar, mas ter o número da página. Com os pontos de interrogação que eu tenho não consigo saber se o que tenho no URL é um valor para pesquisa, ou uma página.
Comment: Como está seu ajax para criar essa URl?
Comment: Não uso ajax para criar a url, estou a usar pushState() e passo as variáves que o utilizador introduzir numa caixa de pesquisa,
Answer: Você pode usar location.search que irá retornar de ? até o final da URL. Então depois tratar o resultado.
Exemplo para o seu caso:
var url = window.location.search; // retorno será algo como: '?qw=palavraChave&pag=numPagin';
var campos = url.split('=');

Simulação do tratamento:

var url = window.location.search; // retorno será algo como: '?qw=palavraChave&pag=numPagin';
var resExamplo = '?qw=stackoverflow&pag=10';
var campos = resExamplo.split('=')[2]; // obter o numero da pagina
console.log(campos);
Comment: O problema desse código é parecido ao meu: se não houver uma keyword de pesquisa então ele vai assumir que a página é a keyword. Queria algo que "soubesse" identificar cada variável.
Comment: "ele vai assumir que a página é a keyword". Não tem mágica para obter os parâmetros de uma URL, você vai precisar obter a URL de alguma forma e verificar o que está nela. No exemplo de tratamento, é possível "saber" cada variável, tanto o nome como o valor.
Comment: eu sei que não tem mágica, mas descobri que existe regex. Mas com essa técnica que você colocou é possível "saber" qual é qual de que forma?
Answer: Como você trabalha com uma string pequena e tem um padrão. pode tentar utilizar regex.
qw=([A-Za-z0-9]+)&pag=([0-9]+)

onde o que se encontra entre parênteses são os grupos que são importantes para você.
exemplo do seu caso
Comment: consegui perfeitamente usando essa técnica, obrigado! regex é muito bom!


How to configure Magento API with Appgyver Composer?

Question: I'm interested in creating a mobile app for android and ios that is connected to my magento store.
I am currently using appgyver composer to do this, but i'm unable to properly configure the magento API with appgyver to receive and send data to and from my magento store. Could someone tell me the process of integrating magento REST API with appgyver composer?
Answer: After using Postman app to look at the code Magento API generated and compared it with Appgyver API example, i realized the formatting was different. Luckily i came across a an REST API extension on Github for Magento, which extends Magento's REST API capabilities and also provided the format i needed. You cant find it here.
I was then able to easily use the Appgyver Composer REST API configuration page to link Magento to the app i am trying to create.
Answer: <code>How to integrate magento api, It's getting 500 error but it working on postman, we request volley get request and put parameter in url and header also but it still not working....pls help me

RequestQueue requestQueue = Volley.newRequestQueue(HomeProductActivity.this);
        JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, "http://126.96.36.199/Devtest/api/rest/categories/?oauth_consumer_key=87fb627751a50a2666e9c4501a4bc85f&oauth_token=f4cb9148deb67e05a3531e05b9edf923&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1501669923&oauth_nonce=VcTJZa&oauth_version=1.0&oauth_signature=xIrlLY0D1CGXkD49OduVqZhIVec=", "",
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        // display response
                        Log.d("Response", response.toString());
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("Error.Response", "hfjf");
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                final Map<String, String> headers = new HashMap<>();
                headers.put("Authorization", "OAuth oauth_consumer_key=\"87fb627751a50a2666e9c4501a4bc85f\",oauth_token=\"f4cb9148deb67e05a3531e05b9edf923\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1501750716\",oauth_nonce=\"Imh2HF\",oauth_version=\"1.0\",oauth_signature=\"b%2F5UoepFy6QL7oFDBMAh9ij0yGM%3D\"");
                return headers;
            }
        };
        getRequest.setRetryPolicy(new DefaultRetryPolicy(80000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_TIMEOUT_MS));
        requestQueue.add(getRequest);
        requestQueue.add(getRequest);
</code>


Complement and open set on topological spaces

Question:
Question:
  Let $Y=\left [ -1,1 \right ]$ be a subspace of $\mathbb{R}$ so the subspace property holds.
  Is $\left \{ x:\frac{1}{2}\leq \left | x \right |<1 \right \}$ an open set?

From the definition of complement,
On a metric space, a proper subset V of X is an open set wrt X if its complement $X\setminus V=\left \{ x \in X : x \notin V \right \}$
Here, $Y\setminus A=\left \{ y \in Y | y \notin A \right \}=\left ( \frac{-1}{2},\frac{1}{2} \right )\cup \left \{ -1 \right \}\cup \left \{ 1 \right \}$
Now, to speak about an open set we have to talk about open balls. I do not have good exposure to elementary real analysis so I'm not exactly sure how can we speak about open ball in this question.
Any help is appreciated.
Thanks in advance.
Edit:
Let $\bar{y}$ be an element in the complement $Y\setminus A=\left ( -1,\frac{-1}{2} \right ] \cup [\frac{1}{2},1 )$
The pertinent is this:
Is there any element $\bar{y} \in Y\setminus A$ st $d\left ( \bar{y},y \right )<\epsilon$
but $B_{\epsilon}\left ( \bar{y} \right )\nsubseteq Y\setminus A$?
Comment: You mean $Y$ is a *subset* rather than a *subspace*, don't you?
Comment: Changes made to OP
Comment: I don't understand the solution by the poster below. I've made an edit to the OP. Would someone assist me?
Answer: Well, you say you are operating in a metric space $(\mathbb R,d(x,y))$ and further you're given the subset $$\left \{ x:\frac{1}{2}\leq \left | x \right |<1 \right \}=(-1,-\frac 1 2]\cup[\frac1 2,1)=:X\subset Y\subset \mathbb R$$
A set is called an open set if for any point $x\in X$ there exists an $\varepsilon>0$ such that for any given point $y\in Y (\text{or }\mathbb R)$ with $d(x,y)<\varepsilon$, $y$ also belongs to $X$.
Now let's take for example $\displaystyle\frac 1 2\in X$ and any $\varepsilon>0$, then
$$
\left\{y:y\in Y, d(\frac 1 2,y)<\varepsilon\right\}\not\subset X
$$
and therefore your set $X$ cannot be an open set in $Y$ (or especially in $\mathbb R$ for this matter).
Comment: I don't understand. You want to show that every element in the complement satisfies the open set definition and the arrive at a conclusion. Why you taking an element in X?. All you're really doing is to show whether or not X is an open set
Comment: I show that there is a point in $X$, $\frac 12$ for which there exists no neighborhood $d(\frac 12,y)$ which is a subset of $X$ - this means, that $X$ is not open. Alternatively you could also show, that the complement is not closed, which I guess was your first idea to do?
Comment: What is that second bracket? Is it an open ball the set of elements in Y?
Comment: What second bracket do you mean?
Comment: The second expression
Comment: Yes, $\left\{y:y\in Y, d(\frac 1 2,y)<\varepsilon\right\}$ is an open ball contained in $Y$ and since there exists no $\varepsilon>0$ such that ball is contained in $X$, the set $X$ is not open.
Comment: Can you explain why there exists no $\epsilon$>0?
Comment: Sorry, your proof is not very intuitive nor understand. I believe this question should be straight forward. If I pick an element in the complement set with epsilon >0, if the ball containing the complement is not contained in the complement set, then the set is closed. Done.
Comment: *Why there exists no $\varepsilon>0$*: if the open ball $\left\{y:y\in Y, d(\frac 1 2,y)<\varepsilon\right\}$ would be contained in $X:=[\frac 12,1)$ this would mean that $(\frac12-\varepsilon,\frac12+\varepsilon)$ would be contained in $[\frac12,1)$, which is clearly not the case for any $\varepsilon>0$. As I said, you could also prove that the complement of $X$ is not closed, this is equivalent. So you basically have to show, that $(-1/2,1/2)$ is not closed (it is indeed open).
Comment: Your use of the open ball notation is really confusing. The open ball in your solution should be the set of all x in X such that the distance between two element in X is less than epsilon. And if I can prove this open ball is not a subset of Y=[-1,1], we are DONE.
Sorry, but your solution isn't very understandable.
Comment: @Mathematicing no, maybe this is the problem: The open ball $\left\{y:y\in Y, d(\frac 1 2,y)<\varepsilon\right\}$ around an $x\in X$ **needs** to be a subset of $Y$, and not of $X$. Here is what I've done in a nutshell: We want to show $X$ is not open in $Y$, for this we find an open ball around $\frac 12\in X$, this open ball is a subset of $Y$ but for no radius ($\varepsilon$) a subset (contained) in $X$, therefore $X$ is not open.
Comment: @Mathematicing In my experience the argument and set theoretic definitions that user190080 has used in the answer provided are very standard for a question of this variety. There are many alternate definitions for the topological properties being discussed here.
Answer: Y=[-1,1]  which is closed subset of reals...
Let X ={x|1/2<=|x|<1}
or we can say
X=(-1,-1/2] union [1/2,1)
It is neither open nor closed....
Complement of X in Y is the same as given in the question....i.e. (-1/2,1/2)union {-1} union{1}……
Now complement is not open as it is not the nbd. of -1 and 1.....or we can say -1 and 1 are not interior points of complement of X.....hence X cannot be closed....
X is not open as....-1/2 and 1/2 are not interior points of X.....
Hence X is neither open nor closed......
(For interior points there should exist at least one nbd. of radius epsilon which is contained in that set.....)


Custom audit log message send from Oracle DB version 12c to SIEM via syslog

Question: i need to send audit log from Oracle DB version 12c to my SIEM via syslog on IBM AIX. The problem is it not include the information i need. For exp:

<134>Mar  4 11:00:25 Message forwarded from abc: Oracle Audit[5374348]: LENGTH : '494' ACTION :[344] '9'),chartorowid('AAAAJCAABAAAA+nABn'),chartorowid('AAAAJCAABAAAA+nABv'),chartorowid('AAAAJCAABAAAisBAAP'),chartorowid('AAAAJCAABAAAisBAC9'),chartorowid('AAAAJCAABAAAisBADQ'),chartorowid('AAAAJCAABAAAisDACn'),chartorowid('AAAAJCAABAAAisEABG'),chartorowid('AAAAJCAABAAAisEABf'),chartorowid('AAAAJCAABAAAisEABn'),chartorowid('AAAAJCAABAAAisEACb'),' DATABASE USER:[3] 'SYS' PRIVILEGE :[4] 'NONE' CLIENT USER:[0] '' CLIENT TERMINAL:[7] 'UNKNOWN' STATUS:[1] '0' DBID:[10] '2346730987'

It not have the information about source IP which really needed to parsing log for security purpose. Is there possile for us to modify and include some information that we need into it ? Thank!
Answer: It is not possible to modify the information generated by Oracle's internal auditing. If you need to supplement the data going to your SIEM, then either

the SIEM tool needs to generate SQL queries to the audit trail
and any other necessary tables within the database, instead of
relying on syslog; or

you need to write a custom PL/SQL function to run the
appropriate queries and use UTL_FILE to write the output to an
external log file that the SIEM can read.

That said, it looks like your log sample is an audit of SYS actions, which may not even exist in the internal audit trail depending on your specific setup and version. If that is the case, what you see is all there is.
Comment: Thank you for reply, yes i has try to use jdbc and access to the table inside the DB and get the logs but sadly our DB team tell me that it impact to the DB availability. Can i ask you: The AUDIT and NOAUDIT command, can we use it on a group of user ? Because in DB there is a lot of user. If typing the AUDIT command for each user isn't the best idea. THanks
Comment: Depending on your version of Oracle and how auditing is implemented, you can audit certain things on all users, but Oracle doesn't really have "groups" like an operating system would. All "normal" auditing is generally written to database tables and would require SQL access, too. I believe I read that Oracle was deprecating the ability to write audit trails to OS files, and the data written to OS log files has always been limited compared to what's in the DB tables.