Unstable variable importance ranking

Question: I am new to R and and random regression forest. Right now I am working with a dataset of 60 input variables (dummy variables and continuous variables) and try to find the most important variables, which describe my dependent variable best. Therefore I am using the permutation-based OOB-MSE.
My problem is now, that each time I run the random forest, the ranking of the variables changes even when I just repeat the command with the same amount of ntree and mtry. First I was thinking that it had something to do with the randomized number of variables used in each tree, so I increased ntree. However, this also didn't help... Has anybody an idea what the problem might be and how I can get stable results for the variable importance measure?
Thanks!
Answer: There are a few things that can effect importance.
If the variables in your data set are correlated there can be a lot of instability in the variable importance as the model can use the variables somewhat interchangeably. Ideally it will spread the importance over all of the correlated variables but in practice it may require a lot of trees for this to happen. Reducing mTry or using extra/totally randomized trees is one way to combat this though this may hurt you're prediction accuracy or at least require re tuning...the most accurate model may not be the best for identifying feature importance.
Masking scores and other methods for explicitly dealing with correlated features have also been proposed.
You could also try doing dimensionality reduction before building you're models but this may destroy some of the non linear etc structure in the data depending on how you do it.
There are also biases in CART style feature selection towards "high cardinality" or sparse features. These features tend to be able to produce decreases in impurity that don't generalize well by random chance.
Further I'd only ever expect the importance ranking to be consistent for the top few features which get used across most of the bagged trees. The less useful features will get used less and have a lot more variability.
[2]: Also here: https://eranraviv.com/random-forest-importance-measures-are-not-important/
Answer: Random Forests are stochastic by nature, so it is normal that the results slightly change from run to run. However, the differences should be very small, especially for measures like Variable Importance (either Gini or mean decrease in accuracy) that are stabilized by being averaged over all trees.

First I was thinking that it had something to do with the randomized number of variables used in each tree, so I increased ntree

The ntree parameter does not control the size of the subset of variables that are randomly tried at each split. The mtry parameter does.
I suspect that there is an issue with your ntree and mtry parameters. If you try only a few variables at each split, and your ntree is not high enough, some variables won't be given a chance to play a role in each tree. This could lead to some instability in the variable importance measures. This is especially true if you have a low mtry, and a lot of important predictors. But there might be other reasons.
You should perform a grid search to tune ntree and mtry based on the OOB error rate first. Or, based on a decent number of trees (to ensure convergence), e.g., 500, you can use the tuneRF function to optimize mtry. Then, once you have your best model, you can use its output (e.g., variable importance measures).
Comment: Yes I always use tuneRF to optimize my model and I even tried to run it with, e.g. 2000 trees: bestmtry <- tuneRF(D[,2:NCOL(D)],D$y, ntreeTry=2000, stepFactor=1.5,improve=0.01, trace=TRUE, plot=TRUE, dobest=FALSE)
rf<-randomForest(y~.,data=D, ntree=2000, mtry=22, importance=T, proximity=T, replace=T, do.trace=T, keep.forest=T, na.action="na.omit"). Is there maybe an issue in my command? Furthermore, even the optimal model has a low R², so could be the reason for the changing of the ranking that my model just doesn't explain the dependent variable well?
Comment: Your commands seem fine to me. How much observations and predictors do you have? How do you get the importance measures? `importance`? `varImpPlot`? Especially, for the latter, see the sort, scale, and n.var parameters. If your covariates are really doing a poor job predicting the outcome, or if your data is very noisy, that could explain the variability. But I would expect at least one predictor or two to stay always on top. What is the amount of variation you observe from run to run? Is it totally random?
Comment: I just saw that you are using a mix of binary and continuous variables. The binary variables should maybe be entered as factors, to make sure that RF differentiate between them and the continuous ones
Comment: Great thank you for your help @user2835597. I ran the model with a subset of 10 input variables (and 340 observations) and you are right, the first two most important variables stay the same as well as the three last variables. Only the ones in between change. Then I should probably derive that the top variables are important, but I should not insist on the order of the variables, right? And regarding the measurement, I use both _importance_ and _varImpPlot_ and for both of them I always get the same results, so I guess that is fine...
Comment: OK so it seems that you have two covariates that are really contributing to the predictive accuracy, 3 that have close to zero importance, and some mildly important input variables in the middle. Do these results carry over when you use the full set of 60 predictors? What matters the most is the *relative* importance of the variables. If you observe a lot of variations among variables that are not important at all compared to the top ones, you don't care, it's probably just noise/randomness. If you observe variation for variables that do have some relative importance, something may be wrong.
Comment: Yes I think something must be wrong, because when I run the model with the 60 input variables, only the first 4 variables stay the same and afterwards the order changes slightly. The input variables are uncorrelated, so there shouldn't be an issue with that. And I even ran the model with ntree=8000 (my best mtry is 20), so that should not be a problem either...But my R² is still really low, so maybe this has an influence...Do you have any other idea?
Answer: I've been dealing with this same issue. Importance rankings change when I randomly stratify on the dependent variable. I looped through 10 to 500 trees random forest models. I get convergence but when I randomly select a training data set the importance rank changed dramatically. So this methodology seems to work well in identifying the top feature selection but it's not stable if you're trying to standardize a methodology for relative importance. Covariance can be measured better in other ways. Random Forests are really good at giving you suggestions. I wouldn't rely solely on a single random forest

Unstable variable importance ranking


Redirect port to openvpnas client

Question: I've been trying really hard to allow a distant pc to access to my web server hosted on a vpn client (openvpn access server).
I'd like to make this setup possible:

The VPS's os is debian 8 btw
I have ip forward enabled
echo 1 > /proc/sys/net/ipv4/ip_forward
I know I will have to use iptables but I've tried adding PREROUTE, POSTROUTE, SNAT and SNAT entries but it was unsuccessfull.
iptables -t nat -A  PREROUTING -d 184.108.40.206/32 -p tcp -dport 25565 -j DNAT –to-destination 172.27.240.2
iptables -t nat -A POSTROUTING -s 172.27.240.2/32 -p tcp -dport 25565 -j SNAT –to-source 18.104.22.168

