Javascript passing arrays between nested Functions()

Question: I keep getting undefined in the alertbox popup...am I missing something? And there is data on nodeArray[0], because if I put it inside the for loop it alerts correctly.
function grabNodes(env, poolName){
    var env = "dev";
    var nodeArray = new Array();

    var ajaxRequest; //initialize ajax object

    var browser = navigator.appName; //find the browser name
    if(browser == "Microsoft Internet Explorer"){
        /* Create the object using MSIE's method */
        ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else{
        /* Create the object using other browser's method */
        ajaxRequest = new XMLHttpRequest();
    }

    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
        // Get the data from the server's response
        //what on this page is changing
            var xmlRes=ajaxRequest.responseXML.documentElement;
            try {
                for(var i=0; i<xmlRes.getElementsByTagName('node').length;i++){
                    nodeArray[i] = xmlRes.getElementsByTagName('node')[i].firstChild.nodeValue;
                }//end for loop
            }
            catch (err){
            }
             alert(nodeArray[0]);
        }

    }

//return nodeArray;
}

function is called by:
function other(){
    oNodeArray = grabNodes(env, poolName);
}

Answer: Ajax calls are asynchronous. alert(nodeArray[0]); is executed before the function you assigned to ajaxRequest.onreadystatechange.
Put the alert in the callback and it will work (provided you get a valid response). Every code that has to operate on the result has to be called from the callback.
Update: You cannot return data. You have to restructure your code to use callbacks.
If your current code is like
oNodeArray = grabNodes(env, poolName);

// work on `oNodearray`

you have to change it to:
grabNodes(env, poolName, function(oNodearray) {
     // work on `oNodearray`
});

and the Ajax callback has to call the function you pass and pass the array to it:
function grabNodes(env, poolName, callback){
    //....
    ajaxRequest.onreadystatechange = function(){
        // stuff
        callback(nodeArray);
    }
}

Because Ajax calls are asynchronous, they don't block the execution of the code. You need to pass a function that will be executed once the data is received.

Further comments:

Use var nodeArray = []; to initialise an array.
var env = "dev"; will shadow the parameter env. If you want to assign a default value, do
env = env || 'dev';

Comment: so the i moved the alert and it gives me the data so I know it is working. But I am not understanding the return statement...if I put it there where does it return to? I need it to return to the oNodeArray which is in another function that calls grabNodes()
Comment: @Jim: You don't need to put a return statement in the callback, it will have no effect. Please see my updated answer.
Comment: grabNodes() has already returned by the time you set the array in the ajax callback.  You need to re-formulate your code such that you can call a given function with nodeArray as a parameter from your ajax callback.  You're trying to program this in a synchronous manner but ajax is by definition not synchronous.
Answer: The ajax call is most likely not yet complete when the alert is invoked. This should be placed inside the onreadystatechange handler.


Highly Correlated Datasets - Why and What Next?

Question: I've got three datasets (of different biological data) that are highly correlated - such that if I use the typical findCorrelation from the caret package with a cutoff of 0.99, then 5000 predictors are removed from one with 8000, another loses 648 from 654, and the last loses 645 from around 700.
My questions are these:

How can I examine my data to understand why they could be highly correlated?

Should I remove my data that is very highly correlated, even if it means the removal of nearly all data (a cutoff of 0.75 would remove everything, therefore 0.99 seems a better option)?

And finally, if I'm subjecting my data to analysis with PLS or PCA methods do I even need to remove highly correlated features at all?

Hope someone can help out, thanks for reading!
Answer: I don't suggest findCorrelation to get rid of highly correlated observations. I've just read the documentation by ?caret::findCorrelation and still don't know which correlation measurement method the function uses, but I think it uses pearson correlation.
Pearson correlation is not always a good way to measure correlation, specifically when you see enormous percentage (like %99 etc.) there should be something wrong. Let me try to explain with an example;
First, I created a dummy dataset with two different variable whose variables come from different distributions;
set.seed(1453)

dummy <- data.frame(a=rnorm(n = 100,mean = 50,sd = 100),
                    b=runif(min = 100,max = 500,n = 100))

Now I'm checking the corrlation between two variable with base cor function (which uses pearson correlation coefficient as default)
cor(dummy)

A matrix: 2 × 2 of type dbl
a   b
a   1.0000000   0.1844875
b   0.1844875   1.0000000

Pearson correlation coefficient says there is %18 positive correlation between two variables. Now, I am creating an outlier which isn't close the mean of both two distributions ;
hack_row <- data.frame(a=10000,b=10000)

dummy2 <- rbind(dummy,hack_row)

Now, Let me check the correlation again;
cor(dummy2)

    a   b
a   1.0000000   0.9896067
b   0.9896067   1.0000000

Pearson says %98 correlation between two variables ! Only one outlier can make it possible.
In short, some outliers can mislead us. %98 is not that realistic. We could use a non-parametric correlation measurement method like spearman correlation with the same data (with outlier).
cor(dummy2,method = 'spearman')

    a   b
a   1.0000000   0.1544787
b   0.1544787   1.0000000

Spearman says there is %15 positive correlation between two variables, which is way realistic than pearson correlation.
To get rid of highly correlated observations, you can use a non-parametric correlation measurement method and without findCorrelation function. Probably it will take a little more effort but you will no longer lose high amount of data.
You can continue with PCA analysis with your trusty uncorrelated data.

EDIT:
I've just learned that caret's findCorrelation takes a correlation matrix as an argument, changing cor's method argument to a non-parametric one fixes everything :)
Comment: Thanks very much for responding! Do you think it matters if my data are normalised? I read that Pearson is favoured if the data are normalised, but I've not heard if using spearman in that case will be fine.


Importar CSV no SQL Server

Question: Eu tentei importar uma base de dados utilizando o csv para uma base pronta do sql server que nós implantamos para outras empresas.
Mas no sistema quando se cadastra, um cliente por exemplo, utiliza-se do MAX(ID)+1 pra gerar o Id para determinada tabela.
Agora quando eu tento importar esses dados novos que estão em csv, o id fica nulo e por ser chave primária não deixa fazer a importação.
Como eu posso realizar esse Max(id) para definir o id da tabela na importação do arquivo csv.
Comment: Altere o tipo do campo para IDENTITY e exclua a coluna do arquivo CSV
Comment: A importação é executada em modo exclusivo, isto é, somente ela acessando a tabela? Qual o número aproximado de registros do arquivo CSV?
Answer: Você pode fazer a importação do arquivo CSV para uma tabela temporária e a partir desta tabela temporária fazer a inclusão na tabela definitiva usando algo como
-- código #1
declare @Ultimo int;

BEGIN TRANSACTION;

SELECT top (1) @Ultimo= id
  from tabela with (tablockx)
  order by id desc;

INSERT into tabela with (tablockx) (id, demais colunas)
  SELECT @Ultimo + row_number() over (order by (SELECT 0)),
         demais colunas
    from #tabelatemp;

COMMIT;

É uma sugestão que você deve avaliar se o bloqueio da tabela é obtido ou não.
É preciso ficar atento ao crescimento do log de transações enquanto a importação estiver em andamento.
Caso queira que o valor gerado para "id" seja segundo a ordem de algum campo do arquivo CSV, substitua (SELECT 0) pelo nome da respectiva coluna na tabela temporária.
É posível importar diretamente do arquivo texto para a tabela ao substituir #tabelatemp por OPENROWSET (BULK ...). Detalhes no artigo "Importação de dados em massa".

Importar CSV no SQL Server


Greatest Common Divisor With large numbers

Question: Find $\gcd(300^{40},2^{57})$
I know how to use Euclidean Algorithm for smaller numbers, but with these large numbers I'm not sure how to do it.
Comment: Note that $300^{40}$ is divisible by $2^{80}$.
Comment: This might help: $300^{40}=(2^8+2^5+2^3+2^2)^{40}$
Answer: Prime Factorize Each: $$300^{40}=2^{80}3^{40}5^{80}$$ $$2^{57}=2^{57}$$.
Thus, notice that $2^{57}|300^{40}$, and so the $\gcd$ is $2^{57}$.
In general, when approaching the $\gcd(a^{b}, c^{d})$, the easiest method would be to factorize $a$ and $c$.


How do I replace the SQL query of a view?

Question: I need to override an SQL query of a view. I'm using Drupal 7 and Views 3.x-7.x-alpha1.
I understood I can write my own query with views_pre_execute. I followed the instructions mentioned here: http://blog.raisedeyebrow.com/2010/04/rewrite-a-views-query/.
I added this piece of code to my custom module.
function alterquery_views_pre_execute(&$view) {
  dsm($view);
}