I must be doing something wrong or lacking something...
Comment: Have you done a tcpdump on the VPS when a 'web client' connects to your 'web server'?  Do you see the incoming packets?  Do you see it being forwared out the VPN link with the correct addresses?  Do you see the packet counters increase in the netfilter table `iptables -nvL -t nat`?
Comment: I've used wireshark on my vps and I've seen multiple TCP incoming packets on the port but nothing going back nor forwarded unfortunately...
I makes me think the port is not open but isn't it already open?
Comment: Oh, one other thing, are you testing this setup from a client outside of the network where the 'web server' is hosted?  Testing it from a client on the same network as the 'web server' would possibly have some weird results.  Also, **cough**, Bungeecord.
Comment: Yep. Web server hosted on the 'school network', test client on 4G (android)
Comment: (also, I don't see my port at all with the `netstat -an` command :/)
Answer: Okay, I got it!
I just had to enable a DMZ for the user in openvpn-as.
You just need the public interface's IP (for me it's because it's the public interface) along with the port and protocol.
184.108.40.206:TCP/25565 did the trick.
(for anyone who asks details : you can find it in https://yourserver:943/admin. Then in User Management->User Permissions->username->show.
Just click "yes, enable DMZ" and enter the parameters.)

Redirect port to openvpnas client


Lagrange multiplier derivative condition

Question: For the Lagrangian $\mathcal{L}(\mathbf{x}, \lambda) = f(\mathbf{x}) + \lambda g(\mathbf{x})$, I read that $\partial\mathcal{L}/\partial\lambda$ must equal $0$. Could someone please explain why?
Answer: The equation $\frac{\partial \mathcal L (x,\lambda)}{\partial \lambda} =0 $ just says that $g(x) = 0$.  This must be satisfied, of course, if $x$ is a minimizer of $f$ subject to the constraint that $g$ is $0$.
Comment: Gotcha. So that's why, in order to find the solution with a given constraint, you take the derivative with respect to all the variables AND with respect to $\lambda$ (because the latter is just another way to express that constraint must equal 0). Thanks!


Does using a covariance matrix of scaled and centered variables compare with using a correlation matrix?

Question: I have some data with features which have different units of measurements. Here, by data, I'm trying to say that the row represents the observations and column the features. There are correlations between the features as well. Hence, principal component analysis would be the best to explain the variance in my data and also identify the variance contribution of each feature in the total variance explained by a principal component.
I read somewhere that principal components analysis (PCA) can be performed on the data by computing both covariance and correlation matrices. If I scale and center my data (Z-scores) and compute covariance and compare it with a correlation matrix, will the results of PCA be different? As both correlation matrix and scale/centered covariances represents standardization of the data, I assume the results (variance contributed by features in a principal component) should be same? Am I wrong in assuming this? I'm a novice and am trying to understand principal component analysis.
Comment: Possible duplicate of [Is there an intuitive interpretation of $A^TA$ for a data matrix $A$?](https://stats.stackexchange.com/questions/22501/is-there-an-intuitive-interpretation-of-ata-for-a-data-matrix-a)
Answer: you will find a nice summary given by user @ttnphns here: https://stats.stackexchange.com/q/22520.
In particular:

If you center columns (variables) of $\mathbf{A}$, then $\mathbf{A′A}$ is the scatter (or co-scatter, if to be rigorous) matrix and $\mathbf{A′A}/(n−1)$ is the covariance matrix.
If you z-standardize columns of a matrix $\mathbf{A}$ (subtract the column mean and divide by the standard deviation), then $\mathbf{AA′}/(n−1)$ is the Pearson correlation matrix: correlation is covariance for standardized variables.

In general you should always center your data when performing PCA. As explained here, not centering your data can give misleading results.
Answer: ** I have updated this answer as upon reflection i was focused on the right eigenvectors and there is a difference in scaling, so my original answer was not 100% accurate **

Does using a covariance matrix of scaled and centered variables
  compare with using a correlation matrix?

Yes

If I scale and center my data (Z-scores) and compute covariance and
  compare it with a correlation matrix, will the results of PCA be
  different?

Depends on what you consider to be meaningful. There will be a scaling difference for the eigenvalues, but the right eigenvectors will be unchanged while the left eigenvectors are just a rescaled version. If you were to use SVD to calculate your PCA but stopped before combining the left eigenvector and the singular values you would find that the U matrix is identical whether using z score transformed or correlation matrix, it is the singular values that will be uniformly transformed between the two.
If you scale (z-score) your data then your covariance matrix is a correlation matrix. A correlation matrix is a covariance matrix scaled against the diagonal (variance). Scaling to unit variance is scaling the original data to the standard deviation. Thus whether you scale to before or after the covariance matrix, the end result is still the same pattern of variation.
Some Matlab code I wrote to test this:
<code>%% generate a matrix of random variables with some covariance
A = rand(100,1);
A(:,2) = A(:,1) - rand(100,1);
A(:,3) = 0.1*A(:,1) + 0.4*A(:,2) + rand(100,1);

%%calculate z-score matrix
A_mc = bsxfun(@minus,A,mean(A,1));
A_z = bsxfun(@rdivide,A_mc,std(A_mc,[],1));

%%validate matrix properties
if any(abs(mean(A_mc))>eps) %check if mean is within machine precision of 0
    error('Oops, matrix did not mean centre correctly')
elseif any(std(A_z)<1-eps | std(A_z)>1+eps)%check if sd is within machine precision of 1
    error('Oops, matrix did not scale to unit variance correctly')
end

%% PCA is based on covariance matrix, therefore it is sufficicent to compare these
A_zIP = A_z'*A_z; %covariance matrix
A_corr = corr(A); %correlation matrix

zIP_Corr = A_zIP./A_corr
zIP_CorrSD = std(zIP_Corr(:))
</code>
The output:
<code>zIP_Corr =

   99.0000   99.0000   99.0000
   99.0000   99.0000   99.0000
   99.0000   99.0000   99.0000

zIP_CorrSD =

1.7405e-14
</code>
You can see the scaling is pretty close to uniform, with the difference likely due to the cumulative effect of the rounding errors between the two processes. So there is no practically significant change in the pattern of variation, therefore the right eigenvectors will be the same.


Can't install experimental modules

Question: I installed Drupal 8.1.2, but I can't install modules of the category "core (experimental)". No problem with other modules or themes for example. I get no logs and no error message. Hitting the install button just redirects me to the extend page.
I have been able to install Migrate by installing Migrate Plus, which requires Migrate, but this does not solve the issue, in particular not for the other modules in "core (experimental)". Is there anything I have to do to be able to install experimental modules?
Comment: No problems when [testing over here](https://simplytest.me/project/drupal), are you using a fresh drupal install? if not, perhaps a contrib module that you downloaded may be causing the problem.
Comment: It is a fresh install
Comment: try doing it again [over here](https://simplytest.me/project/drupal)
Comment: I don't have problems to install them too, as @NoSssweat. I would follow his suggestion to try on simplytest.me.
Comment: Just tried the sandbox and there it works. Of course... :-/ I think I will go for your advice and try a new installation. Maybe something went wrong.
Comment: Still the same problem... Hoster can't help neither because there are no error messages or log entries.
Answer: There's a core issue for failure to install experimental modules (or, more precisely, modules with parentheses in the group name with Suhosin): https://www.drupal.org/node/2665152

Can't install experimental modules


Allow users to change their own hosts file via GPO?

Question: We have a bunch of techs on Windows 10 Pro machines that have to change their hosts file every now and again to be able to test things for customers.
C:\Windows\System32\drivers\etc\hosts

All these machines are part of an Active Directory domain(Running on Windows Server 2012R2) and the current 'default' settings don't allow them change this file by themselves, which is by design as far as I'm concerned, however it's too much work to do it for them.
So my question is: Is it possible to allow users in an Operational Unit to change their own hosts file via Group Policy Object for Windows 10? And how do I accomplish this?
Thanks in advance.
Answer: You can use Group Policy to add a modify ACL for a group that contains these users to the ...\system32\drivers\etc\hosts file. The GPO Setting for ACLs is: Computer/Policies/Windows Settings/Security Settings/File System. Because this setting lies within the computer configuration branch, it needs to be linked to the OU that contains the computer accounts that these users login to. Do not link it to the OU that contains their user accounts.


Close jquery modal

Question: I'm importing Jquery Modal from these two links (js and css)

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />

I've added the following html code inside the body
<button onclick="load();" class="btn btn-primary">

  Filtrar
</button>

  Cargando

and the following is in a js file
function load() {
    openLoadingModal();
    doSomething();
    closeModal();
}

function openLoadingModal(e) {
    $("#loadingModal").modal("show");
    var count = 0;
    var points = "";
    var intervalId = window.setInterval(function(){
        count++;
        $("#loadingModal").text("Cargando" + ".".repeat(count % 3 + 1));

    }, 1000);
    return intervalId;
}

With this, the modal opens as I expect. The thing is that I want to close the modal when this ends. But the solutions I've found didn't work. I tried the following:
    $("#loadingModal").modal("close");
    $("#loadingModal").modal().close();
    $("#loadingModal").modal().close;
    $("#loadingModal").modal("toggle");
    $("#loadingModal").modal().toggle();

None of this closes the modal as it should (maybe hides the modal, but not all of it, since there is a black screen)
I think this shouldn't be this hard, but every link I get in tells me to do one of this
Thanks
Comment: Does this answer your question? [Close Bootstrap Modal](https://stackoverflow.com/questions/16493280/close-bootstrap-modal)
Answer: If there is only one modal on the page, use this:
$.modal.close();

Comment: What could I do if I had more than just one? Thanks for the answer

Close jquery modal


Equivalence of a Vector Norm

Question: I have this for my homework and i need help with this question:
For a 2D vector, is norm2 > norm1 possible?
Characterize all 2D vectors for which the norm2 is equal to the norm1. Explain
graphically.
Comment: What is "norm2" and "norm1"? Do you mean $\ell^2$ norm and $\ell^1$ norm?
Comment: Welcome to MSE. It will be more likely that you will get an answer if you show us that you made some effort.
Answer: For $(x,y) \in \mathbb R^2$ we have
$$||(x,y)||_1 =|x|+|y| \ge \sqrt{x^2+y^2}=||(x,y)||_2,$$
since
$(|x|+|y|)^2=x^2+2|x||y|+y^2 \ge x^2+y^2$.
We have the equality
$$||(x,y)||_1 =|x|+|y| = \sqrt{x^2+y^2}=||(x,y)||_2$$
$ \iff$
$(|x|+|y|)^2=x^2+2|x||y|+y^2 = x^2+y^2  \iff xy=0$.

Equivalence of a Vector Norm


What does this category theoretical notation mean?

Question: I've come across this notation, which I've never seen before:

This is from an article A categorical semantics for causal structure, but I've seen it a few times before; where does this come from (where can I familiarise myself with it)?
Comment: This is an answer to the question, not just a comment. Per site policy, comments should only be used to clarify, not answer the question. See **[How do comments work](https://meta.stackexchange.com/q/19756)** for more information. Therefore I suggest that you post your answer as an answer. This brings extra visibility to the answer und puts the question off the unanswered list. Also notice that comments are not indexed by the full text search, don't have any revision history, can only be edited for 5 minutes and allow only limited markup.
Comment: Search for "graphical calculus" or "string diagrams" for monoidal categories. There are plenty of textbooks e.g. https://link.springer.com/book/10.1007/978-3-319-49834-8 by Turaev and Virelizier. In particular Chapter 2 for monoidal categories and 3.2 for braided categories.
Comment: Thank you, it's now posted as an answer.
Comment: Awesome! :) $\phantom{:-)}$
Answer: (As suggested, I'm posting my comment as an answer)
This notation is called "graphical calculus" or "string diagrams" for monoidal categories.
There are plenty of textbooks and depending on your background and motivation you might choose your favorite. Here is one example (I personally used most): Turaev, Virelizier. In particular Chapter 2 for monoidal categories and 3.2 for braided categories.
Note: Depending on the reference, there might be different conventions. For example if the diagram is read bottom to top or top to bottom or the orientation of arrows etc. Feel free to adopt your favorite one.


Creating a directory on FTP server

Question: I'm trying to create a directory on my FTP server.  Google search shows me this question here.  So I followed what Jon wrote as his answer, and have:
    private static void MakeDirectory(string directory)
    {
        Log("Making directory...");

        var request = (FtpWebRequest)WebRequest.Create(directory);

        request.Method = WebRequestMethods.Ftp.MakeDirectory;
        request.Credentials = new NetworkCredential("user", "pass");

        try
        {
            using (var resp = (FtpWebResponse)request.GetResponse()) // Exception occurs here
            {
                Log(resp.StatusCode.ToString());
            }
        }
        catch (WebException ex)
        {
            Log(ex.Message);
        }
    }

I have a method to verify that the directory exists:
    public bool DirectoryExists(string directory)
    {
        bool directoryExists;

        var request = (FtpWebRequest)WebRequest.Create(directory);
        request.Method = WebRequestMethods.Ftp.ListDirectory;
        request.Credentials = new NetworkCredential("user", "pass");

        try
        {
            using (request.GetResponse())
            {
                directoryExists = true;
            }
        }
        catch (WebException)
        {
            directoryExists = false;
        }
        return directoryExists;
    }

The check actually works. If it exists, it returns true, if not, it returns false. However, whenever I go to run my MakeDirectory(), I get an exception on the line stated above:
The remote server returned an error: (550) File unavailable (e.g., file not found, no access).

Am I missing something?  Why would the GetResponse() work for my directory check, but not for my MakeDirectory()?
Comment: perhaps your login does not have the required permissions
Comment: @Dan-o: I thought about that, looked into it, but the permissions are there.
Comment: Are you sure that the path leading to the file is accessible and existing? There was a similar discussion and solution in StackOverflow: http://stackoverflow.com/questions/9118286/ftp-makedirectory-nested-structure
Comment: Yes, I've verified the path to my server.  I'm essentially trying to create a Folder in my base directory(`ftp://my-site.com`), so my directory looks like `ftp://my-site.com/newFolder`.
Answer: As it turns out, this was an issue on the part of the company who runs our web servers.  They did some FTP update last night that affected not only myself, but all their clients.  They have since fixed the problem.  It just took them a day to admit that it was their fault.

Creating a directory on FTP server


Como criar um site com o pc de servidor usando apenas Python?

Question: explicação resumida
pense no site como um app. eu preciso criar um app no celular que acesse funções no pc através de comandos. no que tange ao tratamento dos comandos e a chamada de funções eu até entendo como fazer, o problema é que eu não consigo trabalhar a transferência de dados web para pc. infelizmente minha área não é web, por isso agradeceria muito a ajuda. '''independente de usar ou não python, minha única real restrição é não usar javascript e html... css, xhtml, django, ou outras linguagens são permitidas'''
ps: não precisar ser online, um servidor local basta
explicação longa
eu tenho um amigo que é o famoso fanboy de javascript, e olha que eu nem sabia que isso existia, ele basicamente propõe que js deve ser usado em tudo, inclusive no lugar das linguagens de baixo nível. eu entendo o valor de js, também como os das outras linguagens, e, como tal, não poderia simplesmente me abster de ir contra essa tese. a escolha de python não foi arbitrária, é a minha linguagem mãe e a que eu mais domino, assim como o sistema que me propus a fazer pois ele será realmente útil pra mim.
assim, eu decidi desenvolver uma ferramenta dentro do campo predominante de js, a web, que facilitasse minha vida como desenvolvedor python.
Comment: Sua pergunta é demasiadamente ampla e há muitos conceitos por trás que você precisará aprender para fazer o que deseja. Você precisará configurar um servidor HTTP em sua máquina local, precisará configurar toda sua rede para permitir acessos externos à ela, configurar para seu servidor se comunicar com a interface do Python para, então, executar o código que necessita. Veja essa pergunta: [Como configurar apache2 para python 3.5.2](https://pt.stackoverflow.com/q/177499/5878) para ter uma noção inicial. E estude HTTP, é muito importante conhecer o protocolo que está utilizando.
Answer: PAra responder a pequenas chamadas via HTTP com funções arbitrárias de Python, o mais simples é usar um microframework como o Flask - de uma olhada no hello world do Flask mesmo - http://flask.pocoo.org/docs/1.0/tutorial/
Django é uma boa, mas ele já vai criar um projeto em que é mais chato de configurar urls de view, e assume que você vai usar um banco de dados com ORM, que pode nem ser o seu caso.


I am trying to generate two random 3 digit prime numbers and creating a function using RSA methods on VB.NET

Question: I am trying to generate two random 3 digit prime numbers and creating a function using RSA methods in VB.NET.
p, q are randomly generated 3 digit prime numbers
Dim p, q As Integer
p = TextBox9.Text
q = TextBox10.Text

'If  CInt(Math.Floor((999 - 100 + 1) * Rnd())) + 100 Mod Prime

this is all I have thus far, I am struggling to fully implement it.

Let n = pq. Calculate n and write it down.
Calculate ϕ(n) and write it down.
iv. Pick an integer e ≥ 2 such that gcd
e, ϕ(n) = 1. This will be used for encrypting messages.
v. The pair (n, e) is your public key. Make this publicly available to everyone, and anyone can send encrypted messages to you
Comment: What are you actually trying to accomplish? Generating a random prime number or generating an encrypted string?
Comment: Can you clarify exactly what part of this you're struggling with?  Does TextBox9 & 10 already have the random primes?  Where does the Prime variable come from?  Perhaps have another read over the How to ask top in the help, particularly the homework section I'm guessing
Comment: I have tried to edit your question into an easier-to-read format, but it seems that there is information missing. Please [edit] your question so that someone who cannot see the question you've been given has enough material to write an answer for you.
Comment: I am trying to generate two 3 digit numbers that are also prime.
Answer:
I am trying to generate two 3 digit numbers that are also prime

Take a look at the following code:
Public Function GenerateTwoPrimes() As Integer()
    Dim r = From i In Enumerable.Range(100, 999).AsParallel() Where Enumerable.Range(1, CInt(Math.Sqrt(i))).All(Function(j) j = 1 OrElse i Mod j <> 0) Select i
    Dim lst As List(Of Integer) = r.ToList()
    Dim ordered = Enumerable.Range(0, lst.Count - 1)
    Dim rng = New Random()
    Dim arr As Integer() = ordered.OrderBy(Function(c) rng.Next()).ToArray()
    Return New Integer() {lst(arr(0)), lst(arr(1))}
End Function

You will get two random 3 digit prime numbers.
For example:


Angular: input binding not updating

Question: I am currently having issues trying to bind a list to an input object in Angular. I expect the interpolated value in the child to update every time I add to the list but instead, the original loaded values remained unchanged in the view. Even the OnChange doesn't trigger, I have been wrestling with this for hours any assistance would be appreciated.
Parent

@Component({
   selector: 'main-app',
   templateUrl: './main-app.component.html',
   styleUrls: ['./main-app.component.sass']
})
export class MainAppComponent implements OnInit {
  list_values = [ 10, 20, 30 ]

   add_to_list(){
      this.list_values.push(12)
      console.log( this.list_values )
   }
}

Child

{{in_list}}

@Component({
  selector: 'main-task-list',
  templateUrl: './main-task-list.component.html',
  styleUrls: ['./main-task-list.component.sass']
})
export class MainTaskListComponent implements OnInit {
  @Input( 'in-list') in_list: number[] | null = null

  ngOnChanges( changes: SimpleChanges ){
     console.log('re render')
  }
}

Answer: The reference of you item doesn't change when you push value in it. It need to change. try to create a new item and the ngOnChange will trigger again:
this.list_values = [...this.list_values,12]

instead of
this.list_values.push(12)

Comment: Maybe is not my case but this solution is not working when I'm trying to change the value of the list of my mat-table-cell

Angular: input binding not updating


Component of CustomModule ignores toplevel declaration in AppModule

Question: After a long search on this pages, I am still lost.
I have an AppModule and an ModalModule. AppModule is importing ModalModule
AppModule declares LoaderComponent with this decorator attributes:
selector: 'my-loader', template: '
...
<ng-content></ng-content>'

ModalModule declares ModalComponent.
Inside the template of ModalComponent I want to use LoaderComponent:
<my-loader>
Loading...

Just information text.
</my-loader>

And this does not work!
'my-loader' is not a known element:
1. If 'my-loader' is an Angular component, then verify that it is part of this module.
2. If 'my-loader' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

If I add CUSTOM_ELEMENTS_SCHEMA to ModalModule, it just ignores the element and the DOM looks like this:
<my-loader>

Loading...

Just information text.

</my-loader>

But I want it to be rendered by angular and look like this:
<my-loader>

...

Loading...

Just information text.

</my-loader>

Does somebody have an idea?
Comment: Right after my post, I found this and will try it: https://stackoverflow.com/questions/39906949/angular2-how-to-clean-up-the-appmodule/39907757#39907757
Answer: Cleaning up and using a SharedComponent helped!
Angular2 How to clean up the AppModule
Only difference, I had to do, is adding CommonModule and FormsModule to the imports of SharedModule!


Minimize Type II errors in black-box testing

Question: Okay so I have a function in the shape of a black box that I'd like to test. It's characteristics are:

It gives either 0, 1 or -1 as output.
I can query it easily, producing tens of thousands of samples in short time.
I have no other prior information. I don't know the mean nor the variance.

My hypothesis is this: I want to test that it is "unbiased", in the sense that its mean is 0.
But I want to bias my testing in this way:

False positives (i.e. Type II errors) must be minimized.

For this p-value testing (at least as I understand it) won't work, since it tries to minimize false negatives. My project needs to reject my implementation of this function every time that it truly has a bias: if it's biased I should reject it, but if it isn't then it's okay to reject it with a low-ish probability.
What should I be doing? The textbook I'm using (Ang & Tang for Engineering) explicitly skips over Type II error mitigation, so I have no idea on how to proceed.

Edit: more details on the problem, since it seems I can't quite explain it myself.
My function receives a point in N dimensions, and generates the gradients of a Noise function that belongs to the family of Perlin Noise. These gradients are unitary, and are built in such a way that the values of every coordinate are either α or -α (at "random"), and then one of them is chosen at "random" as well and made 0. α depends on the number of dimensions, but suffice to say that it's built to make the gradient unitary.
By "random" I mean a deterministic process that for any given point, always produces the same results. This is an important property of the Noise functions. But it also must seem random, and that's where things get complicated. The process is as follows:

Point gets feed into a hash function.
Hash of the point is used as the seed for a pseudorandom generator.
Generator is used to produce all "random" actions.

I can, and am, using now a cryptographic hash function and a cryptographic pseudorandom generator. Those should have no bias I could measure (at least in polynomial time), and therefore I'm more or less certain that my function is indeed unbiased if I give it random input (for which I'm also using a cryptographic pseudorandom generator). But for sanity, and in case I then decide to try faster hashers or generators, I want a test that can check if the unbiasedness holds (with a certain probability of failure).
To finalize: I'm more interested in rejecting biased functions than in accepting unbiased ones. That's what I don't know how to do.
Answer: You will need to accept some probability of accepting a biased box. (Otherwise, you will need to keep querying ad infinitum to be certain, because, who knows, the bias might only manifest with at least $10^{12}$ samples.)
And then you are squarely in the realm of statistical-significance testing. Indeed, you might want to look into power and sample-size calculations, where you prespecify an $\alpha$ level (the probability of rejecting an unbiased box, could be the classical 0.05), a $\beta$ level for power (one minus the probability of not rejecting a biased box - in your situation, $\beta$ should probably be rather high) and an effect size that gives "practical bias" (is a bias of $10^{-2}$ relevant? $10^{-6}$? $10^{-28}$?). A power calculator, or a simple simulation, will then give you the required sample size for your experiment.
Comment: > You will need to accept some probability of accepting a biased box

Of course! I know that I need infinite samples otherwise. I'm fine with, idk, 99% chance of rejecting a biased box.
Comment: Very good. Then the approach I outline should work. (And I don't understand why you write that p-value testing wouldn't work.)
Comment: Sorry, tried to edit my comment but got cut off by the timer! Here's what I was trying to write:
(Regarding the rest of your answer:) I'm sorry, I really don't understand most of that. Most importantly:
- Where can I learn about power?
- What tools allow me to calculate the effect size? And what is an effect in this context?
Yes, I'm a noob on statistics. Sorry about that, but uni's course was pretty lame on statistical inference and I'm picking it back up after some years.
Comment: (I also realize that comment formatting doesn't allow for line breaks. Ouch, my last comment is kind of a pain to read)
Comment: No problem. [Wikipedia](https://en.wikipedia.org/wiki/Power_(statistics)) is actually pretty good at power analysis. Essentially, you have four factors playing together: (1) your sample size $n$, (2) an effect size you are interested in which I called "practical bias", (3) the probability of rejecting an unbiased box which you will accept, which is the $\alpha$ level, and (4) the probability of detecting a "practically biased" box, which is $\beta$. Power analysis analyses the interplay between these four (always in the context of a specified experimental setup and analysis). ...
Comment: There, I've now explained in more details what my problem is, since it seems I can't convey it in statistical terms. Thank you, and sorry for the inconvenience. **Edit**: oh, just read your comment. I think I'm getting it now, will come back after reading some more. Thanks!
Comment: ... For instance, if you want to detect a smaller effect size ("practical bias") with given $\alpha$ and $\beta$, then $n$ will need to go up. If you want to be more stringent with your $\alpha$ level with given effect size and $\beta$, then your $n$ will need to go up. Power analysis is usually used to calculate the sample size before running an experiment, based on subjectively set $\alpha$ and $\beta$ and "relevant" effect sizes. There are power calculators for simple experiments out there, but in your case, I'd recommend writing your own in a few lines of R.
Comment: The key is that you need to *pre-specify* your experimental setup and your analysis plan including the model. (This is often not done cleanly in clinical study sample size determination.) I am not really sure whether your question really is about how to analyse your box. If so, perhaps you could clarify.
Answer: Let me try to rephrase Stephan's answer: You will need to accept a box with some bias as unbiased, otherwise the procedure that you want does not exist.
Here is why: as you sample more and more points from your box, you narrow the range where it's mean is likely to be. Say, for illustration, after 100 points you know that the mean is $0 \pm 0.1$, and after 10000 points you know that the mean is $0 \pm 0.01$. The more you draw, the narrower the range, but it is always a range. At no point you will be able to say "yep, that's a zero mean box".
The solution is to call a box with mean in some interval, for example $(-0.01, 0.01)$, unbiased, and otherwise biased. Then you can do statistics with power, sample size, etc.
Comment: Mm, that seems very reasonable. I guess I didn't try to formalize the **alternative hypothesis** as something that wasn't "mean is not 0", which would need infinite samples. I think I can come up with a reasonable "unbiased range" for the number of dimensions I'm working on, and based on that build the inference scheme.


Conjugacy classes of a group of order $8k$

Question: Let G be a group of order $8k$, show that there are at least 5 different conjugacy classes.
Hi everyone, I have this problem I think I had a solution involving stabilizers, however I feel there must be a really easy and quick solution. Any ideas on what that might be?
Edit: To give more motivation into the question. It was suggested to me by a college, I believe he found it a book by J.M. Gamboa Mutuberría(he has a bunch, I do not know which).
My current line of thought consist of using the fact that considering the action
$$
\rho:G\times G\rightarrow G, \rho(x,y)=yxy^{-1}
$$
and that $x\in G$ is a fixed point iff $x$ is in the centralizer of $G$ we have $$
card(G)=card(Centr(G))+\sum_{s=1}^{n}\theta_s
$$, where $\theta_1\ldots\theta_n$ are the distinct orbits, now orbits have at least size 2 and divide 8k. But I said before, I think this is getting to complicated and my college suggested the problem must have a simpler suggestion
Comment: The number of finite groups with a given number of conjugacy classes is bounded. (This is due to Landau.) So you can always classify all the groups with at most four conjugacy classes, it's not that hard. Or you can do whatever part of the partial classification is needed to see that the order cannot be divisible by 8.
Comment: @verret Bounded by how much?
Comment: @JyrkiLahtonen Where did you get that equation?
Answer: A simple answer can be based on the fact that a $2$-group has a non-trivial center (the same applies to any $p$-group). The assumption about the order $n=8k$ of the group $G$ implies by basic Sylow theory that there is a subgroup $P\le G$ of order $8$. Let $z\neq1_G$ be an element of $Z(P)$. It follows that the centralizer of $z$ has order
$8\ell$, $\ell\ge1$. Therefore the conjugacy class of $z$ has $|[z]|=n/(8\ell)\le n/8$
elements.
Assume that there are at most four conjugacy classes — two in addition to $[1]$ and $[z]$. They have sizes $n/a$ and $n/b$ for some divisors $a,b>1$ of $n$. The conjugacy classes form a partition of $G$, so
$$
1+\frac n{8\ell}+\frac n a+\frac n b=n.\qquad(*)
$$
If $a=b=2$ then the left hand side of $(*)$ is too large. If $a,b\ge3$, then the l.h.s. is too small ($1+n/8<n/3$ whenever $n\ge8$). Hence we can assume w.l.o.g. that $a=2$ and $b>2$. Also, $1+n/8\le n/4$ leading to $b\le 4$.

If $b=4$, then $(*)$ implies that $\ell=1$ and $n=8$. But, a non-abelian group of order eight is either the quaternion group $Q_8$ or the dihedral group $D_4$. Neither has a conjugacy class of size four, so this case can be ruled out.
If $b=3$, then $(*)$ implies that $\ell=1$ and $n=24$. A conjugacy class of size $n/3$ necessarily consists of elements of order three, each generating its own centralizer. Thus $G$ has four Sylow $3$-subgroups. The conjugation action on the set of those Sylow subgroups gives us a homomorphism $f:G\to S_4$. An element $x\in G$ of order three can normalize only one Sylow $3$-subgroup, namely the one it generates, so $f(x)$ is a 3-cycle. It follows that all the 3-cycles of $S_4$ are in the image of $f$, and those are known to generate $A_4$. Therefore $\operatorname{ker} f$
has order one or two. The alternative of a kernel of size two is impossible. After all, the kernel is normal, and consists of full conjugacy classes. Hence $f$ is an isomorphism, and $G\cong S_4$. But $S_4$ has five conjugacy classes. A contradiction.
Answer: Let $G$ be a finite group with $|G| \equiv 0$ mod $8$ and assume that the number of conjugacy classes is at most $4$. This is equivalent to the statement that the number of irreducible complex characters of $G$ is at most $4$. Since $|G|$ is the sum of the squares of its irreducible character degrees we get $|G|=1+a^2+b^2+c^2$, where the $1$ comes from the principal character and $a,b,c$ are non-negative integers. Since squares mod $8$ equal $\bar{0}$,$\bar{1}$ or $\bar{4}$, the equation $\bar{0}=\bar{1}+\bar{a}^2+\bar{b}^2+\bar{c}^2$ mod $8$ has no solutions, a contradiction.
Note (1) One can show that if $|G|$ is odd and $k(G)$ denotes the number of conjugacy classes, then $|G| \equiv k(G)$ mod $16$.
(2) In general, for a non-abelian $G$,  $k(G) \leq \frac{5}{8}|G|$. Hence if we have equality here, then $|G|$ must be a multiple of $8$. Example: $G=Q_8$, the quaternion group of order $8$.
Comment: Yes correct, the 5/8 theorem is for non-abelian groups of course. Thanks for noting! Will correct. Btw, I gave your direct solution a +1.


Django dont set CSRF token on AJAX GET from angularJS

Question: I am writing application with AngularJS on frontend and Django as REST service on backend. I'm trying to send some JSON data using POST request, but facing with csrf-token issue (CSRF token missing or incorrect). As far as i know, previously i should make a GET request on Django to obtain this token. So i have wrote simple view:
def get_csrf_token(request):
    return HttpResponse(json.dumps({'success': True}))

I have added httpProvider defaults, and on start of angular application making GET request on view:
angular.module('app')
    .config(function($httpProvider){
        $httpProvider.defaults.xsrfCookieName = 'csrftoken';
        $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    })
    .run(function($http){
        $http.get("http://127.0.0.1:8888/get_csrf_token/")
    })

but this view dont set a CSRF token, and i still cannot do POST request.
Answer: If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token cookie. This is common in cases where forms are dynamically added to the page. To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie().
Comment: Thanks a lot! Decorator helped me


What is wrong with this schema definition and db query?

Question: Hello and thank you for your time to help me in this weird case.
I have a schema API function that returns few database table information, and everything seem to work fine... except the most simple table.
$schema['quotes_key'] = array(
  'description' => 'Auth keys for quotes',
  'fields' => array(
      'qid' => array(
        'description' => 'The {quotes} this key belongs to.',
        'type' => 'int',
        'not null' => TRUE,
      ),
      'key' => array(
        'description' => 'Key of the qid to be accessed anonymously.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
      ),
    ),
    'primary key' => array('qid'),
    'indexes' => array(
      'qid'        => array('qid'),
    ),
  );

Then, I use drupal_write_record to write a new object to the database.
$key = new stdClass();
$key->qid = 789;
$key->key = md5(uniqid());
drupal_write_record('quotes_key', $key);

Whenever I run this code, I'm getting a mysql error:
user warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key) VALUES (789, '02ab38a849e02744f532cdf3137df146')' at line 1 query: INSERT INTO quotes_key (qid, key) VALUES (1, '02ab38a849e02744f532cdf3137df146') in .../includes/common.inc on line 3576.

Can anyone kindly help me to figure out the problem ? I tried db_query to do the same database INSERT but getting same error. So I guess the problem is with my schema.
the qid is stored in a {quote} table.
I tried reinstalling schema by drupal_uninstall_schema() and drupal_install_schema()
Thank you.
Answer: I believe key is a reserved word. I'd stray away from using the key instead of trying to get MySQL to accept it. But here's some examples on how to get around it (which might not be possible via Drupal's db api).
https://stackoverflow.com/questions/2889871/how-do-i-escape-reserved-words-used-as-column-names-mysql-create-table
Comment: Thank you very much Johnathan. that was the problem.. and MySQL docs confirms "key" is reserved. Thanks a lot!
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Comment: See also [List of SQL reserved words](http://drupal.org/node/141051).


Random variable and its support

Question: Q: Cells live for a random but finite amount of time and when they die they leave behind k offspring with probability pk for k=0,1,2. Initially there is one cancer cell in a petri dish. After one hour a scientist counts the number of cancer cells in the petri dish. What is the random variable and its support for this experiment?
My attempt so far is :
Denote by X the random variable equal to the number of cells in the petri dish
Supp(X) = ?
I am not quite sure if it is right but my thoughts leaded me to say {0,1,2}
Any help on this will be highly appreciated
Thanks alot
Comment: Saying that the support is $\{0,1,2\}$ assumes that only one cell death occurs during the course of the hour; an assumption not warranted by the question as asked.
Answer: The random variable being measured in this experiment is the total number of cells in the petri dish after an hour.
We are not given any information about how quickly these cells divide, so given only this information we have no upper limit for how many cells there might be in the dish after an hour, and the cells can divide in such a way that there are any number of them after a given time.
So, the support of this random variable is the non-negative integers, since there can be any number (from $0$ and up) of cells after an hour.

Random variable and its support


Testing for variable independence with count data and assumption violations

Question: I used a survey to collect information about injuries suffered while practicing and competing in gymnastics. I have count data on the injuries that looks something like this:
<code>           Floor   Vault   Rings ...
Head         33      45      7
Neck         43      19      17
Shoulder     21      39      25
...         ...     ...     ...
Toes         16      9       3
</code>
I wanted to see if there was a relationship between the body part injured and the equipment being used. I thought that using a chi square test of independence would work but I've hit a snag, I think.
When the participants filled out the survey, they were able to check multiple responses. For example, if someone was injured while performing the vault, they could have injured both their head and neck and both would show up in the injury count. Thus one injury contributed to two cells.
I've considered running separate analyses for each body part but I don't think that exactly answers my question. Is there another way to tackle this problem or a different statistical test that might work?
Answer: There are at least a couple options with "check all that apply" data.
First, you could analyze each body part as a separate dependent (in this case) possibly logistic regression (injured that part vs. did not) or possibly some form of count regression (number of times that part was injured). I suspect a zero-inflated negative binomial regression would be best here.  The equipment would be the independent variable.
Second you could analyze combinations of body parts as the dependent variable. This would depend on having a large enough N to make various combinations common enough to analyze, and it would require some judgement in picking combinations. You don't say how many body parts you list, but it looks like it would be at least 10. That makes for a LOT of potential combinations. You might wind up with things like "Head and something else" but you'd have to be careful to make the categories exhaustive and exclusive.
Comment: ZINB is useful when there are a lot of 0's.
Comment: I have 18 body parts listed so I think the number of combinations would be too large. What would be the advantage of using ZINB over a negative binomial regression. I have a very cursory understanding of these procedures. I don't think there are any pieces of equipment or body part that has zero probability of being injured.


Geração do .IPA sem neccesidade de certificado?

Question: Bom dia,
Gostaria de saber se existe a possibilidade de gerar o .IPA ios sem a necessidade de certificado ou algo do tipo para teste em desenvolvimento, para assim não precisar atribuir o dispositivo, há essa possibilidade?
Answer: Para testes de desenvolvimento (não AdHoc):

Compile o projeto (⌘ + B);
Na barra esquerda do Xcode procure pelo .app (pasta Product);
Clique com botão direito e selecione Show in Finder;
Crie uma pasta chamada Payload e copie seu .app para ela;
Clique com botão direito na pasta e selecione Comprimir;
Renomeie e troque a extensão de .zip para .ipa;


How to Create Dictionary via LINQ to XML?

Question: I have the following XML:
<FootNotes>
  <Line id="10306" reference="*"></Line>
  <Line id="10308" reference="**"></Line>
  <Line id="10309" reference="***"></Line>
  <Line id="10310" reference="****"></Line>
  <Line id="10311" reference="+"></Line>
</FootNotes>

and I have the following code where I'm to get a Dictionary<int, string>() object into
myObject.FootNotes

so that each Line is a Key/Value pair
var doc = XElement.Parse(xmlString);

var myObject = new
  {
      FootNotes = (from fn in doc
                       .Elements("FootNotes")
                       .Elements("Line")
                       .ToDictionary
                       (
                       column => (int) column.Attribute("id"),
                       column => (string) column.Attribute("reference")
                       )
                  )
  };

I am unsure how to get this from the XML into the object though. Can anyone suggest a solution?
Answer: Your code is nearly correct. Try this slight variation instead:
FootNotes = (from fn in doc.Elements("FootNotes")
                           .Elements("Line")
             select fn).ToDictionary(
                 column => (int)column.Attribute("id"),
                 column => (string)column.Attribute("reference")
             )

I don't think the long from ... select syntax really helps much here. I'd use this slightly simpler code instead:
Footnotes = doc.Descendants("Line").ToDictionary(
                e => (int)e.Attribute("id"),
                e => (string)e.Attribute("reference")
            )

However you are using an anonymous type in your example code. You need to use a concrete type if you are planning to return this object to the caller.
var myObject = new SomeConcreteType
    {
        Footnotes = ....
    };

Comment: the code is _almost_ correct, except for `(from fn in ` and the trailing `)`. The sample you provided before editing pointed this out. You should revert the last edit so I can select this as the correct answer
Comment: @DaveDev: I've actually added that now too :)


Compare current time with fixed time 05:00:00 PM

Question: How will I compare current time [NSDate date] with fixed time 05:00:00 PM.
That 05:00 PM is already passed or not. I just need BOOL check for this.
Answer: - (BOOL)past5pm
{
    NSCalendar *gregorianCalender = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *components = [gregorianCalender components:NSHourCalendarUnit fromDate:[NSDate date]];

    if([components hour] >= 17) // NSDateComponents uses the 24 hours format in which 17 is 5pm
       return YES;

    return NO;
}

Answer: NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]  autorelease];
[dateFormatter setDateFormat:@"HH.mm"];
NSDate *currentDate = [NSDate date];
NSString *curDate = [dateFormatter stringFromDate:currentDate];

if ([curDate doubleValue] >= 17.00)
{
    //set your bool
}

Comment: Comparing a ObjC object with a double seems a bit wrong, don't you think so?
Answer: Try this
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        [dateFormatter setDateFormat:@"hh:mm:ss a"];

        NSDate* date = [NSDate date];

        //Get the string date
        NSString* str = [dateFormatter stringFromDate:date];

        NSDate *firstDate = [dateFormatter dateFromString:@"05:00:00 PM"];

        NSDate *secondDate = [dateFormatter dateFromString:str];

        NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];

        NSLog(@"Time Diff - %f",timeDifference);

Answer: You can probably use plain C style code and get the difference as an integer and then decide what you need to return from the comparison function depending on wether the difference is positive or negative. You can compare minutes this way as well. Dont forget to import time.h.
    time_t now = time(NULL);
    struct tm oldCTime;
    localtime_r(&now, &oldCTime);
    int hours = oldCTime.tm_hour;
    int diff = 17-hours;
    NSLog(@"Time difference is: %d.", diff);


Random variable $X$ inducing a distribution on $V$

Question: I have been learning about discrete probability and found a somehow confusing (to me) definition of distribution of a random variable $X$ on a set $V$.
The definition of a Random variable $X$:
$$
X:U\to V
$$
Now, I'm reading that more generally, the Random variable $X$ induces a distribution on $V$ by the equation:
$$
P(X=v) = P\left[X^{-1}(v)\right]
$$
I imagine that $P(X=v)$ is the probability of $X$ being of value $v$.
So what does this $P\left[X^{-1}(v)\right]$ mean? How are both sides related? Is there a way of explaining it by example?
Comment: If $V$ is the (countable) set of possible values $X$ takes, then for all $v\in V$ we have $X^{-1}(\{v\}) = \{u\in U\mid X(u)=v\}$ an event (an element of our $\sigma$-algebra on $U$), since presumably, singletons are measurable sets in $V$ (as occurs for example when $V\subset\mathbb{R}$ is endowed with the Borel $\sigma$-algebra). We can therefore find the probability of this event.
Answer: The three following sets coincide:
$$
\{X=v\}=\{u\in U\mid X(u)=v\}=X^{-1}(\{v\}).
$$
In particular,
$$
P[X=v]=P[\{X=v\}]=P[X^{-1}(\{v\})].
$$
Answer: $X^{-1}(\{v\})$ is the inverse image of the set $\{v\}$ under the function $X:U\to V$: $$X^{-1}(\{v\})=\{u\in U\,|\,X(u)=v\}.$$ In order words, $X^{-1}(\{v\})$ is the set of all points in $U$ for which the value of the function $X$ is $v$.
Answer: $X$ is a function, and $X^{-1}(v)$ is the set of values in $u \in U$ that satisfy $X(u) = v$. So if you want to know the probability that $X = v$ where $X$ is considered a random variable (where the probability is denoted P(X = v) like you guessed), all you have to do is add up the probabilities of all $u \in U$ that satisfy $X(u) = v$. That's what the equation is saying.


Categorical Time

Question: I always want to apply category theory to structures that involve "time" or "stepping"/"increment"(discrete "time").
I visualize it as a sequence of categories that are somehow connected(generally the objects are the same and only the morphisms will change, not sure if they are functorially related or not in all cases).
In my cases they are discrete systems in the sense that a morphism does not continuously flow, although, I suppose it should be valid for such systems too(analogous to the calculus of limits).
Is there anything in category theory that deals with this topic? I find that that category theory is more relevant to real systems when time seems to be included but I haven't been able to really apply it with time. In fact, one thing I sort of want to do is have Markovian like structures on categories. A set of categories with probabilistic transitions between them, this too is a sort of category with, I guess, the transitions being functors that are selected with a probability(but in a sequence of steps).
It seems to be category theory generally is thought of as a static structure but this is quite limiting to problems that are actually relatively simple statically but change over time. E.g., imagine a cell phone network where the objects are cell phones and the morphisms are connections. The connections may be off or on(a phone call) and also last for any length of time. Each instant in time there is a category/graph of the network. But over time the graph is dynamically changing. We can even do things like calculus over it.
So, in such ways it looks more like graph theory, BUT, of course, these happen to be categorical structures(identities, composition inclusion, etc)... so the goal is to extract some time-dependent structural variation. E.g., we can think of a typical "basic" category as static in time analogous to a constant function, it's derivative is 0. In this case the categorical structure is dynamic and its "derivative" is not constant but shows how the structure is evolving. Ultimately I want to be able to extract some meta-structure from the evolution of the changing categorical structure(and ultimately derive some type of meta^n-structural deductive chains which would, I hope, ultimately be categorical in nature).
Comment: You might be interested in Schultz-Spivak's book on temporal type theory, which replacing the entire foundation of math with a time-dependent superstructure by working in a topos of sheaves on intervals of real numbers. In this topos the sentence "$C$ is a category" in first order logic is automatically translated to "$C$ is a time dependent family of categories." https://arxiv.org/pdf/1710.10258.pdf
Comment: @KevinArlin Thanks, this may be what I'm looking for. My category-foo is not great and only reading a little bit of the paper It is not clear if this is precisely what I'm after but it seems like it is at least along the same lines(It might be structurally identical but the language itself that is used is not how I would express it... but again, I don't speak category-foo all that well).
Answer: I don't know if the following are exactly what you're looking for, since they are about modelling dynamical systems within category theory, rather than having a dynamical system of categories, but they are likely to be useful for inspiration, if nothing else.
There's a classic way to look at discrete-time dynamical systems in category theory. One is just to model a dynamical system as a set $X$ with an endomap, that a function $f\colon X\to X$, which you think of as the update function. This can be seen as a functor $\mathcal{N}\to\mathsf{Set}$, where $\mathcal{N}$ is a monoid (i.e. a category with a single object) whose morphisms are the natural numbers and the composition of two morphisms is given by addition. Natural transformations between such functors give a natural notion of morphism between dynamical systems, and the resulting category (being a presheaf category and hence a topos) has a lot of very nice properties. This is explored in Lawvere and Schanuel's classic book 'Conceptual Mathematics', among other places.
For Markov processes, a nice place to start is Tobias Fritz' recent paper A synthetic approach to Markov kernels, conditional independence and theorems on sufficient statistics. This paper gives a modern framework for thinking about probability in category theory, based on what he calls "Markov categories", which generally behave like categories of sets and stochastic functions (i.e. Markov kernels). Similarly to the above construction discrete-time, time-homogeneous Markov process is a functor $\mathcal{N}\to \mathscr{M}$, where $\mathscr{M}$ is a Markov category. Fritz mentions Markov processes only briefly in his paper, but still I think it's a good place to start in thinking about them.
In both of these cases, if you want to consider non-time-homogeneous systems (i.e. where the update function can change on every time step) you can look at functors from $\mathbf{N}$ instead of $\mathcal{N}$, where $\mathbf{N}$ is the natural numbers seen as a preorder instead of a monoid. (I'm making this notation up - I'm not sure if there are standard symbols for these categories.)
This kind of approach can also be used for continuous-time systems, by replacing the monoid of natural numbers with a monoid of real numbers, although things tend to get significantly more complicated due to the need to consider topology. See this blog post by Jade Master for such a construction.
Since you seem to be looking for a discrete-time dynamical system where the state space consists of categories, it could be that you would be interested in functors $\mathcal{N}\to\mathsf{Cat}$ or $\mathbf{N}\to\mathsf{Cat}$. This seems like it should be related to the Grothendieck construction. I have no intuition for what it would be like, and I also don't immediately know how one would make it into a stochastic process.
Going in a somewhat different direction, there is a fair bit of current research in category theory in something called "open dynamical systems", which may be in discrete or continuous time. The idea here is to define dynamical systems with inputs and outputs (in various different senses), such that they can be composed with each other. If you search YouTube you can find some lectures by David Jaz Myers that give a good overview, and you can also find some papers on this topic by John Baez' group, among others.
Comment: Thanks, I'll take a look at it. Not sure if what I'm asking can be translated in to a dynamical system without over complicating it or, if essentially, they are equivalent interpretations. What I'm basically taking about are a sequence of graphs(or even a whole family of sequences) and trying to deduce the underlying structure. I believe that the underlying logic will essentially be "invariant" or the structure that changes the least in some sense(assuming the graph represents the logic directly, which it may not). Each graph has it's own logic, but so does the sequence of them.
Answer: Time is a physical concept and it's a question of how it is to be modelled. It's quite possible that it's an artifact of our modelling that we get time invariance since causal nets, a model in quantum gravity allow, for modelling of time as open - a relatively recent result.
This to me seems a prime suspect in modelling by category theory: the problem being to say something new that hasn't already  been said by causal set theory.
Comment: I'm not necessarily treating time as physical. Another way to think about it is parameterized, so it really has nothing to do with physical time. If C is a category then C[x] can be thought of as a parameterized category, say $x \in \mathbb{Z}$. This has nothing to do with physical time, quantum gravity, or any of that other non-sense. Maybe I should not have used the word time? [It just so happens that parameterizations and "time"(as we know it) seem to highly correlate. Time seems parameterizable by mathematics]

Categorical Time


How to stop Senna.js from calling multiple jQuery event handlers

Question: I have developed a SPA website using Senna.js and it works great! However, I have recently noticed that it doesn't remove jQuery event handlers when leaving the page. So I have all kinds of functions firing twice when I navigate back to a page I have already visited.

I fixed most of my personal code by doing this
$("#element").off("event").on("event", etc.)
But there are thousands of lines of other people's code which is also powering my website and I am worried that they are firing twice as well.
Does anybody on SO have any insight or approaches to handling this?
Answer: You can detach event handlers using Senna's lifecycle events. For example:

var app = new senna.App();

app.on('beforeNavigate', function() {
// detach jQuery event handlers
});


Suppose that G is a group with $|G| = mp$ where $p$ is a prime and $1 < m < p$. Prove that $G$ is not simple.

Question: The question I am trying to solve is:
Suppose that G is a group with  $|G| = mp$ where  $p$ is a prime and  $1 < m < p$. Prove that  $G$ is not simple.
We were given the hint to construct a homomorphism $G \to S_m$.
I came across this proof, but I don't understand all of the parts of the proof.
Proof:
Let  $H\leqslant$ G be such that  $\lvert H \rvert=p$. It is trivial that there is a homomorphism  $\phi:G\to \text{Sym}\left(G/H\right)$ by having  $\phi_g(aH)=gaH$. Moreover, one can prove that $\ker\phi\subseteq H$. Now, since  p is prime and  $\ker\phi\leqslant H$ we must have that  $\ker\phi=\{e\}$ or  $\ker\phi=H$. Suppose that  $\ker\phi=\{e\}$ then  $\text{im}(\phi)$ is a subgroup of $\text{Sym}\left(G/H\right)$ of order  $mp$ and so $ mp\mid m!$ but since  $p$ is prime and $ m<p$ this is impossible. Thus,  $H=\ker\phi$ and so  $\{e\}\triangleleft H\triangleleft G $ so that $G$ isn't simple.
My questions are why is it trivial that such a homomorphism exists, how do we show that the kernel is in $H$, and why is the kernel equal to either $\{e\}$ or $H$?
Thank you for any help.
Comment: Since you asked about the specific approach, I won't make this an answer. But there is another way: Assume that $K$ is another subgroup of order $p$. Consider the subset $KH$ and note that the restriction on the order forces $K = H$.
Answer: The group $G$ acts on the set of cosets of $H$ by left multiplication. This action is just permuting the cosets in some way. There are $m$ such cosets, so the action of $G$ on $G/H$ 'translates' to a homomorphism from $G$ to $S_m\cong \text{Sym}(G/H)$.
The details of why $\phi$ is actually a homomorphism. $\phi:G\to\text{Sym}(G/H)$ is given by $g\mapsto\phi_g$, where $\phi_g(aH)=gaH$. It's not too difficult to show that $\phi$ is a homomorphism: $\phi(g_1g_2)=\phi_{g_1g_2}$ and $$\phi_{g_1g_2}(aH)=g_1g_2aH=g_1(g_2aH)=g_1\phi_{g_2}(aH)=\phi_{g_1}\circ\phi_{g_2}(aH)=\phi(g_1)\phi(g_2)(aH).$$
So $\phi(g_1g_2)=\phi(g_1)\phi(g_2)$ and we do indeed have a homomorphism.
For the kernel: The kernel of $\phi$ is the set of elements of $G$ which are sent to permutations which fix all cosets of $H$ in $G$. Consider the permutations which fix $H$, i.e. $\phi_g(H)=H$, clearly this is true only for $g\in H$, so the kernel has to be a subgroup of $H$.
Remember that the order of $H$ is prime, and Lagrange's theorem states that the order of any subgroup must divide the order of that group, so since ker$(\phi)\leq H$, its order can only be 1 or $p$, so either $\{e\}$ or $H$ itself.
Hope this helps.
Comment: Yes! Thank you!


Flabby representable sheaves

Question: Let $S$ be a scheme. Consider some representable moduli functor $\mathcal{M}:(Sch/S)^{op}\rightarrow Set$ represented by some scheme $M$. Then for each $V\in (Sch/S)^{op}$, let define
$$\mathcal{M}^{glob}(V):=\text{im}\left(\mathcal{M}(S)\rightarrow \mathcal{M}(V)\right).$$
This defines a subfunctor $\mathcal{M}^{glob}\subset \mathcal{M}$. I'm interested if this functor is again representable. I tried showing that this is a open or closed subfunctor, but with no succes.
In a bit more generality, consdier a sheaf representable $\mathcal{F}$ on some site $\mathcal{C}$ with an initial object $X$. Then we can define a maximal flabby sub-pre-sheaf $\mathcal{F}^{glob}$ by defining
$$\mathcal{F}^{glob}(V):=\text{im}\left(\mathcal{F}(X)\rightarrow \mathcal{F}(V)\right).$$
Is this a sheaf again, and is it representable?
Comment: In general, this construction will not even yield a sheaf. For instance, if you have a sheaf on (the gros site of) a connected topological space $X$ that has an open neighbourhood $V$ that is a disjoint union of two connected open neighbourhoods $V_1$ and $V_2$, then the sheaf condition would require $F (V) \cong F (V_1) \times F (V_2)$, but if $F$ is the sheaf of continuous functions $X \to \mathbb{C}$ then the image of $F (X) \to F (V)$ does not agree with the product of the images of $F (X) \to F (V_1)$ and $F (X) \to F (V_2)$. Unfortunately this example is not easily translated to schemes.
Answer: Let $\mathcal{C}$ be a small site (or, at least, cofinally small) and let $\textbf{Psh} (\mathcal{C})$ be the category of presheaves on $\mathcal{C}$. There is a functor $\Gamma : \textbf{Psh} (\mathcal{C}) \to \textbf{Set}$ represented by the terminal presheaf (which may or may not be representable in $\mathcal{C}$, at this level of generality), and it has a left adjoint $\Delta : \textbf{Set} \to \textbf{Psh} (\mathcal{C})$ that sends every set $A$ to the "constant" presheaf defined by $(\Delta A) (U) = A$. We have a counit morphism $\epsilon_F : \Delta \Gamma F \to F$ for every presheaf $F$, and your construction is precisely the image of this morphism. Expressed this way, the failure of $\operatorname{Im} \epsilon_F \subseteq F$ to be a sheaf becomes unsurprising: usually we have to sheafify the presheaf image to obtain a sheaf.
If your goal is to construct a flabby (pre)sheaf, then it would be inappropriate to sheafify $\operatorname{Im} \epsilon_F$: sheafification can destroy flabbiness. On the other hand, if we work with presheaves then representability is a rather strong condition: indeed, representable presheaves are projective, so the epimorphism $\Delta \Gamma F \to \operatorname{Im} \epsilon_F$ would be split. But that would make $\operatorname{Im} \epsilon_F$ a retract of a constant presheaf, hence also constant – not very interesting, I think.
Finally, let me remark that the notion of flabby (pre)sheaf does not seem to be appropriate for non-localic sites. The point of flabby sheaves of modules on a topological space or locale is that they are acyclic with respect to the global sections functor, but I don't think this is true for a general site.

Flabby representable sheaves


Get a HLS stream for a HVEC/h265 video

Question: What I want to do?
Generate HVEC (h265) HLS of a mp4 file.
What I already have tried?
I came across this post https://superuser.com/a/1416549/1084556. It first asks to convert h264 video to h265 format and then do the HLS packaging`.
So I ran
ffmpeg -hide_banner -y -i "original.mp4" -c:v libx265 -c:a copy -y -movflags +faststart -tag:v hvc1 "h265.mp4"

Above command is good enough to generate a h265 encoded video which is working on QuickTime Player on macOS.
Next I
ffmpeg -y -i h265.mp4 -c copy \
    -hls_segment_type fmp4 -hls_time 6 -hls_list_size 10 \
    -hls_flags delete_segments+append_list+split_by_time \
    -hls_playlist_type vod hls.m3u8

Above command generated a few m4s along with hls.m3u8 and init.mp4 files, which seems to be the expected behaviour but when I host the files and try to play it in any online media player, it doesn't work, and throws error
A media error occurred: bufferIncompatibleCodecsError

Player used (https://hls-js.netlify.app/demo/, https://bitmovin.com/demos/stream-test)
Answer: Based on the spec document both hls.js plugin and also the bitmovin player supports HEVC HLS format. You didn't mention about the browsers that you've tested. Based on my understanding, you can only playback HEVC/fmp4 HLS stream on safari browser. Worth testing that as well.
Comment: I've tested this on both Chrome and Safari. On Chrome, they both throw errors. On Safari, while we do not get any errors, the players are still not able to play the streams.
Comment: If you can share your HLS link, I can take a look at the manifest and also the segments. I would also suggest you to run your hls output in [mediastreamvalidator](https://developer.apple.com/documentation/http_live_streaming/about_apple_s_http_live_streaming_tools) tool that will give you valuable insight.
Comment: I actually did that as well. Raised another question here with output from mediastreamvalidator https://superuser.com/q/1661921/1084556.

Get a HLS stream for a HVEC/h265 video


JQuery Datatable not displaying when rows too large

Question: I have a encountered a weird problem with JQuery datatables; I have these on a number of pages on my site, and they are working perfectly, except when the data exceeds some seemingly arbitrary size.  In one instance this is exactly 798 rows (with two columns), another, which has nine columns, won't display anything over around 500 rows.  I am figuring this is something to do with the overall size of the data.  Looking this up on Google people are saying there can be a problem with very large datasets, but these always seem to refer to rows in the millions; the most I have is just over 16000.  Surely this shouldn't cause an issue?
Basically if I try to return more rows than it likes, it does nothing; no errors, just doesn't display any data and locks up IE. Is there a setting somewhere I have missed that is causing this?
Thanks
Answer: I ended up using Server Side processing to handle the data loading:
<code><script type="text/javascript">
$(document).ready(function() {
    //http://www.datatables.net
    $('#userTable').dataTable({
        "sPaginationType": "full_numbers",
        "bJQueryUI": false,
        "bAutoWidth": false,
        "bLengthChange": false,
        "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": "/Project/GetDataTables2",
        "fnServerData": function(url, data, callback) {
            $.ajax({
                "url": url,
                "data": data,
                "success": callback,
                "contentType": "application/x-www-form-urlencoded; charset=utf-8",
                "dataType": "json",
                "type": "POST",
                "cache": false,
                "error": function() {
                    alert("DataTables warning: JSON data from server failed to load or be parsed. " +
                    "This is most likely to be caused by a JSON formatting error.");
                }
            });
        },
        "aoColumns": [
            { "bSortable": true },
            { "bSortable": true }
        ]
    });
});
</script>
</code>
This worked perfectly and loaded quickly since I am only loading 10 or so at a time.


How to generate templates suggestion for media.html.twig for a specific field in a content type?

Question: I have a content type (say Article) with an entity reference field to another content type (Author). I have used layout builder together with a view mode to display the content of the Author field in the Article content type.
One of the fields in Author is an image which is rendered via media.html.twig. Coincidentally there is also an image in Article rendered via media.html.twig
I used hook_theme_suggestions_media_alter to provide a new suggestion.
<code>/**
 * Purpose: Adds theme suggestions for media.html.twig that are more specific to the content type.
 */
function custom_default_theme_suggestions_media_alter(array &$suggestions, array $variables) {

  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $content_type = $node->bundle();
    if($content_type == 'article') {
      $suggestions[] = 'media__' . $content_type;
    }
  }

}
</code>
but as the Author content type is rendered on the Article  page I can't seem to get a suggestion for the Author page. Is is possible to generate a suggestion for media.html.twig for a particular field in a content type referencing another content type?
Answer: I found a workaround for this by using the view mode along with the content type.  So the new code would be
<code>/**
 * Adds theme suggestions for media.html.twig
 */
function my_custom_theme_suggestions_media_alter(array &$suggestions, array $variables) {

  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $content_type = $node->bundle();

    // Adding suggestion for article page.
    if($content_type === 'article_page' && ($variables['elements']['#view_mode'] === 'full')) {
      $suggestions[] = 'media__' . $content_type;
    }

    // Adding suggestion for author block in article page.
    if($content_type === 'article_page' && ($variables['elements']['#view_mode'] === 'responsive_image')) {
      $suggestions[] = 'media__author_block__' . $content_type;
    }
  }
</code>


A question on spectrum

Question: Let $A,B \in {C^{n \times n}}$ and ${\sigma (A + B)}$ is spectrom of $(A+B)$.
Suppose

$M = \left\{ {\lambda  \in C:\lambda  \in \sigma (A + B),\left\| B \right\| \le \varepsilon } \right\}$
$F(A) = \left\{ {{v^*}Av:v \in {C^n},{v^*}v = 1} \right\}$
$K = \left\{ {\lambda  \in C:dist(\lambda ,F(A)) \le \varepsilon } \right\}$ ,where ${dist(\lambda ,F(A))}$ denotes the distance between $\lambda $ and
$F(A)$.

Why does $M \subseteq K$?
Comment: Please consider asking at Mathematics StackExchange instead. (This smells like homework, which is typically not what we entertain here.) Be prepared in that case to explain to them what you have tried.
Answer: Let $\lambda  \in M \Rightarrow \exists v: (A+B-\lambda E)v=0 $. Without loss of generality we assume that $\|v\|=1  $.
Then $v^*(A+B-\lambda E)v =0 \Rightarrow \|v^*Av - \lambda\|=\| v^*Bv
\|.$
Then you need to show that last expression is less than $\varepsilon$ and you will have that  $\lambda  \in K$.

A question on spectrum


powershell Export-Csv overwrite and -append

Question: <code>#Create an empty System.Array object
$employees = @()

#Add newly created object to the array
#$employees += $employee
for ($i=1;$i -le 2;$i++)
{
    $employee = New-Object System.Object
    $employee | Add-Member -MemberType NoteProperty -Name "Creation Time" -Value $(Get-date)
    $employee | Add-Member -MemberType NoteProperty -Name "Employee ID" -Value $($i.ToString("D2"))
    $employees += $employee
    Start-Sleep -Seconds 1
}

#Finally, use Export-Csv to export the data to a csv file
$employees | Export-Csv -NoTypeInformation -Path "c:\temp\test\EmployeeList.csv"
</code>
this is code write data is overwrite old data,i want to same change code, add "-Append"
<code>$employees | Export-Csv  -NoTypeInformation -Path "c:\temp\test\EmployeeList.csv" -Append
</code>
error message:
Export-Csv : A parameter cannot be found that matches parameter name 'Append'.
At D:\powershell\MU_TAG_ET.ps1:292 char:70
+ $employees | Export-Csv -Path "c:\temp\test\EmployeeList.csv" -Append <<<<
    + CategoryInfo          : InvalidArgument: (:) [Export-Csv], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.ExportCsvCommand
can u help me??
Comment: `-append` is starting from 3.0 version. Are you in powershell 2.0?
Answer: If you don't have Powershell V3 or later as mentioned, you could test to see if your CSV exists, if that's the case, use Import-Csv to $employees array, add new $employee PSCustomObjects, and export when done.


Hora atual usando java script

Question: Ele esta imprimindo a hora atual do sistema, mas quando abro o projeto na web, ele na atualiza a hora sozinho.
e eu quero saber também, como eu coloco os segundos logo apos o minuto. (pra fazer uma contagem certinha, igual relogio)
Sou iniciante, por isso o código esta ruim galera, aceito dicas
JS:
function carregar (){
var msg = window.document.getElementById ('msg')
var img = window.document.getElementById ('imagem')

var data = new Date ()
var hora =  data.getHours ()
var minuto = data.getMinutes ()
var segundos = data.getSeconds ()

if (hora >= 18){
    img.src = "./img/noite.jpg";
    document.body.style.background = 'Black'
    msg.innerHTML += `Boa noite, agora são ${hora}:${minuto}`

}
else if (hora <18 && hora >12){
    img.src = "./img/tarde.jpg";
    document.body.style.background = '#b9846f'
    msg.innerHTML += `Boa tarde, agora são ${hora}:${minuto}`
}
else if (hora >= 0 && hora <12){
    img.src = "./img/dia.jpg";
    document.body.style.background = 'rgb(70, 142, 236)'
    msg.innerHTML += `Bom dia, agora são ${hora}:${minuto}`
}

}
HTML:

    Projeto horas

Answer: Você pode utilizar o setInterval para deixar o relógio dinâmico

var relogio = document.getElementById("relogio")

function updateClock() {
    var data = new Date(),
        hora =  data.getHours(),
        minuto = data.getMinutes(),
        segundos = data.getSeconds() <= 9 ? "0"+data.getSeconds() : data.getSeconds()

    relogio.innerHTML = `${hora}:${minuto}:${segundos}`
}

setInterval(updateClock, 1000)

O setInterval() recebe dois parâmetros: Função de callback (a função que você quer que seja executada em loop) e o temporizador que irá executar a função em loop, a cada X milisegundos
Fonte: https://developer.mozilla.org/pt-BR/docs/Web/API/setInterval

Hora atual usando java script


How to express the notion of a vector, where every element inside is matrix?

Question: I met a question when I tried to express a vector, where every element inside is a matrix. We know the notion usually works like this:

scalar: $a$
vector: $\boldsymbol{a}$
matrix: $\boldsymbol A$
vector (elements inside are vector): $\boldsymbol{A} = [\boldsymbol{a}_1, \boldsymbol{a} _2, \boldsymbol{a} _3]$

What if I want to express a vector (or tensor) where the elements are matrices, like the following:

vector (elements inside are vector): $? = [\boldsymbol{A}_1, \boldsymbol{A} _2, \boldsymbol{A} _3]$

Should I still use $\boldsymbol A$, Or is there a formal expression?
Answer: This question is about conventions, and it will differ from field to field. You should use the conventions of your field.
Otherwise, the standard ISO 80000-2 identifies notation for scalars, vectors, matrices, tensors, and more. Symbols for tensors are in sans-serif bold italic. The isomath package implements this in LaTeX.
Comment: +1 for isomath, great little package
Comment: Thank you so much for your answer, Arya! I checked the materials you mentioned, and it seems the symbols of matrix(2-15.1) and tensor(2-17.19) are the same: both are sans-serif bold italic with a capital case. Thanks again!
Comment: The matrix notation has serifs. The tensors don't.
Comment: Sorry I didn't notice that difference! Thank you so much for pointing it out. Problem solved!


como comparar duas matrizes e trazer os valores diferentes?

Question: Estou tentando fazer o esquema de criar um loop de 1 a 70 por exemplo
no banco irá retornar
1
10
11
20
39
50
67
69
de 1 a 70 só que irá tudo, só irá trazer alguns numeros entre 1 e 70 .
estou tentando criar um loop usando o for de 1 a 70 e comparar com os valores mostrado acima que retorna do banco, eu preciso mostrar na tela os valores de 1 a 70 que não tem no banco, ou seja, que não tem no banco seria possível fazer isso?
Segue o código:
$aleatorio = rand(1, 70);
echo $aleatorio."
";
$recorte = $valor."_".$aleatorio;

$query = mysqli_query($con,"select material_name_crop from qe.etiquetas_recortadas_aoi where material_name_crop = '$recorte' and line = '$pkg' and brand = '$brand'") or die("erro na query");
$rows = mysqli_num_rows($query);
if($rows < 1){
    echo $recorte." - ".$pkg." - ".$brand." S";
}else{
    $pesq = mysqli_query($con,"select material_name_crop from qe.etiquetas_recortadas_aoi where material_name_crop like '%$valor%' and line = '$pkg' and brand = '$brand'") or die("erro na query");
    $total = mysqli_num_rows($pesq);
    echo "Total ".$total."

";
    $count = 0;
    while($recorte = mysqli_fetch_array($pesq)){
        $count = $count+1;
        $content = explode("_",$recorte[0]);
        $t = $content[1];

        //print_r($content);
        for($i=0;$i<=70;$i++){

            $j[] = $i;
            //echo $j[$i];
            $result = array_search($j[$i], $content[1]);
            echo $result;

    //      echo array_diff($val)."  -   ";
        }
        echo "
".$count." - ".$content[1]."      /       ";

        //print_r($j);

    }
        echo "
".$count." - ".$content[1]."      /       ";

        //print_r($j);

    }
    //echo $recorte[0]." - ".$pkg." - ".$brand." N";
}

Comment: Eu recomendaria que desde já busque [edit] sua pergunta e melhorar o texto, principalmente utilizando pontuações. Está praticamente ilegível e incompreensível.
Comment: minha duvida é simples gostaria de saber se consigo trazer informações diferentes comparando duas arrays
Answer: Tu pode utilizar a função in_array, onde ela vai checar se o valor não está dentro do array (no teu caso, seriam as informações vindo do banco).
// Armazena os dados vindo do banco em um array como este
$array_banco = array(1, 4, 7, 8, 2, 90);

for($i = 1; $i <= 70; $i++) {
   // Checa se o valor do for nao esta dentro do array
   if(!in_array($i, $array_banco)) {
        echo $i . ' nao esta dentro do array';
   }
}

Comment: Não seria `for($i = 1; $i <= 70; $i++) {`  para não retornar valor 0(zero)
Comment: Sim sim, coloquei errado ali. Já arrumei, valeu pelo aviso.


I need to go few websites and grab specific data set

Question: Looking for a way to go to a few websites (10 sites) and grab a set of data, need a proper way to do since I am new to coding.
code:
WebUI.openBrowser('');
WebUI.navigateToUrl("www.site1.com");
WebUI.maximizeWindow();
String text1 = WebUI.getText(findTestObject("xpath"));

Do I need to do this for all the 10 websites?
Comment: why don't you loop it ?
Comment: How would you do it manually?
Comment: I have a set of values and need to compare those with 10 sites.
Answer: Let's say you have the 10 URLs in an array. Create another empty array that will hold the text values:
WebUI.openBrowser('');
def mySites = ["www.site1.com", "www.site2.com", "www.site3.com", "www.site4.com", "www.site5.com", "www.site6.com", "www.site7.com", "www.site8.com", "www.site9.com", "www.site10.com"];
def myTexts = [];

Then loop your above code in a for loop, and add the text values to the array (note: xpath element name is the same for all the sites in this example, you should edit that according to your needs):
for(i=0; i<mySites.size; i++){

    WebUI.navigateToUrl("www.site1.com");
    WebUI.maximizeWindow();
    myTexts << WebUI.getText(findTestObject("xpath"));
}


Invite Facebook friends error

Question: I created a page tab like and win application. The plugin that Facebook provides for inviting friends doesn't seem to work anymore. Is there an error with the plugin?
This is the app: https://www.facebook.com/mees.melky/app_196218193879130
Kind Regards,
Mark
Comment: What is the plugin? Error message?
Comment: It's the plugin were you can select friends and they then get a notification with a link to the app.
Answer: try this it has helped me. copy it in ur html .
http://www.9lessons.info/2012/07/facebook-invite-friends-api.html#comment-form

Invite Facebook friends error