Following the instructions, when I look for the value of $view->build_info['query'], I see that the type is object of a class SelectQuery.
How am I able to get total control of the query and use my own select statement?
I know that with hook_views_query_alter() I can modify a keyed array, but I would rather write the select statement from scratch.
Comment: Ìf you want to rewrite the views query from scratch, why on earth do you use views on the first place? :)
Answer: Well, nothing is stoping you from building your own SelectQuery object and replacing the existing one. Overriding the query plugin is also an option. In this case it would be best to know WHY you're trying to replace the whole query. It makes very little sense to me.
Also, you're using alpha1? Why? That code is four and a half months old. Before attempting anything else, please update to -dev.
Comment: I think rewriting the sql is the easiest option. I can copy the sql statement from views UI and then do some modifications. So in that sense I was wrong to say I'm creating everything from a scratch. I'm also able to use views pager this way, right?
Comment: What are the modifications that you're trying to do? Yes, you could use the pager, but I'm wondering if there's a more targeted solution that we can suggest to you.
Comment: One motive is that I have an exposed filter and I have to check whether the value of the this filter can be found from any of the fields present in the views. There might be other ways to do this but I'm interested to know how to modify the sql query directly.
Comment: @jjei you can limit the filters with results by using [Views Hacks: Views Selective Exposed Filters](http://drupal.org/project/views_hacks#views_filters_selective), a [D7 port](http://drupal.org/node/1170644) is on its way.
Answer: If you create your own views class you can overide the execute() method to do whatever you like. If you look at the apachesolr_views or sparql_views modules you can see how they do just that. The views don't even use SQL.
Comment: I tried this by looking sparql_views but didn't get it working. I don't get why hook views_pre_execute has been changed. There seems to be a lot of work now to use views if u want to change the actual sql statement and you haven't written views plugins before.
Comment: I think is is because views is a query abstraction layer, so it is designed to stop you having to write queries yourself.
Answer: Any reason you couldn't implement hook_views_query_alter to change the query itself?
http://drupalcontrib.org/api/drupal/contributions--views--docs--views.api.php/function/hook_views_query_alter/7
Comment: This only let's you adjust the query object, before it's built. It's not a lot of use if you want to do something outside of Views' capabilities.


Integration by substitution, derivative of $g ' (x)$, why?

Question: First, let's look at the formula for integration by substitution:
$$\int f(g(x)) \cdot g'(x) = F(g(x))$$
where $F$ is an antiderivative of $f$.
But... I don't get why there's a $g'(x)$?
Example: $(2x-3)^2$. There is NO $g'(x)$ here, only $f(g(x))$ meaning only an inner and outer function... yet I'm supposed to use integration by substitution to solve this one, but how can I do that since it doesn't look like my formula?
Comment: This has nothing to do with integration.
Comment: Try $f(x)=x^2, g(x)=2x-3$ and note that $g'$ is constant, so it can get in and out of the integral sign.
Comment: If $F'(x) = f(x)$, then the *derivative* of $F(g(x))$ is $f(g(x))·g'(x)$, the identity you cited is false.
Comment: Hallo Daniel: what is $F$ (w.r.t. $f$ and $g$, I mean)?
Comment: It's an example from my book, so I'm pretty sure it has something to do with integration. Basically, I'm being told to use the formula mentioned in my first post to integrate (2x-3)^2. I know that my f(g(x)) is equal to (2x-3)^2, but I have no g ' (x) multiplied on, so what does that mean?
Answer: Yes, there is a $g'(x)$ if you just give it a little hand: the candidate $g(x)$ is obviously $2x-3$, corresponding to $g'(x)=2$.
$(2x-3)^2=\frac{1}{2}.(2x-3)^2.2$
Answer: I am assuming that you left out a symbol in the equation as the left hand side of your equation is actually equal to the derivative of the right hand side.
For your question: The trick here is that with the correct choice of $g(x)$, $g^{\prime}(x)$ will be a constant $c$, and so you can safely make a substitution after "multiplying" your integrand by $\frac{c}{c}$.


In college sports, does a redshirt have to sit a whole season?

Question: More specifically to college football or even basketball, is a player who is redshirted allowed to play at all during their redshirt season?
Comment: basically a college player has 4 years of eligibility to play sports (one for every year of college). A team has the option to "Redshirt" a player for one year out of the four years the player is at school. If you are "redshirting" a year you cannot play in any of your teams games but you dont lose a year of eligibility. Its usually used on incoming freshman so they can develop another year but still be able to play 4 years. dont know if that makes sense or not
Comment: What does *redshirted* mean?
Answer: Being redshirted doesn't commit the player to not playing the entire season; the team/player can change their decision part way through the year, but that revokes the benefit of having been redshirted (ie, that year would now count against their eligibility).
If the player plays in at least one game, that year counts towards their eligibility limits.
There is an exception if you start a season as an active player, and then get injured shortly into the season. You can retroactively be classified as a redshirt for that season.
Comment: "If the player plays in at least one game, that year counts towards their eligibility limits." true except if the player is injured.. you can apply for an injury redshirt with the Ncaa. Other than that good answer +1
Comment: I think you have to apply to the NCAA and they decide whether to award you an injury redshirt or not
Answer: This can vary a lot between sports so I'm not sure if there's a clear answer, but for the most part, once you've chosen to redshirt, you don't play anymore, unless you want to forfeit the redshirt.
In outdoor track, for example, people can red-shirt even if they've already run up to two competitions, and as long as it's before a certain date, and they have an injury.
Comment: So I guess a major factor is the sport they play in?


Are statements allowed to assert something about their containing sets?

Question: Let $X$ be a set.
Let $x \in X$.
Let $x$ be a statement $P(X)$ that asserts something about $X$.
I thought I read somewhere this isn't allowed.  However I can't find anything on Google.  Maybe I'm searching for the wrong things.
Comment: @WordsLikeJared Well then."It depends."
Comment: Are you saying that $X$ contains a **statement** about $X$? Which set-theory are you working with?
Comment: @user251257 1. Yes. 2. I was not specifying on purpose.  In case the answer was "it depends."
Answer: I suspect you might be thinking of the axiom of foundation. This axiom rules out, among other things, sets containing themselves as elements or even as subsets of elements. It is an axiom of ZFC, but there are set theories which don't include it (or even include outright anti-foundation axioms).

On the other hand, if you really are asking about sentences:
I think this will become less mysterious if we focus instead on cooking up a sentence which refers to a set which happens to contain it; that is, build $x$ first and then find an appropriate $X$. For example:
$$\mbox{"The set of English sentences containing ten words is finite."}$$
Take "$x$" to be the sentence above, and "$X$" to be the set of English sentences containing ten words. While self-reference is always worrying, it's hard to find an objection to something this straightforward. Note in particular that there isn't really any (direct) self-reference going on here.
Now of course, ultimately what sets are "allowed" depends on exactly what set theory you're using. E.g. ZFC proves that there is no universal set, but NF proves that there is a universal set. Meanwhile, in both ZFC and NF every object is a set; sentences, as such, don't exist and are rather part of the metatheory (although they can be represented by sets in various ways). So if you're not satisfied with the above vague response, you have a lot of work to do to make your question precise.


example of locally finite type not finite type

Question: Let $A$ be a ring then, a homomorphism $A\rightarrow A[x_1,\cdots,x_n]$ induces a finite type morphism between spectrums.
I want to find the map which is a locally finite type but not finite type....
Comment: The comments by Marci are wrong. For morphisms of affine schemes, locally of finite type = finite type. Affine morphisms are quasi-compact.
Comment: Try $k[x]\rightarrow k(x)$.
Comment: Dear Marci, $k[x]→k(x)$ is the inclusion?? Then, $\operatorname{spec}k(x)=\{0\}$... so is $\operatorname{spec}k(x) \rightarrow \operatorname{spec}k[x]$ is finite type??
Comment: The map $k[x]\rightarrow k(x)$ is not of finite type, $k(x)$ is not finitely generated $k[x]$-algebra.
Comment: sorry... but then is this map locally finte type???
Comment: Assume k is algebraically closed. Then every maximal ideal is given by $x=a$ for some $a\in k$. Then locally (for example around 0) $k[x]$ becomes $k[x]_{(x)}$. Moreover $k(x)$ is finitely generated over $k[x]_{(x)}$, you only need to add $1/x$.
Answer: A morphism is called of finite type if it is quasi-compact and locally of finite type. If $f_i : X_i \to Y$ are morphisms of finite type for $i \in I$, then clearly the induced morphism $f : \coprod_{i \in I} X_i \to Y$ is locally of finite type, but it is usually not of finite type when $I$ is infinite. So, for example, if $A$ is any commutative ring $ \neq 0$, then the canonical morphism $\coprod_{n \geq 0} \mathrm{Spec}(A) \to \mathrm{Spec}(A)$ locally of finite type, but it is not of finite type.
Comment: Why the downvote?


Where can I get a list of all the Views handler properties when building my own Views handler?

Question: I'm learning about Views handlers and need some clarification on how its built.
Looking through the Views Bulk Operations module as seen below. There are 2 IF statements that checks for base table name and revision table. Now my questions are:

When it says table, are they referencing to a table name in the database?
title, group, help, etc... where can I find a list of other parameters for this as seen below in the screen shot?
These fields show up when you click on the "add field" button in the View, but what dictates if it shows up in a content type or user type view?
Answer:
When it says table, are they referencing to a table name in the database?

Often yes, but not always. A Search API index View declares a "table", for example, but if Solr etc. integration is enabled, it won't necessarily be talking to a database/table. A lot of the time though, yes, a "table" tells Views the base table to select data from; the FROM part of the SQL query.

where can I find a list of other parameters for this as seen below in the screen shot?

The hook_views_data() API docs walk you through all the possibilities in comments and code.

These fields show up when you click on the "add field" button in the View, but what dictates if it shows up in a content type or user type view?

The loop in the code you've shown, combined with the condition immediately after. All entity types are looped over, and if their known Views data has a base and/or revision database table, a new field is added to provide operations (because VBO knows it can process those "tables").


Models e contextos não aparecem na box de Scaffold

Question: instalei VS community 2019, e mexendo em um projeto antigo, notei que as classes não ficam mais verdes como tendo referencia, e não consigo acessa-las clicando com o direito e indo em implementação, ou definição.

Além disto, observei que ao tentar criar um novo item via scaffold, as models e contextos não carregam para caixa de dialogo para serem selecionados.

Ja tentei rebuild, recriação do assembly.cs, do diretório .vs, mas sem sucesso
Alguém já passou por isto?
Comment: Nunca tive esse problema com o VS2019 desde de os primeiros testes. Já tentou fazer uma atualização/reinstalação?
Comment: Sem updates... na reinstalação, persistiu.
Answer: Não sei exatamente o que aconteceu. Precisei desinstalar a versão 2019, e voltar para a versão 2017 do Visual Studio Community.


How to collect logs with syslog-ng from www servers in dmz and send them to server behind firewall(NAT). Can Zabbix proxy solve this?

Question: I have several www servers in DMZ. My monitoring and log gathering server lays in my LAN. There is no comunication like
WWW server in DMZ ----> monitor server in LAN.
I can connect DMZ from my LAN
LAN --via proxy--> WWW server in DMZ.
I'm going to use syslog-ng. Problem is that syslog-ng work in client-server architecture and clients connect to server to send logs.
Is there a way to configure syslog-ng in some type passive mode that server (in my LAN) will connect to clients(DMZ) and collect logs?
EDIT:
I was reading about Zabbix proxy (zabbix can monitor logs) ... And teoreticaly relying on zabbix docs it will be posible to make my scenario work. Anybody can confirm that?
Comment: Is there any other host in the DMZ that can connect to monitor server?
Comment: no there isn't, LAN is not accessible from outside
Answer: What about tunneling, i.e. using Stunnel? For every DMZ server to be monitored:

Let the logserver start a tunnel to the DMZ server
Configure the DMZ server's syslog so that it connects to the tunnel and use it as additional destination

Note: this may work through firewall/NAT (as per your title) but not through proxy (as per your question content).
Answer: I don't know about syslog-ng, but I know that Splunk can be configured to collect and index log files from client systems periodically. Otherwise, the best I think you would be able to do is to setup a cron job on your log server to rsync the files to something like /var/log/clientN/*.log, and manually call logrotate on the client.
Comment: im looking for ready-made solution, i want avoid making logging system from scratch (rsync, email etc..)
Answer: This might not help, but I'll share how we get around this. Essentially we use multiple DMZs.

DMZ1 contains Internet-facing hosts and cannot talk back to the inside LAN.
DMZ2 is a segregated area (on the same firewall, different VLAN) that can talk to hosts in DMZ1 (both ways) but not the Internet. Some hosts in DMZ2 can also talk to certain hosts on the inside LAN.

Therefore hosts in DMZ1 that need to syslog centrally/scp files/send email reports do so via a management host in DMZ2. The information on the management host can then be picked up by a host on the inside.


Will 1000BASE-LX autonegotiate to work with 100BASE-FX

Question: We have existing equipment that uses 100BASE-FX (multi-mode fiber).  Will it work with 1000BASE-LX (also multi-mode) through autonegotiation?  Virtually everything I found on the web about autonegotiation was for copper interefaces.
This question is different from this which covers the fiber.
EDIT: 2/8/11: changed gigabit to -LX so both are 1300 nm.
Answer: The optical wavelengths of the two standards you mentioned, 100Base-FX and 1000Base-SX, are incompatible with each other.
100Base-FX uses a 1300 nm near-infrared (NIR) light wavelength, while 1000Base-SX uses a 770 to 860 nanometer, near infrared (NIR) light wavelength.
Answer: No, not by design, though it wouldn't be hard to design a NIC/module that could handle both but you'd need to let us know what equipment is at the gig end to allow us to help you on that.
Comment: I think what Chopper means to say is that equipment that supports 1000BaseSX doesn't necessarily support 100BaseFX, it's possible the equipment supports both, but certainly not all cards do.
Comment: No, the encoding is wildly different for a start.
Comment: Some (unknown) proprietary equipment.  My question is more about does the standard support autonegotiation?  Require it?


Let M be a finitely generated A-module and $φ : M → A^n$ a surjective homomorphism. Then $\ker φ$ is finitely generated

Question: Question 2.12 in Atiyah and MacDonald is similar to this:
Let M be a finitely generated A-module and $φ : M \longrightarrow A^n$
a surjective homomorphism. Show $\ker φ$ is finitely generated.
I like the solution posted here because it is short: https://users.math.msu.edu/users/ruiterj2/Math/Documents/Fall%202018/Commutative%20Algebra/Commutative%20Algebra%20Homework%202.pdf
Proof. Since $A^n$ is a free, and hence projective, A-module, the short exact sequence
$0 \longrightarrow \ker φ \longrightarrow M \longrightarrow A^n \longrightarrow 0$
splits, so $M \cong A^n ⊕ \ker φ$. Since $M$ and $A^n$ are finitely generated, so is $\ker φ$.
I understand the short exact sequence says the second function is 1-1 and the third, $φ$, is onto which we know from the problem statement, and this sequence is similar to the rank-nullity theorem - and the implication that $\ker φ$ is finitely generated, but how can $M \cong A^n ⊕ \ker φ$?
$\ker φ$ is a submodule of M so how can M be isomorphic to a direct sum of the free module $A^n$ and $\ker φ$
Comment: The sequence splits because $A^n$ is projective. See here https://en.wikipedia.org/wiki/Projective_module
Answer: Recall that the direct sum of two $A$-modules $P,Q$ is:
$$P\oplus Q=\{(p,q)\mid p\in P, q\in Q\}$$
So $A^n\oplus \ker\varphi$ can be thought of as the set of ordered pairs $(a,\phi)$, with $a\in A^n$ and $\phi\in\ker\varphi$.
Can you now see the isomorphism with $M$?
Comment: @EndreMoen no, you can think of it as saying $M$ is made up of copies of $A^n$, one for each $\phi\in\text{ker}\varphi$.
Comment: @EndreMoen Yes, since in that case $\varphi$ is an isomorphism.
Comment: Thanks @Luke Derry, is the elements isomorphic to $M$ in $A^n$ pairs $(a,ϕ)$ and those elements $b \in A^n$ that are not isomorphic mapped to $(b, x)$ where $x \notin ker( ϕ)$ ?
Comment: so if $kerφ = {0}$ so there is only 1 element then M is made up of just one copy of $A^n$ ?
Answer: You can either think of this as the genuine definition of $A^n$ being projective, or an equivalent condition.
As stated in the Wikipedia link provided in the comments, a module $P$ is projective if and only if every short exact sequence of the form
$$0 \rightarrow M \xrightarrow{f} N \xrightarrow{g} P \rightarrow 0$$
splits. That is, there exists a section
$$h:P \rightarrow N$$ such that
$g \circ h: P \rightarrow P = \text{Id}_P$.
Now, this does not yet give you exactly what you need. The property that $N \cong M \oplus P$ does follow from this, though. You should treat this deduction as an exercise. Try to construct a map $M \oplus P \rightarrow N$ (there is an obvious way to do this, given the existence of the section $h:P \rightarrow N$), and then show that this is an isomorphism.
In general, not all short exact sequences split; that's what is special here (and indeed, what is special about projective modules).
Comment: You want a map $\phi:M \oplus P \rightarrow N$. It needs to take a pair $(m,p)$ to some element $\phi(m,p) \in N$. You have two maps already, $f:M \rightarrow N$ and $h:P \rightarrow N$ (where the second of these is the section that you know exists because the short exact sequence splits).

Can you see how to combine those two maps into one map? I won't tell you what it is, but for a hint, perhaps people would denote it $(f + h):M \oplus P \rightarrow N$.

It then remains to show that this map is an isomorphism - you would use the respective properties of $f$ and $h$ to show this.
Comment: Thanks @Matt ! Is $f:M⊕N⟶P$ defined as  $f(0,n)↦p$ ?
Comment: No, that is not a map you're trying to define. You want a map $f:M \oplus P \rightarrow N$ :)
Comment: Thanks @Matt ! Is it $(f + h)(m, p) = f(m) +_N h(p) = n_1 + n_2$ ? And since $Im(h)$ is $\ker  φ$ in the example, the mapping becomes: $(f + h)(m, p) = f(m) +_N \ker(p) = n_1 + 0 = n_1$ ?
Comment: So then we have the SES $$0 \rightarrow M \xrightarrow{φ} A^n \xrightarrow{\ker φ} \ker φ \rightarrow 0$$ So $\ker φ$ is onto, and we need that $\ker φ$ is 1-1 to show it has an inverse. Then the isomorphism can be shown by showing the identity mapping $φ^-1(φ(a, p ) = (a,p)$, $a \in A^n, p \in ker φ$ ?


do the null space vectors need to be an orthogonal complement to the rowspace vector, isn't it enough to be linearly independent?

Question: say for example I have two 3 dimensional vectors that are linearly independent then I would be be able to form a 2 dimensional subspace which is a plane in the 3 dimension. the null space in my understanding is the missing vectors that are needed to represent the whole 3 dimension and conventionally is it formed by finding the orthogonal complement for both vectors in my subspace which is for sure linearly independent.
my question is, do the nullspace vectors need to be orthogonal, I am under the assumption that any vector that is linearly independent is good enough to represnt the whole dimension ? if that is not the case, why is it conventional for them to be orthogonal is it for simplicity?
Comment: This is a bit of a strange question. We don't speak of "a null space" or "a row space" in isolation -- these two terms are properties _of a particular matrix_, but you don't mention any matrix in your question at all, which makes me suspect you're confusing some terms.
Comment: @RaedTabani: There is no such thing as "the nullspace for a given vector space". Vector spaces (or subspaces) do not have nullspaces; only matrices (and perhaps linear transformations) do.
Comment: @Raed and you still haven't mentioned a matrix. Are you aware that "row space" and "null space" are, by definition, properties of a *matrix*?
Comment: Can you please state your definition of null space very carefully?
Comment: Certainly you can do the following: Take any two independent vectors; they span a plane. If you supplement your two original vectors by _any_ vector outside the plane, you get a basis for all of $\mathbb R^3$, and $\mathbb R^3$ will be a direct sum of your plane and the line spanned by the additional vector. The two spaces will just not be "row space" and "null space" of anything that is relevant for this operation.
Comment: I pictured the nullspace for a given Vector space as everything i.e all vectors that are not spanned by my row space, in my example the row space is a plane in 3d so it has to be all the parallel planes in  R3?
Answer: Your observations can be formalized as follows:
Let $A$ be a $m \times n$ matrix over a field $K$ (e.g. $K = \mathbb{R}$ for geometric intuition). For every $1 \leq i \leq m$ let $A_i = (A_{i1}, \dotsc, A_{in})^T \in K^n$ be the transposed of the $i$-th row of $A$ and let
$$
 R = \mathrm{span}_K\{A_1, \dotsc, A_m\} \subseteq K^n.
$$
For $x,y \in K^n$ let $x \cdot y = \sum_{i=1}^n x_i y_i$ and call $x$ and $y$ orthogonal if $x \cdot y = 0$. For any subspace $U \subseteq K^n$ let
$$
 U^\perp = \{x \in K^n \mid \text{$x \cdot y = 0$ for every $y \in U$}\}
$$
be the orthogonal complement of $U$.
Then $(A \cdot x)_i= \sum_{j=1}^n A_{ij} x_j$ for all $x \in K^n$ and $1 \leq i \leq m$. Therefore $x \in \ker A$ if and only if $\sum_{j=1}^n A_{ij} x_j = 0$ for every $1 \leq i \leq m$. Notice that $\sum_{j=1}^n A_{ij} x_j = A_i \cdot x$. Thus $x \in \ker A$ if and only if $A_i \cdot x = 0$ for every $1 \leq i \leq m$, i.e. if $x$ is orthogonal to each row of $A$. It then follows that $x$ is already orthogonal to every $y \in R$ because
$$
 \left( \sum_{i=1}^m \lambda_i A_i \right) \cdot x
 = \sum_{i=1}^m \lambda \underbrace{A_i \cdot x}_{=0}
 = 0.
$$
So we have $\ker A = R^\perp$. In this way is makes sense to say that the nullspace $\ker A$ is precisely the orthogonal complement $R^\perp$ of the subspace $R$ spanned by the rows of $A$.
(These who know the dual space will recognize this as a special case of the equality $\mathrm{im}(f^*) = \ker(f)^\perp$ where $f \colon V \to W$ is some linear map and $f^* \colon W^* \to V^*$ is the induced linear map.)


Regra PREG MATCH apropriada

Question: Criei um loop que mostra todos os mêses do ano com o código seguinte:
for($i = 1;$i <= 12;$i++){

}

então criei uma variável $_GET que receberia uma regra como a seguinte: 1,2,3,4,5,6,7,8,9,10,11,12
Esta é a variável $_GET:
$listaMesesPagos = isset($_GET["mesespg"]) ? $_GET["mesespg"] : null;$listaMesesPagos = is_string($listaMesesPagos) ? $listaMesesPagos : null;

O objetivo dessa variável $_GET é mostrar os meses que foram pagos pela pessoa X. Por exemplo se a pessoa X pagou a sua mensalidade nos mêses: Janeiro, Fevereiro e Março (1,2,3). Então a $_GET receberia os valores: 1,2 e 3 na seguinte maneira: http://localhost/pagina.php?mesespg=1,2,3 que mais tarde seria jogada em uma ARRAY php através do explode() ficando assim:
$arrayMeses = explode(",",$listaMesesPagos);

Mas para usar o explode() é necessário primeiro saber se a variável $_GET recebeu na seguinte regra: n,n,n que neste exemplo é: 1,2,3 por isso usei a preg_match com o $pattern a seguir:

$regraDaListaDosMeses = '/^([0-9]{1,2}\,{1}){1,11}([0-9]){0,1}$/';

Dessa forma, antes de usar o explode o php verifica se a variável $_GET está nesta regra acima: (1,2,3). Caso esteja o PHP jogará os números para uma array parecida com esta: array(1,2,3); caso contrário o php criará uma array vazia para evitar erros como está no código a seguir:

if(preg_match($regraDaListaDosMeses, $listaMesesPagos) == true){
$arrayMeses = explode(",",$listaMesesPagos);
}else{
    $arrayMeses = array();
}

Então o loop for() checaria se os mes atual está na array $arrayMeses caso não mostraria que o mês está pendente. Segue o código:
            for($i = 1;$i <= 12;$i++){
            /*mês pago*/if(in_array($i, $arrayMeses)){/*CÓDIGO AQUI*/}
            /*mês não pago*/else{/*CÓDIGO AQUI*/}
        }

Agora, com base nessa "delicada" explicação. :) vamos ao problema que está na regra do preg_match.
vejam, na regra: /^([0-9]{1,2}\,{1}){1,11}([0-9]){0,1}$/. Esta não está apropriada. Eu quero uma regra que verifica que, por exemplo, os seguintes carácteres estão corretos: 1,2,3;1,2,3,;1,2,3,4,5,6,7,8,9,10,11,12.
Podem me ajudar?
Answer: Um número inteiro entre 1 e 12:
[1-9]|1[0-2]

Agrupado:
(?:[1-9]|1[0-2])

Seguido por uma vírgula ou o fim do texto ($):
(?:[1-9]|1[0-2])(?:,|$)

Repetir 0 a 12 vezes:
(?:(?:[1-9]|1[0-2])(?:,|$)){0,12}

Desde o início (^) até o final do texto ($):
^(?:(?:[1-9]|1[0-2])(?:,|$)){0,12}$

Então:
$regraDaListaDosMeses = '/^(?:(?:[1-9]|1[0-2])(?:,|$)){0,12}$/';

Demo no regex101.com

Alternativamente, você pode filtrar apenas meses válidos do array usando preg_grep():
$listaMesesPagos = '1,@@@,4,,7,128,9,ooo10,11,';
$arrayMeses = explode( ',', $listaMesesPagos);

$regraMes = '/^(?:[1-9]|1[0-2])$/';

$arrayMeses = preg_grep( $regraMes, $arrayMeses);

var_export($arrayMeses);

Resultado:
array (
  0 => '1',
  2 => '4',
  4 => '7',
  6 => '9',
  8 => '11',
)

Ou sem expressões regulares, usando array_filter().

Regra PREG MATCH apropriada


writing/reading a single variable in applescript

Question: I'm just starting with applescript in xcode and currently have an app that asks for a folder location, then creates a folder structure.
on buttonClick_(sender)
    set theLocation to choose folder with prompt "Where to save your project?"
    tell application "Finder"
        set newFolder to make new folder at theLocation with properties {name:(theTextField's stringValue() as string)}
        set fontsFolder to make new folder at newFolder with properties {name:"fonts"}
        set jpgFolder to make new folder at newFolder with properties {name:"jpg-pdf"}
        set mainFolder to make new folder at newFolder with properties {name:"main"}
        set printFolder to make new folder at mainFolder with properties {name:"• for printer"}
        set refverFolder to make new folder at newFolder with properties {name:"ref_ver"}
        set supportFolder to make new folder at newFolder with properties {name:"support"}
    end tell
    quit
end buttonClick_

Now I'm trying to have the app take "theLocation" folder alias and save it, so the next time the app launches it automatically chooses that folder as the save location without having to add it. I understand the logic that will go into it, but I can't figure out how to store/read information. I've tried tutorials on writing to the info.plist, but none of them have worked. Am I missing a basic piece of info on how applescript works?
Thanks
** Edit
script New_ProjectAppDelegate
property parent : class "NSObject"

property theTextField : missing value
property theLocation : ""

on applicationWillFinishLaunching_(aNotification)
    tell standardUserDefaults() of current application's NSUserDefaults
        registerDefaults_({theLocation:theLocation}) -- register the starting user default key:value items
        set theLocation to objectForKey_("theLocation") as text -- read any previously saved items (which will update the values)
    end tell
end applicationWillFinishLaunching_

on buttonClick_(sender)
    if theLocation is "" then
        set theLocation to choose folder with prompt "Where to save your project?"
        tell standardUserDefaults() of current application's NSUserDefaults
            setObject_forKey_(theLocation, "theLocation") -- update the default items
        end tell
    else
        set theLocation to theLocation as text
        --display dialog theLocation as text
    end if
    tell application "Finder"
        set newFolder to make new folder at theLocation with properties {name:(theTextField's stringValue() as string)}
        set fontsFolder to make new folder at newFolder with properties {name:"fonts"}
        set jpgFolder to make new folder at newFolder with properties {name:"jpg-pdf"}
        set mainFolder to make new folder at newFolder with properties {name:"main"}
        set printFolder to make new folder at mainFolder with properties {name:"• for printer"}
        set refverFolder to make new folder at newFolder with properties {name:"ref_ver"}
        set supportFolder to make new folder at newFolder with properties {name:"support"}
    end tell
    quit
end buttonClick_

on applicationShouldTerminate_(sender)
    tell standardUserDefaults() of current application's NSUserDefaults
        setObject_forKey_(theLocation, "theLocation") -- update the default items
    end tell
    return current application's NSTerminateNow
end applicationShouldTerminate_

end script
Comment: I am a newbie to apple scripts. Can you tell me how can I edit info.plist.I want to edit some properties in info.plist file with my values.Any help will be appreciated.
Answer: Properties are not persistent in Xcode scripts, but you can utilize the user defaults system.  To use the defaults, you register some initial values when your application starts up, then read from the defaults (which will overwrite the registered values if they have been saved before), and when your application quits save the new values - for example:
property theLocation : "" -- this will be the (text) folder path

on applicationWillFinishLaunching_(aNotification)
    tell standardUserDefaults() of current application's NSUserDefaults
        registerDefaults_({theLocation:theLocation}) -- register the starting user default key:value items
        set theLocation to objectForKey_("theLocation") as text -- read any previously saved items (which will update the values)
    end tell
    -- other initialization stuff
end applicationWillFinishLaunching_

on buttonClick_(sender)
    if theLocation is "" then
        set theLocation to choose folder with prompt "Where to save your project?"
        set theLocation to theLocation as text
    end if
    -- display dialog theLocation
    tell application "Finder"
        -- create folder structure
    end tell
    quit
end buttonClick_

on applicationShouldTerminate_(sender)
    tell standardUserDefaults() of current application's NSUserDefaults
        setObject_forKey_(theLocation, "theLocation") -- update the default items
    end tell
    return current application's NSTerminateNow
end applicationShouldTerminate_

Comment: This is exactly the direction I'm looking for, but the application is still not recognizing theLocation as having a default value when I open it. In order to use the NSUserDefaults do I have to initialize it anywhere or import a class? I'll add my entire code to the original post.
Comment: NSUserDefaults only supports objects that can be represented in a property list, so for an alias you will need to create an NSData object to hold it, or (easier in this case, I think) coerce the folder path to text.  I've updated the buttonClick_ handler in my example to show the path coercion (you will also see plist errors like this in the debug console).
Comment: I see it now! I was only setting the alias to text if the location already existed in the defaults, which wasn't doing anything, rather than setting it to text after the 'choose folder' was issued. It is working now, and I thank you for the help.
Answer: You can define a property at the beginning of your script, which allows you to store information even after the script quits...
property theLocation : null
if theLocation is null then set theLocation to (choose folder with prompt "Where to save your project?"
...

The script will store the alias in "theLocation" for future use. However, saving or recompiling the script will reset the property back to its original value.


Command "Print All Lines Starting With"

Question: I am looking for a perl command where lines starting with a string are printed. For example, if I wanted to print all lines starting with "1234", what would that command look like? Sed? Awk? Grep?
Answer: perl -ne 'print if /^1234/'

or
sed -ne '/^1234/p'

or
awk '/^1234/'

or
grep '^1234'

or
ruby -ne 'print if /^1234/'

or even
python -c 'import fileinput;print "\n".join([l for l in fileinput.input() if l.startswith("1234")])'

Comment: oh, python is so-o-o-o beautiful
Comment: `python -c 'import sys; [sys.stdout.write(l) for l in sys.stdin if l.startswith("1234")]'` -- maybe slightly less pathological, but clearly Python is not meant to replace grep  :)
Comment: Thanks for the improvement, @Eevee.  Of course using sys.stdin doesn't let you specify a list of files at the end of the command line the way the rest of the entries in my answer do... :)  But yes, this is definitely not Python's niche.
Answer: perl -ne'print if /^1234/' file

But most people would use grep.
grep ^1234 file

Or on Windows
findstr /r ^1234 file

Answer: For completion:
sed -ne '/^1234/p' somefile
awk '/^1234/{print}' somefile
grep '^1234' somefile

Comment: `{print}` is the default action for awk, so you all you need is the `/^1234/` part.

Command "Print All Lines Starting With"


Bayesian inference - Calculating the prior distribution of the parameter in the Bernouli distribution from a series of bernouli proccesses

Question: What I have are n different time series of bernouli processes of varying lengths, taking the values of 0 or 1. What I would like to do is to use Bayesian inference to calculate, for one of these series, the posterior distribution of the parameter p that drives the proccess. To do this I first need the prior distribution of the Bernouli paramter p which I gather should be available to me through all the n time series that I have. But how do I do this in practice?
To find the mean of the prior distribution of p seems straight forward enough, just count the total number of occurances in all times series and divide by the total number of trials. The variance on the other hand seems a bit less clear to me. I imagine I could take sample means (i.e. frequentist maximum likelihood estimator of p) from each of the n processes and then compute a sampl variance from all of these, is that appropriate? Intuitively it feels not quite right to me since these estimators will themselves not be very indicative of the true value at all (this is in fact the whole reason I am trying to use Bayesian inference here) since they will likely not the long enough. For example I may have one of the n processes be of length ~50 with the true p being something like 0.2.
Is there any way to adress this issue or is the approach I mentioned the best we can accomplish? Will the prior value of the variance affect the results I get in my Bayesian inference later a lot, or is it not so impactful?
Thank you!
Edit: Adding my comment to Tim's answer here to clarify the goal:
I think I should clarify that I do not postulate that all of these Bernoulli Processes have the same p. In fact, I am assuming that they have different values of p. My goal is to find the distribution of p for one specific process (to make things clear we can say that the data available from this process was not used to find the prior). To this end, I need a prior distribution of p, and I'm thinking this one should be found via the other available processes. Does my question make more sense framed like this?
We could for example say that the possible values of p are 0.3, 0.5, and 0.7 all with the same probabilities. If this were the case then we would use that as the prior and then after some observations become more confident that we are dealing with one of them rather than the others. So it is this (unknown) prior distribution that I need to find
Comment: If you believe that many or all of your currently available data may be relevant for continued experimentation, then you can use whatever parts of them you believe to be relevant and with whatever weights you think are appropriate to arrive at a prior distribution for pending experimentation.  You are entitled to choose whatever prior you trust most. Of course, you will get better results in the end if your trust is wisely placed. [If you are _truly clueless_ about the relevance of previous data, then it may be best to use a flat or uninformative prior.]
Answer: Prior is something you choose prior to looking at your data. So if you want to use a Bayesian model to find the posterior for $p$ given your data, you cannot use the same data to choose prior because you would be using this data twice. First, it wouldn't make much sense. If you would be able to estimate the (prior) distribution for $p$ from the data, then your problem would be already solved, since your aim was to calculate the distribution of $p$. Second, if you used the data to get the prior and then used it for Bayesian inference, you would end up with incorrect (too narrow) uncertainty estimates.
Consider simple example of beta-binomial model. In $n$ trials you observed $k$ successes, this corresponds to the maximum likelihhod estimate for the probability of success equal to $k/n$. Let's say that you used this data to construct a Beta prior for the probability of success $p$.
$$
p \sim \mathcal{Beta}(\alpha, \beta)
$$
with pseudocounts $\alpha = k$ and $\beta = n - k$ corresponding to $E[p] = \alpha / (\alpha + \beta) = k/n$. Given that beta distribution is a conjugate prior for binomial likelihood, we instantly know that the posterior distribution for $p$ is
$$
p|k,n \sim \mathcal{Beta}(\alpha + k, \beta + n - k)
$$
It is the same distribution as the prior, but counting each datapoint twice. With "two times more data" the posterior would be narrower than the prior, since "more data" would make it more precise. You would be cheating yourself.
Prior should be based on what you know about the parameter before collecting your data. So it can be based on theory, some other experiments described in the literature, your wild guess, etc, but not the data.
Comment: Hi, thank you for the answer. I think I should clarify that I do not postulate that all of these Bernoulli Processes have the same p. In fact, I am assuming that they have different values of p. My goal is to find the distribution of p for one specific process (to make things clear we can say that the data available from this process was not used to find the prior). To this end, I need a prior distribution of p, and I'm thinking this one should be found via the other available processes. Does my question make more sense framed like this? I am
Comment: We could for example say that the possible values of p are 0.3, 0.5, and 0.7 all with the same probabilities. If this were the case then we would use this as the prior and then after some observations become more confident that we are dealing with one of them rather than the others.

So it is this (unknown) propr distribution that I need to find
Comment: Difficult to see how (discrete) dist'n with .3, .5, .7 equally likely leads to useful prior. Do you really mean 0.301, 0.498, and 0.705 are _impossible_ values of $p?$ // Maybe you're thinking of something like $\mathsf{Beta}(4,4),$ which puts probability mostly in $(,2, .8).$ // One reason for using (continuous) beta priors with binomial likelihoods is that computation of posterior dist'n becomes trivial. [Mybe google 'conjugate prior'.]
Comment: I believe the distribution is continuous, this was simply an example to demonstrate. I want to find a proper continuous prior for this situation. My goal would be to estimate the prior mean and variance from my available data, and then find the corresponding beta parameters from that.
Answer: Following on from @Tim's (+1) Answer, it is OK to use prior opinion or data to arrive at
what you believe is a reasonable prior distribution for a proposed new experiment.
Beta distributions have support $(0,1),$ so they are
natural prior distributions for Bernoulli success
probability $p.$
Suppose you begin with no idea at all about the success
probability. Then you might use a flat or non-informative
prior distribution such as $\mathsf{Beta}(1,1)\equiv\mathsf{Unif}(0,1)$ or the Jeffreys prior $\mathsf{Beta}(.5, .5).$
Suppose a preliminary experiment showed $7$ successes in $20$
trials. Then by Bayes' Theorem the posterior distribution from the uniform prior and that small experiment would be $\mathsf{Beta}(1+7,\, 1+13)\equiv\mathsf{Beta}(8,14).$ This (preliminary) posterior has mean $\mu = $ $8/(8+14) = $ $8/22 =  0.3636$ and it puts 95% probability in the (Bayesian credible) interval $(0.181, 0.570).$ as computed in R below.
<code>qbeta(c(.025,.975), 8, 14)
[1] 0.1810716 0.5696755
</code>
Subsequently, if you decide to do more extensive experimentation
to obtain results from $500$ additional trials, then you can use the
posterior distribution from the preliminary experiment
as the prior distribution for the more extensive one (provided,
of course, you are still using the same--or very similar--coin or process).
If you get $x$ successes in these $n = 500$ additional trials, then your
updated posterior distribution is
$\mathsf{Beta}(8+x, 14 + n - x).$ and you can use R
as above to get a 95% Bayesian credible interval based
on all the information you have.


swift dictionary nested array manipulation - cannot mutate nested array inside dictionary

Question: var dict = ["alpha": ["a", "b", "c", "d"]]
// output : ["alpha": ["a", "b", "c", "d"]]

var alphaList = dict["alpha"]
// output : {["a", "b", "c", "d"]

alphaList?.removeAtIndex(1)
// output : {Some "b"}

alphaList
// output : {["a", "c", "d"]}

dict
// output : ["alpha": ["a", "b", "c", "d"]]

Why is 'dict' not altered? Is it because 'alphaList' is a copy of the array and not the actual array inside the dictionary? Can anyone point me where in Swift language documentation I can find this information?
What is the correct/functional way to manipulate values (of complex type) of a dictionary?
Comment: It looks like when getting a reference to an array inside a dictionary it is in fact a copy/different instance -- When playing in a playground i got

`var d = ["t": ["a", "b", "c", "d"]] // ["t": ["a", "b", "c", "d"]]`

`var a = d["t"] // {["a", "b", "c", "d"]}`

`a?.removeAtIndex(1) // {Some "b"}`

`a // {["a", "c", "d"]}`

`d // ["t": ["a", "b", "c", "d"]]`

`unsafeAddressOf(a!) // "UnsafePointer(0x7FF8C1C088C0)"`

`unsafeAddressOf(d["t"]!) // "UnsafePointer(0x7FF8C1F00990)"`

`unsafeAddressOf(d) // "UnsafePointer(0x7FF8C1C00120)"`
Answer: Good question yes it creates the copy of the value in your case the value is Array
    var alphaList = dict["alpha"]
/* which is the copy of original array
changing it will change the local array alphaList as you can see by your output */
    output : {Some "b"}

In order to get the original array directly use
dict["alpha"]?.removeAtIndex(1)

Or update it using the key
alphaList?.removeAtIndex(1)
dict["alpha"] = alphaList

Apple : Assignment and Copy Behavior for Strings, Arrays, and Dictionaries
Swift's String, Array, and Dictionary types are implemented as structures. This means that strings, arrays, and dictionaries are copied when they are assigned to a new constant or variable, or when they are passed to a function or method.
This behavior is different from NSString, NSArray, and NSDictionary in Foundation, which are implemented as classes, not structures. NSString, NSArray, and NSDictionary instances are always assigned and passed around as a reference to an existing instance, rather than as a copy. "
Answer: Swift arrays and dictionaries are value (struct) times. There are only one reference to such instance. While NSArray and NSDictonary are class type and there could be multiple references to such instances.
The statement var alphaList = dict["alpha"] makes copy for ["a", "b", "c", "d"], so you cannot change the original array.
If you want to mutate original "alpha" you have to use dict as root variable:
dict["alpha"]?.removeAtIndex(1)

Answer: You are right, alphaList is a copy, hence any change you make on it is local and does not affect the original array. The documentation describes that in Structures and Enumerations Are Value Types.
The only way to make changes to an array after extracting it from somewhere else is by passing the array to a function by reference, using the inout parameter modifier:
func modifyAlphaList(inout alphaList: [String]?) {
    alphaList?.removeAtIndex(1)
}

modifyAlphaList(&dict["alpha"])
dict // (.0 "alpha", ["a", "c", "d"])

Answer: This link should help
https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-XID_150
Swift's String, Array, and Dictionary types are implemented as structures. This means that strings, arrays, and dictionaries are copied when they are assigned to a new constant or variable, or when they are passed to a function or method.


Matroid isomorphisms and self-duality

Question: The uniform matroid $U(n,k)$ has $n$ elements and all $k$-element subsets are bases. I was under the impression that $U(2k,k)$ is self-dual, that is, it is isomorphic to its dual in which bases are replaced by their complement.
However, the usual definition of matroid isomorphism seems to be the following:

Definition. Two matroid $(X_1,I_1)$ and $(X_2,I_2)$ are isomorpic, if there exists a bijection $X_1\to X_2$ that induces a bijection $I_1\to I_2$.

It is not hard to see, that this defintion cannot provide an isomorphism between, e.g. $U(4,2)$ and its dual. No permutation of the elements of the matroid can induce the following map on the characteristic vectors of the bases:
$$0011\longleftrightarrow 1100,\qquad 1010\longleftrightarrow 0101,\qquad 1001\longleftrightarrow 0110.$$
What now? Is $U(4,2)$ not self-dual? Or is there a different version of matroid isomorphism, e.g. the following:

Definition. Two matroids $(X_1,I_1)$ and $(X_2,I_2)$ are isomorphic if their lattices of independent sets are isomorphic as lattices.

And if so, which one is the "standard definition"?
Comment: Your second definition does not handle loops or parallel elements correctly.
Answer: I think you are hoping that the map that does the dualizing already is the isomorphism if a matroid is self dual. That doesn't need to be the case. $U(2k,k)$ and its dual are isomorphic through the identity map but that is a different map than the one that maps each element in $U(2k,k)$ to its dual.

Matroid isomorphisms and self-duality


Integrating factor for non-exact ODE $y(1+2x^2+2y^2)\; \mathrm dx + x(1-2x^2-2y^2)\; \mathrm dy=0,$

Question: If we have a non-exact ODE, then to convert it to an exact ODE we multiply the ODE with an integrating factor $\mu(x,y)$.
Lets us say we have the following ODE: $$M(x,y)dx+N(x,y)dy=0,$$ and let us denote $\frac{\partial M(x,y)}{\partial y}=M_y$ and $\frac{\partial N(x,y)}{\partial x}=N_x$.
Since the ODE is not exact, $M_y-M_x =f(x,y)\neq 0$.
We know that if $\frac{f(x,y)}{N(x,y)}$ depends only on $x$ then $e^{\int\frac{f(x,y)}{N(x,y)}dx}$ is the integrating factor of the ODE and if $\frac{f(x,y)}{M(x,y)}$ only depends on $y,$ then $e^{\int\frac{f(x,y)}{-M(x,y)}dy}$ is the integrating factor.
But what is the integrating factor of the ODE when both $\frac{f(x,y)}{M(x,y)}$ and $\frac{f(x,y)}{N(x,y)}$ are functions of $x$ and $y$ and neither of them are independent of any variable?
For example, in the following ODE: $$y(1+2x^2+2y^2)\; \mathrm dx + x(1-2x^2-2y^2)\; \mathrm dy=0,$$ $M_y-N_x=f(x,y)=8x^2+8y^2$  and neither of $\frac{f(x,y)}{M(x,y)}$ and $\frac{f(x,y)}{N(x,y)}$ are independent of any variable i.e both of them depend on $x$ and $y$ both.
So in such cases how do we determine the integrating factor?
Answer: I believe there is no general procedure to find integrating factors in every case. There are some special cases where it is possible as you commented. I'm gonna point out another one:
If
$$
\frac{N_x-M_y}{xM-yN} = g(xy)
$$
for some function $g$ of one variable (here $g(xy)$ means that the function $g$ is evaluated in the number $xy$. I mention this because often people think that I missed a "$,$" separating the varaibles), and if $f$ is a primitive of $g$, meaning that $f'(t)=g(t)$ for all $t$, then $\mu=e^{f(xy)}$ is an integrating factor (you can prove it by yourself).
So, in this case, you obtain
$$
\frac{N_x-M_y}{xM-yN} = -\frac{2}{xy},
$$
and we can take $g(t)=-2/t$. A primitive for $g$ is given by $f(t)=-2\ln|t|=\ln (t^{-2})$, and hence
$$
\mu = e^{\ln((xy)^{-2})} = \frac{1}{x^2y^2}
$$
is an integrating factor.
Answer: Similar to this post that I answered, in this problem, the integration factor is in the form of $x^ay^b$,
$$x^ay^b\cdot y(1+2x^2+2y^2)\; dx + x^ay^b\cdot x(1-2x^2-2y^2)\; dy=0,$$
Take partial derivative $M_y=N_x$ and simplify
$$(b+1)(1+2x^2+2y^2)+4y^2=(a+1)(1-2x^2-2y^2)-4x^2$$
Compare coefficient, the constant term should be equal, hence $a=b$, and we get
$$(a+1)(4x^2+4y^2)=-4x^2-4y^2$$
hence, $a=-2$, and we get the integration factor
$$\boxed{\mu=\frac1{x^2y^2}}$$
Answer: Let's say your equation $P(x,y)dx +Q(x,y)dy=0$ is not exact, but when you multiply by a function $\mu(x,y)\neq 0$ it is.
$$\mu P\,dx + \mu Q\,dy = M\,dx +N\,dy=0$$
So
$$M_y = \mu_y P + \mu P_y\qquad N_x=\mu_x Q+\mu Q_x$$
Then
$$M_y-N_x= (P_y-Q_x)\mu+\mu_y P-\mu_x Q = 0\implies \boxed{\mu+\frac{P}{P_y-Q_x}\mu_y-\frac{Q}{P_y-Q_x}\mu_x=0}$$
(I think the boxed equation is a very important equation). Replacing the functions given
$$\mu+\frac{y(1+2x^2+2y^2)}{8(x^2+y^2)}\mu_y-\frac{x(1-2x^2-2y^2)}{8(x^2+y^2)}\mu_x=0$$
Now you got a PDE for the function $\mu$. But we just need one. Let's compare the terms
$$(1)\quad \frac{y(1+2x^2+2y^2)}{8(x^2+y^2)} \qquad,\qquad (2)\quad \frac{x(1-2x^2-2y^2)}{8(x^2+y^2)}$$
it would be beautiful to amplify (1) by $x$ and (2) by $y$ because the crossed terms $xy$ will cancel and the $x^2+y^2$ will too. So let's choose the family $\mu(x,y)= r(xy)$, then
$$\mu_x=yr'\quad , \quad \mu_y=xr'$$
Remember that $r'$ means $r$ derived respect its argument ($xy$). In the PDE
$$r+\frac{xy(1+2x^2+2y^2)-xy(1-2x^2-2y^2)}{8(x^2+y^2)}r'=0\implies r+\frac{xy}{2}r'=0$$
This means
$$\frac{r'}{r}=-\frac{2}{xy}$$
integrating respect the argument of $r$ you get
$$\ln r = -2\ln xy+c$$
Choose one function to solve the problem. Let's choose $r(xy)=\frac{1}{x^2y^2}=\mu(x,y)$
The exact equation is
$$\left(\frac{1}{x^2y}+\frac{2}{y}+\frac{2y}{x^2}\right) dx + \left(\frac{1}{xy^2}-\frac{2x}{y^2}-\frac{2}{x}\right) dy = 0$$
Finally the potential function is
$$\phi(x,y)=-\frac{1}{xy}+\frac{2x}{y}-\frac{2y}{x}=\frac{2x^2-2y^2-1}{xy}=c$$
Answer: $$y(1+2x^2+2y^2)\; \mathrm dx + x(1-2x^2-2y^2)\; \mathrm dy=0,$$
$$2(x^2+y^2)(ydx-xdy) + xdy+ydx=0$$
$$2(x^2+y^2)(ydx-xdy) + d(xy)=0$$
It's easy to see that $\mu =\dfrac 1 {x^2y^2}$ will do the job.
$$2(x^2+y^2)d \left( \dfrac  xy\right) + \dfrac {d(xy)}{y^2}=0$$
$$2\left(1+\dfrac {y^2}{x^2}\right)d \left( \dfrac  xy\right) + \dfrac {d(xy)}{x^2y^2}=0$$
THe DE is separable.


Readonly form field in edit view - Flask-Admin

Question: I tried to set a form field as readonly just for the edit view in a Flask-Admin application. Following the answers to this question I know that if I have this
class MyView(ModelView):
    form_widget_args = {
        'title': {
            'readonly': True
        }
    }

I can set a form field as readonly, but this is applied to both create and edit views. How can I apply an argument to the edit view only?
Answer: A pure python solution could be using the on_form_prefill callback function that admin provides, and it's only run in the edit view. You wouldn't need form_widget_args in that case.
You could have something like this to edit the form dynamically, making that field read only:
class MyView(ModelView):
  def on_form_prefill(self, form, id):
    form.title.render_kw = {'readonly': True}

Answer: Another way to do it is to use form_edit_rules and form_create_rules. Display the fields you only want in create view, and add the field you want to be displayed in edit view and make it read-only
form_create_rules = (
    'col1', 'col2', 'col3')
form_edit_rules = (
    'col1', 'col2', 'col3', 'col4')

form_widget_args = {
    'col4': {
        'disabled': True
    }
}

Comment: can col4 be included in create rules? read only only in edit mode
Answer: I would do a little workaround for this. Create a custom edit template and add it to your class. The standard edit template you find in the flask repository on github (standard edit template)
class MyView(ModelView):
    edit_template = 'my_custom_edit_template.html'

And in your custom edit template make a javascript function which disables your element. So it's only disabled in edit view and not in the create view.
{% block tail %}
    {{ super() }}
    {{ lib.form_js() }}

{% endblock %}

It's maybe not the best solution but it works for me. I think it should also be possible to change the jinja2 template to directly disable the filed. I tried: {{ form.myfield_id(disabled=True) }}  but then it renders my field twice... but my first approach works.
Answer: I think you can do it by checking the value you are trying to edit in the method that handles edit.
For eg:
You are trying to edit a value with id 1, then in the views py file you can check for the that value and add the code.
def editdata(id=None):
    if id:
        form.title.render_kw = {'readonly': True}
#rest of the code


Curvature of a non-compact complete surface

Question: Assume $\Sigma$ is a non compact, complete surface. Assume the integral $$\int_{\Sigma}K$$ is convergent, where K is the Gauss curvature of $\Sigma$. Is it always true that $$\frac{1}{2\pi}\int_{\Sigma}K$$ is an integer?
Answer: No. Start with a one-nappe circular cone. Cut off the tip and replace with a subset of a sphere, resulting in what is now a $C^1$ infinite surface. Smooth near the circle where they join, so the result is at least $C^2.$ The result has zero curvature except near the spherical part. Since we did not specify the central angle of the cone, we get whatever we like in the way of total Gauss curvature, up to an effective maximum given by a hemisphere and an infinite cylinder.
Comment: Better make it $C^2$ so that $K$ makes sense. This smoothing idea also shows how to "fix" Gauss-Bonnet when you have some cone points in a compact surface.
Comment: Do you know where I could find more information about a $C^1$ infinite surface?
Comment: Im sorry so this $C^1$ infinite surface is similar to what you would get by intersecting a sphere with two parallel planes? Or is that incorrect?
Comment: @user77680, what is your actual background?
Comment: @user, it resembles a badminton birdie, where you let the part with the feathers just keep going and going.
Comment: Double bachelors physics and pure math and Masters in applied math but I've never talked about any of these things.
Comment: ohhhhhh ok I see what you are saying now replace what was cut off with the subset of the sphere. That visual helped a lot. Thank you.
Answer: Better luck on this for complete minimal surfaces. In that case, $K$ can't change sign and complex variable theory tells you the Gauss map can't miss many values.
Answer: I believe that Alexander horned sphere is a good example for as a visual representation for as an answer.
Comment: Could you add some more details to your answer? Else it is best to leave this as a comment.
Answer: Sure, I am going to have to go with the contrapositive on this one: $\int{\Sigma}$div$\gamma$$\nu$ = $\int{\partial\Sigma}< \nu, N> \sigma$ #. In other words Stokes theorem.


Can I use hook_css_alter inside of hook_form_alter

Question: Can I use hook_css_alter inside of hook_form_alter. I need to unset a css file only on certain forms and only to non-admins. This is what I have but it doesn't work.
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\UserSession;

function mymodule_form_alter(array &$form, FormStateInterface $form_state,  $form_id) {
  $user = \Drupal::currentUser()->getRoles();
    if(in_array("administrator", $user)) {

    function mymodule_css_alter(&$css) {
      unset($css['core/themes/stable/css/system/components/tabledrag.module.css']);
    }
  }
}

Comment: Short answer: no. You cannot do this.
Comment: Longer answer...that inner function only exists within the scope of the form alter function (or even the if block, is that even syntactically allowed in php?), so it's a "no" at the language level before Drupal gets involved. Finding some context from the request in a global hook_css_alter that lets you identify the page and unset accordingly would be an option, but I suspect there'll be something more elegant in D8
Answer: You can't use a hook function inside of a hook function. If you are in the css alter hook you have to get the information you need from where you are in code. For example you could check for the route name of the form because the current route match is available in a service. So this could work (not tested):
function mymodule_css_alter(&$css) {
  $user = \Drupal::currentUser()->getRoles();
  $route = \Drupal::service('current_route_match')->getRouteName();
  if (in_array('administrator', $user) && $route == 'entity.node.edit_form') {
    ...

Comment: Thanks, I tried this but it didn't work.
Answer: Yo unset CSS files on certain pages for certain users, you could do something like this:
function hook_css_alter(&$css, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
   if (\Drupal::routeMatch()->getRouteName() == 'form.route') {
    $roles = \Drupal::currentUser()->getRoles();
    if(!in_array("administrator", $roles)){
       unset($css['file.css']);
    }
  }
}

Hope this helps
Comment: I suppose you are doing something wrong then... This should definitely work
Comment: Thanks, I tried this but it didn't work.


Order of cyclic subgroup

Question: This should be easy, but I keep getting stuck on it.
Suppose $D$ is a cyclic group of order $m$ (written additively) and then  let $D[n] = \{x \in D : nx = 0\}$.
I'm trying to show $D[n]$ has order $d$, where $d = hcf(m,n)$. I can see that $D[n]$ should be generated by $\frac{m}{d}$ and this has the required order, but how to show that this is the generator? I'm sure I need to use Bezouts lemma somewhere but can't quite see it.
Thanks
Answer: You don't need Bézout's lemma. Let $g$ be a generator of $D$. Then
$$k\cdot g \in D[n] \iff (nk)\cdot g = 0 \iff m\mid nk.$$
Now just write $n = \nu d$ and $m = \mu d$ and you see that
$$m\mid nk \iff \mu \mid \nu k \iff \mu \mid k,$$
since $\gcd(\mu,\nu) = 1$.

Order of cyclic subgroup


Is there a name for a scatter plot which compares predicted vs observed values?

Question: I have a scatter plot which compares predicted vs observed values. What is the appropriate name for this type of plot?
To elaborate, I have a set of measurements for a specific engineering quantity at several moments in time. I also have a model which predicts the value of that quantity at those same moments in time. To illustrate the quality of the model, I am plotting each (prediction, measurement) pair as a point in a scatter plot, with the prediction on the $X$ axis and the measurement on the $Y$ axis. I'm also drawing the line $y=x$ on the chart as a reference. (Points on that line represent perfect agreement between prediction and measurement.)
I have repeatedly heard this type of plot referred to as a "Q-Q plot". According to the definition of a Q-Q plot given on Wikipedia, this is technically incorrect because I'm not plotting quantiles. I am trying to determine if popular usage of the term "Q-Q plot" in situations like mine has made that the de facto name for this type of plot. If not, then what is an appropriate name for this type of plot?
Answer: A scatter plot of observed and predicted is emphatically not a quantile-quantile plot (which defines a never-decreasing sequence of points).
People often just talk informally in terms of what is on which axis, say observed versus or against predicted or fitted (e.g. Chambers et al. 1983).
I'd suggest that plotting observed on the vertical or $y$ axis and predicted or fitted on the horizontal or $x$ axis is marginally preferable to the opposite convention for two reasons:

Plotting response or outcome variable on the vertical axis is a common convention throughout science.
This matches the very common convention of plotting residuals on the vertical axis and predicted or fitted on the horizontal axis in a very common associated plot. (Plots of observed versus fitted and of residual versus fitted show the same information; the first conveys the good news and can be easier to think of substantively, while the second conveys the bad news and can be easier to think of statistically, particularly when considering whether a model is adequate or can be improved.)

On which is the right way round with versus, see discussion at versus (vs.): how to properly use this word in data analysis
A more formal name is calibration plot (e.g. Harrell 2001, 2015; Venables and Ripley 2002; Gelman and Hill 2007).
Chambers, J.M., Cleveland, W.S., Kleiner, B. and Tukey, P.A. 1983.
Graphical Methods for Data Analysis. Belmont, CA: Wadsworth.
Gelman, A. and J. Hill. 2007.  Data Analysis Using Regression       and Multilevel/Hierarchical Models.  New York: Cambridge University Press.
Harrell Jr., F.E. 2001.  Regression Modeling Strategies: With         Applications to Linear Models, Logistic Regression, and Survival Analysis.  New York: Springer.
Harrell Jr., F.E. 2015.  Regression Modeling Strategies: With         Applications to Linear Models, Logistic and Ordinal Regression, and Survival Analysis.  Cham: Springer.
Venables, W.N. and Ripley, B.D. 2002. Modern Applied Statistics with S. New York: Springer.
Comment: @Antoni Thanks; I did that while you were suggesting it. (I think the wording residual vs fitted is slightly preferable, FWIW.)
Comment: +1 Would there be a point in mentioning any contrast (pros and cons) of this type of plot versus a fitted v residuals plot?


Using nth-child to display divs side by side-one larger div on the left two smaller on the right-but the second smaller div keeps getting pushed down

Question: I'm playing around with nth-child and trying to create a layout that looks like this

but for some reason the larger divs will only allow one smaller div to display to its side, it pushes the second smaller div down like this:

even though according to the dimensions they should fit. What am I missing or not understanding here? I've included my HTML and CSS below:

#main {
  text-align: center;
}
.boxes {
  font-size: 30px;
  height: 200px;
  width: 45%;
  background-color: grey;
  margin: 10px;
  display: inline-block;
}
.boxes:nth-child(6n-2) {
  font-size: 30px;
  height: 420px;
  margin: 10px;
}
.boxes:nth-child(6n-5) {
  font-size: 30px;
  height: 420px;
  margin: 10px;
}

box1

box2

box3

box4

box5

box6

Comment: What you are trying to achieve is called a **Masonry** layout. Sure you can try floating different children or wrap each group in a container but this requires a lot of maintenance and is not flexible.
Comment: Related: http://stackoverflow.com/questions/8470070/how-to-create-grid-tile-view-with-css
Answer: you need to assign float-parameters to these boxes: float:left to box 1,2,3 , float:right to box 4,5,6
Here's a codepen: http://codepen.io/anon/pen/mPojBJ
(widths / margins still need to be tweaked)
Answer: I think this will work for you, see fiddle https://jsfiddle.net/c259LrpL/44/
change .boxes{display: inline-block} to .boxes{float: left}
.boxes {
  font-size: 30px;
  height: 200px;
  width: 45%;
  background-color: grey;
  margin: 10px;
  float: left;
}

Then float the other big box right
.boxes:nth-child(4) {
    float: right;
    margin-right: calc(100% - (90% + 30px)) !important;
}

Comment: Thanks, this works well. Although I'd still be interested in knowing why my original solution doesn't work if you have any ideas, as it seems like it should.
Comment: @nickstobie Its because you were using `inline-block` incorrectly, see here for a good explanation http://stackoverflow.com/questions/9189810/css-display-inline-vs-inline-block
Answer:

Hi. It will be more easy if you will do the above implementations. As you can see, I didn't use float:left because it is more efficient to use display:inline-block;


How to hide/display rows in datatables?

Question: I am trying to hide/display certain rows based on data from a hidden column. my table structure looks like:

        Agent ID
        Agent Name
        ID Number
        Mobile Number
        Team Name
        Status

I am trying to hide/show records based on the Status column, using a checkbox. If the status == DEREGISTERED I want to exclude it from the table (unchecked checkbox).
I adapted my code from what was done here:
$.fn.dataTableExt.afnFiltering.push(function (oSettings, aData, iDataIndex) {
    // does not run this
    console.log("GOTHRERE");
    if ('agent_search' == oSettings.nTable.id) {
        // console.dir(oSettings);
        console.dir(aData);

        var dereg = aData[5];
        console.log(dereg);
        if (dereg == "DEACTIVATED"){
                return $('#toggle_deregistred').is(':checked');
        } else {
            return $('#toggle_deregistred').is(':not:checked');
        }
    }

    return true;
});

I have tried using $.fn.dataTableExt.afnFiltering witch is used for custom filtering, only to find that I can not do it. It was once possible in previous versions of dataTables as in this case , but as it turns out it was a bug that allowed it to be possible :|.
Is there a way that I can filter out rows based on if their Status with the use of a checkbox? or is there something in the api I can use that I have over looked?
UPDATE:
I have made a jsfiddle in which it is working, how ever in the process of adapting my code to put it in jsfiddle, I noticed that it is bServerSide that is causing the $.fn.dataTableExt.afnFiltering not to work. Is there a work around or another way to user Server-side processing?
Comment: There are no rows with a "DEREGISTERED" value, there's only one row with "DEACTIVATED". I assume you want the checkbox to hide all rows that have the class "DEACTIVATED" if it's unchecked, and show those rows when it's checked. Your original code already seems to do this in the fiddle. However, I added a method that specifically hides and shows the rows: http://jsfiddle.net/kc56p47L/7/
Comment: You could add a DEREGISTERED class to your tablerows at the time you are creating them from your data, and add an event listener to the checkbox. When the checkbox is changed, call the hide() method on the offending table row. Call show() when you want to show the table row again. Why bother with custom filtering when you can do it the way that's easier for everyone to read? :)
Comment: @imdabestmanideedeet Thanks for your suggestion. It is a good idea, but the problem comes in when I start searching for the records. It reDraws the table in order to display only the relevant records, and as result it shows the records with status `DEREGISTERED` again. any suggestions?
Comment: Could you put your own code in a JSFiddle page? That would make it easier for everyone to understand what you are trying to do.
Comment: Updated question with jsfiddle...
Comment: Sorry about that, my mistake... Your added method does not work, because `fnDraw()` redraws the table without consideration for what you 'manually' changed. The jsfiddle works as I had it, but when I add `"bServerSide": true` it does not work.. I can not demonstrate this in jsfiddle. I am getting my data from the server-side... so I need either a work around, or another approach...
Answer: I found an alternate way to the checkbox of hiding/displaying.
I use Bootstrap 3 tabs to apply different filters:

All

 Deregistered

    <fieldset id="all" class="tab-pane active">

                Agent ID
                Agent Name
                ID Number
                Mobile Number
                Team Name
                Status

    </fieldset>
    <fieldset id="dereg" class="tab-pane ">

                Agent ID
                Agent Name
                ID Number
                Mobile Number
                Team Name
                Status

    </fieldset>

I first initialize the table on the first tab all which uses bServerSide=true and for the other table(when I switch to the other tab) I do:
$('#search-tabs a').click(function(e) {
    e.preventDefault();
    $(this).tab('show');
    if (this.dataset["dtname"] == "all") {
        oTable.fnDraw();
    } else if (this.dataset["dtname"] == "dereg") {
        var data = $("form").serialize();
        $.post(
            url,  data
        ).success(function(data){
            console.log(data.aaData);
            kTable = $('#dereg_agent_search').dataTable( {
                "sScrollY": "250px",
                "data": data.aaData,

                "destroy" : true,
                "sDom": "<'row'<'col-sm-6'><'col-sm-6'f>r>t<'row'<'col-sm-6'i><'col-sm-6'>>S",
                "aoColumnDefs": [
                  {
                        "bSortable": false,
                        "aTargets": [ 6 ],
                        "sWidth":"150px",
                        "mRender": function( data, type, full ){
                            return "
ViewEdit
"
                        }
                    },
                    {
                        "bSortable": true,
                        "aTargets": [ 0 ],
                        "sWidth":"150px",
                        "mRender": function( data, type, full ){
                            if (full[5] == "DEACTIVATED"){
                                return ""+data+""
                            } else{
                                return ""+data+""

                            }
                        }
                    },
                    {"aTargets": [ 4 ], "sWidth":"250px" },
                    {"aTargets": [ 5 ], "bVisible":false},
                ],
                "bDeferRender": true,
                "bStateSave": true
            } );
        });
        kTable.fnDraw();
    }

});

Notice that I get the data to populate the table from the server - using a jQuery $.post request, and then I use datatables' data attribute to populate the table.
I hope This can Help someone.

How to hide/display rows in datatables?


SYSTEM user to schedule tasks on Win 2003 server?Impact?

Question: I wish to schedule a bat file on my Win 2003 server without a password.
The requirement is to run it everyday at a specific time.
We use expiring passwords and do not have a non expiring account.
I plan to schedule this using Scheduled Tasks as a SYSTEM user.
It is working fine, for me.
However,
What is the impact of using a SYSTEM user?
Is there something we should be cautious about?
The code is certainly not malicious!
However, i do not wish to impact other users/applications on my Win 2003 server.
Any one has details of the impact?
Answer: The impact of running scheduled tasks as System is that System is a very highly privileged account. Even more powerful than an administrator. What this means is that your scheduled task has all the privileges it needs to completely trash the system if your scheduled task is misconfigured, or if something malicious is inserted into your batch file, etc.
Running your scheduled tasks as a non-privileged user ensures that the amount of damage it can do to the system is limited.
It's just one of those best practice, better safe than sorry measures. That said, people still run scheduled tasks as System all the time. Sometimes I do it too.
Answer: There isn't anything inherently wrong with using the SYSTEM account - it is an extremely high priveleged account, higher even then the local administrators group.
The big thing is being sure that not only the script / executable itself is clean but also whatever input it'll be using (if any).
Using one of the other security principles such as the network service account may be better depending on your use case.
For details see Microsoft's page on service user accounts. If possible these make things a lot easier then a dedicated user that you need to keep track of the password for.
EDIT:
Sorry, I forgot about the fact that you can't use these accounts in 2003. This feature was introduced in 2008. See Is it possible for a Scheduled Task to run as NETWORK SERVICE?
Also seriously consider upgrading from 2003.


Number of observations to study the reproducibility

Question: I'm running an experiment which is about to investigate the influence of gases on the resistance of sensors. Since this is chemistry and gases are experimentally rather hard to handle, I would like to study how well the experimental setup itself is performing.
To start simple, I would like to get started with any potential deviations between the runs, so, precisely this means I would do the following:
The system and its components do not change and I flood the volume with gas. Then I measure.
Afterwards I air the volume and wait several hours longer than necessary. Then I flood the volume with gas and measuer again. I air again. Over and over.
Here is my first question: How often should I do this? 5 times? 10? 30?
Despite from that, is there an another / more "statistical" way?
Comment: Here is a pretty good reference: https://www.isobudgets.com/how-to-perform-a-repeatability-test/.  From your description above, this is only the first part of many additional tests, thus the future test will fulfil the 30 sample requirement.
Comment: Thanks a lot! That is very well-written.
Comment: It will be hard to answer this question unless there you provide more information about the variability among resistance measurements under the same conditions, whether you expect the various gases to affect that variability, and how big the differences among gases that you wish to detect are. It would also help to have information about how many gases you wish to test in this way.
Comment: Using the same operator, on the same set-up, under the same conditions with the same sample is a Repeatability test.  I can't find any good references to support this, but a typical test usually is 3-5 repeats assuming a normal distribution of the output, each additional test adds additional expense and provides less and less new information,
Comment: @EdM Isn't that something I wanna' find out (related to the variability)? Yes, the resistance will be affected by the gas (the technical purpose of gas sensors is that gas has the main influence on them). I would start with a single gas.
Comment: @Dave2e I'm quite sure that in a statistics course the lecturer once said that it is a thumb of rule to use 30 runs per parameter - or per degree of freedom - or something similar. I can't really remember. I also do not remember how that enters when having more than one parameter (60 runs or 30^2 runs?..). Hence, I assumed much more repeatings than 3-5? However, shouldn't there be a statistical background behind it? I can't really find something to dive into, combined everything I find, is that it seems to be totally arbitrary/empirical.
Answer: Start by considering how precisely you need to know the variability among runs. That should be informed by the differences in sensor resistances you ultimately want to be able to detect among gases. When you eventually get to the point of comparing gases, note the following rule of thumb* for the number needed in each group ($n$) to detect a difference in mean values between 2 groups having normal distributions and the same variances:
$$ n =\frac{16}{\Delta^2}$$
where $\Delta$ is the standardized difference, the ratio between the difference you would like to be able to detect $(\delta)$ and the standard deviation $(s)$ of the measurements, $\Delta=\frac{\delta}{s}$.
So if you only care about differences among gases on the order of 100 resistance units, it won't matter much whether the standard deviation among runs on the same gas is 0.1 unit or 1 unit or 10 units. The rule of thumb says if you only care about differences on the order of 100 units you might get away with single measurements on each group unless the standard deviation is on the order of 25 $(\Delta = 100/25 = 4),$ although you would probably want to do 2 or 3 regardless to rule out some catastrophic error. Note also that this rule of thumb shows you how much different values of the standard deviation would matter in terms of ultimate experimental design.
The reason for first thinking hard about the precision that you need in your variance estimate is that "learning a variance is hard," as @cardinal put it in this answer. The variance of a variance estimate when sampling from a normal distribution goes with the 4th power of the standard deviation and decreases only about linearly in the number of observations, so you need a lot of observations to pin down limits on the true value of the variance. You don't want to spend more effort on determining the variance than is necessary.
I would recommend starting with a pilot study that puts more emphasis on multiple gases and less emphasis on the number of runs per gas. Use a panel of gases likely to cover the range of expected resistance measurements and start with about 4 tests on each gas. Standard linear modeling (analysis of variance) of that type of pilot study will give you information both about likely differences of interest between gases $(\delta)$ and, by pooling information from among the gases, the standard deviation of measurements $(s)$ around the corresponding mean values. You then use diagnostic tools for linear models to examine whether assumptions like constant standard deviation among gases are reasonable, and if needed adapt your approach accordingly.
You might also want to design your pilot study in a way that can help you estimate potential carry-over among consecutive measurements on different gases. This sensor system presumably depends on gas adsorption to the resistive element, which can be quite tenacious and hard to displace. Rather than doing your tests by "waiting several hours longer than necessary" to get some idealized estimate of measurement errors, you might be better off running your tests more like they will be performed in practice and learning early on just how big a problem carry-over might be. My former life as a chemist makes me suspect that in practice that will be a larger problem than the error inherent in the resistance measurements.

*Gerald van Belle, Statistical Rules of Thumb, 2nd edition, Wiley, page 29.
Comment: Nice informative answer (+1)
Comment: Thanks a lot! It's a bit slightly over my head resp. have to think about some details. Thus, I have some questions: Though you say the differences I wanna' observe are important I do not really know how to anser this question. Do I look for 100 Ohm differences? Or 1000 Ohm differences? When I want to evaluate them in general, isn't this a question that should be answered by the experiment/analysis?


C++ Templates: dealing with long class names

Question: If using statements are barred from headers in CPP projects according to nearly everyone, and templates must be declared in the headers unless specific steps are taken to specifically list out the classes that will be accepted in the cpp file,
What is the manner in which the following header template declaration should be rendered readable:
template<class A>
SomeLibrary::LongNameClass<SomeLibrary::LongNameClass2,SomeLibrary::LongNameClass3>
unreadable_function(SomeLibrary::LongNameClass<SomeLibrary::...> input1, ... input2, ... omg){
        SomeLibrary::SomeFunction<SomeLibrary::LongNameClass<SomeLibrary::...
        etc.
}

Comment: Readable C++? Sounds blasphemous
Comment: If by "fingertips dying" you mean that typing that stuff takes much time then it could be a complaint opposite to *"improving readability"*. Note that code is read more often then written so spending more time properly formatting code (and adding comments) is never a bad idea.
Comment: Using an actual documentation for your function? You can split template / function parameters on multiple lines. If you have too much imbrication / arguments, maybe it's a design issue... And nothing prevent you from using `using` inside the function - Using outside would bring your `using` declaration in every file that includes your header, which you do not want.
Comment: Just don't try to squeeze everything into a single line.
Comment: @VTT not just visually unreadable.  Also: fingertips dying
Comment: @VTT well, it goes both ways: I need to write faster, read what I write, and not have to waste mental energy and development time transcribing long winded class names, during development--we (people who prefer typed, multiparadigm programming languages for bigger projects) are competing with python now, and I am more than proficient with python, so I have to qualify the time I spend in C++ with output.
Answer: Dont be mistaken, the only banned statement is using namespace <...>.
The statement using <alias> = <type> as well as typedef <type> <alias> are still valid and widely used.
Comment: `using <...>` is also sub-par. But using some local alias is ok, I guess, provided you can make it super-unique. Actually, shove it in a `detail` namespace and refer to it there, yay (although be careful because the more you do this the more you're back to square one )
Comment: Aliases are fine, however the tricky part would be not to end up with names like `LongNameClassFromSomeLibrary`.
Comment: @bordeo With `using` is cpp-file there is still naming collision probability, but it will be only in this cpp-file, not entire project.
About scope of `using` inside namespaces I'm not sure. Never have tried this
Comment: and--just to be clear--I am free to use usings in cpp files?  ALSO, if I create a namespace, I can use usings differently?
Comment: @SemyonBurov awesome, I will try that, and comment
Answer:
What is the manner in which the following header template declaration
  should be rendered readable:

Use white-space to format your code for readability.
Use trailing return types to make function names stand out.
Use concise, meaningful identifiers.
Provide high-level abstractions (sometimes just a typedef).

See Kevlin Henney's talk for more explanation.
namespace Some {

template<class A>
auto unreadable(LongName<...> input1,
                ... input2,
                ... omg)
 -> LongName<LongName2, LongName3>
{
    Some<LongName<...>>();
    etc.
}

} // namespace Some

Comment: what about typedefs within the namespace? Will these cause collisions when imported? I mean, if it is **in** the namespace, I would imagine I would always pick the same or similar alias names...
Comment: A typedef may be used to provide a meaningful abstraction, while at the same time shorten code. E.g. `typedef std::map  NameCount;`