Comparar arrays e destacar as alterações

Question: estou com um probleminha que não estou conseguindo resolver.
Eu tenho um array com um histórico de ocorrências que possui 5 posições, e preciso fazer a exibição desses históricos destacando os itens diferentes de cada array.
No momento eu consigo pegar a diferença entre dois deles, porém não estou conseguindo perceber o melhor modo de receber todas as diferenças.
<code>$diff = array_diff($historico[3], $historico[4]);
</code>
Nesse caso ficam faltando os historicos da posição 2,1 e 0.
A estrutura do array que eu tenho é essa:
<code>[
[0] => Array
    (
        [0] => 07/06/2018 15:49:00
        [1] => Questionamento :  teste questionamento
    )
[1] => Array
    (
        [0] => 07/06/2018 15:50:00
        [1] => Questionamento :  teste questionamento 2
    )
 [2] => Array
    (
        [0] => 07/06/2018 15:51:00
        [1] => Questionamento :  teste questionamento 3
    )
 [3] => Array
    (
        [0] => 07/06/2018 15:52:00
        [1] => Questionamento :  teste questionamento 4
    )
  [4] => Array
    (
        [0] => 07/06/2018 15:53:00
        [1] => Questionamento :  teste questionamento 5
    )
</code>
]
Comment: é array dentro de array?
Comment: Tipo dentro do array historico tem 5 arrays?
Comment: Sim é um array de histórico com um array para cada atualização.
Comment: Imagino que terá que fazer um loop recursivo, pegando cada um e comparando com o restante
Comment: Só você colocar os outros arrays ai dentro ué, $diff = array_diff($historico[0],$historico[1],$historico[2],$historico[3],$historico[4]);
Comment: @Anderson Henrique dessa maneira não funcionou.
Comment: @Marcelo tenho que comparar o último com o penúltimo, o penúltimo com o antepenúltimo, até chegar no primeiro.
Comment: Você pode ordenar o array antes de acomparar, https://secure.php.net/manual/pt_BR/array.sorting.php
Answer: Não sei o motivo, mas se quer pegar de trás para frente faça assim
<code>#array para pegar as diferenças
$diferencas = array();
#for pegando o tamanho do array e diminuindo, o motivo do menos 1 é que o array inicia de 0 então mesmo tendo 4 registros seriam de 0 a 3 no caso 3, teria que diminuir 1
for($i = sizeof($historico) - 1; $i > 0; $i--):
    #adiciona a comparacao de array da posicao atual com uma anterior
    array_push($diferencas,array_diff($historico[$i],$historico[$i - 1]));
endfor;
#printa as diferencas
print_r($diferencas);
</code>
Você também pode ter outra forma sem precisar dos menos
<code> #array para pegar as diferenças
$diferencas = array();
#Reverte as posicoes dos arrays de tras pra frente, ultimas chaves viram primeiras
krsort($historico);
for($i=0; $i < sizeof($historico) - 1; $i++):
array_push($diferencas,array_diff($historico[$i],$historico[$i + 1]));
endfor;
print_r($diferencas);
</code>
Comment: Obrigado, dessa maneira funcionou corretamente.
Comment: Denada, se puder por favor marcar como resposta eu agradeço. @ValdirSilva


Optimization parameter for classification

Question: I do not have enough knowledge about optimization.
My problem is simple.
Lets say I have 100 classes. Each class contains some instances (images). The feature vector obtained from a particular image depends on a parameter P.
I need to learn this parameter automatically by maximizing the classification accuracy.
As I have no idea about optimization, could you please suggest me about how I can do this.
Thank you.
Comment: I think the question is too broad. I suggest you try a specific classifier and ask specific questions about the details of optimization.
Comment: However, we can already tell you that classifier optimization is far from a simple problem. Frank Harrell will soon also tell you that accuracy (or other measures based on the proportion of successes / failures) are not a goot target value for optimization and that you need so-called proper scoring rules instead. Have a look around here, there are actually quite a few optimization questions already on this page.
Comment: please specify your classifier
Comment: Any classifier, SVM, LDA, any
Answer: Basically you need to add an exra grid on top of your typical learning stack. Since you didn't specify the algorithm of choice or any properies of p, I can't really be more specific. The most basic version would look something like this though:
For all values of p:

Apply p to the images to obtain feature vectors
Apply the learning procedure using these feature vectors
Remember the performance for this choice

Afterwards, look at the value of p that gave you the best performance and use this for subsequent learning. Remember to use a held out part of your dataset for testing.
For more information, look at 'cross validation'.


GraphQL API Returning 404 Resource Not Found in Consumption Tier APIM

Question: I am trying to add GraphQL API in API Management - Consumption Tier, and it's returning a 404 Resource Not Found error.
<code>{
  "statusCode": 404,
  "message": "Resource not found"
}
</code>
The Same API configuration in Basic Tier and Developer Tier works perfectly fine. Am I missing something? Are GraphQL APIs not supported in consumption tier? Is there any extra configuration required specifically for consumption tier to support graphql APIs?
Please let me know.
Answer: This is a known issue and should be fixed by GA. As a workaround use any of the other dedicatd tiers.


IIS 6.1 Handlers for HTML, ASP, INC files

Question: I have a legacy website in which .HTML, .ASP, and .INC files are being used. Problem is all pages have VBScript code not parsed by IIS and thus written on page as static text. I want to fix it. All .html pages include both .ASP and .INC for scripts.
Now currently IIS Handlers are as below: all .htm, .html, .inc have IsapiModule handlers as well as ServerSideIncludeModule. This is what I suspect causing issue. So now if I remove ServerSideIncludeModule handlers and just keep IsapiModule, it parses VBScritpt correctly but HTML pages with INC inclusion do not open but ask to save a file to download. What am I missing here? This worked on my localhost fine but not on Production.
How can I fix this issue?
Thank you!
Answer: How about you fix the underlying problem: the fact that you have server code in a file that is not meant to be read by the server. Change the extension from .html to .asp.  Problem solved.
Comment: If that was possible, I would have done that. It's an old website and company wont spend much resource time doing renaming, cleaning up, redirecting etc.
Comment: I hate to tell you this, but undoing the default behaviors in IIS to handle HTML as a server executed file is not going to be easy as you have discovered, may end up being faster to rename the files and refactor the code. Could easily be scripted out for the most part.


Decision Tree uses too few Variables

Question: The Decision Tree algorith used only 3 variables ("lstat" "rm"    "dis") to make a regression.
The Dataset is Boston Housing which has 13 predictor variables and 1 response variable.
I understand that the variables used for split are decided based on Gini or Entropy coefficients.
But could it really be that all other variables except these 3 have zero predictive power?
Code:
library(MASS)
set.seed(1)
train = sample (1:nrow(Boston), nrow(Boston)/2)
tree.boston=tree(medv~.,Boston , subset=train)
summary(tree.boston)

plot(tree.boston)
text(tree.boston , pretty =0)

Output:
Regression tree:
tree(formula = medv ~ ., data = Boston, subset = train)
Variables actually used in tree construction:
[1] "lstat" "rm"    "dis"
Number of terminal nodes:  8
Residual mean deviance:  12.65 = 3099 / 245
Distribution of residuals:
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max.
-14.10000  -2.04200  -0.05357   0.00000   1.96000  12.60000

Graph:
Answer: For your question: Yes, this is the most predictive feature set based on gini criteria and the 50% train data you sampled. However, you are probably looking for accuracy when you mean predictive. That would have to be calculated for an in-sample and out-sample metric (eg. Mean squared error or mean absolute error). Based on that you can decide whether these are predictive. If you change the train sample (i.e. sample 50% with a different seed, it may be possible to get other features). Given there is no limit of depth I guess, the accuracy in sample would be 100% or 0 MSE or something like that i.e. over-fit.
Seed plays a critical role in tree based models. Decision Tree being the most basic model, in this case it seems, these are the only features predictive. However it is for the current training set that has been sampled. If the seed is changed for sampling, the predictive features might change.
Random forests therefore have better prediction as it will average across several decision trees. In case of random forests, it must be noted that there is functionality for feature sampling with a seed as well.
I find this video on decision trees helpful for intuition:
https://www.youtube.com/watch?v=wpNl-JwwplA&feature=youtu.be
Comment: Very helpful thank you. I would upvote your comment but I dont have enoigh reputation.

Decision Tree uses too few Variables


EntityFramework core (7th) how to map protected/private properties

Question: Looks like the way how private/protected properties mapped to db was changed in EntityFramework core
So what should I do to be able correctly map this class:
class Model
{
   protected string _roles {get; set;}
   [NotMapped]
   public IEnumerables<RoleName> Roles => Parser_rolesToRoleNames(_roles)
}

Answer: I do not understand your NotMapped-Property, because it seems to have no name?
To make EF Core map your protected property anyway, in your DbContext in OnModelCreating use the EntityTypeBuilder.Property-Method:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Model>()
        .Ignore(m => m.NotMappedProperty)
        .Property(typeof(string), "_roles");

    base.OnModelCreating(modelBuilder);
}

During batabase creation, the respective column is generated.
To make EF write the values of the private properies to the database, you need to override SaveChanges:
 public override int SaveChanges()
        {
            foreach (var entry in ChangeTracker.Entries())
            {
                foreach (var pi in entry.Entity.GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic))
                {
                    entry.Property(pi.Name).CurrentValue = pi.GetValue(entry.Entity);
                }
            }
            return base.SaveChanges();
        }

This way all values of your private properties are added to the corresponding change tracker entries and are written to the database on Insert / Update.
Comment: Does this mean I can make a table read-only from EF's point of view just by making the property private and not overriding `SaveChanges`?
Comment: The property name is Roles and it is using the new C# 6 lamba expression property syntax "Properties and indexers can have getters and setters. Expression bodies can be used to write getter-only properties and indexers where the body of the getter is given by the expression body" https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C%23-6


What is the term for these scale repetition patterns?

Question: I am making some notes on scales and patterns and I am wondering what is the term for these types of scale repetition patterns? Interested to know because I want to categorize them

Interested to know the general term for them so that I can also categorize
12-23-34-45-...
12345-23456-34567-...
Comment: In German this is called *Quartgang* or *Terzgang*. It seems that there is no term in English. s. https://dict.leo.org/forum/viewUnsolvedquery.php?idForum=1&idThread=106326&lp=ende
Comment: Tell me when you have labeled your series. I'm trying to do the same with all kind of motifs. https://music.stackexchange.com/questions/95594/is-there-a-list-of-motifs-and-labels-of-this-motifs
Comment: Do you mean the single motifs or the group of the motifs (their sequenced repetition)?
Comment: @AlbrechtHügli, do Quartgang or Terzgang mean four (or three) step-wise notes?
Comment: I mean taking a sequence of notes from a scale and diatonically transposing them up on step for every time it is played
Answer: I have seen such patterns referred to by a few different names, and I think that depends on context.  Albrecht is correct in identifying the tetrachord and motif, the first is pretty specific the second more general.  In guitar exercise books I've seen them calls sequences and diatonic patterns, or diatonic sequences.  That assumes they are played on the diatonic scale but such patterns could be played on the pentatonic or chromatic as well.  Such patterns can be very musical, designed to emphasize specific difficulties on a particular instrument, and get very wild.  On guitar it is quite common to see these sequences with a string skip in them (as that is an achilles heel for many).  Other than that I am not aware of any deeper meaning.
Answer: I think the term you are looking for is melodic sequence (similar to, but distinct from harmonic sequence) where some melodic unit is transposed and repeated...

If you are studying scale patterns and sequence, this may interest you. You can take one beat permutations of the line...

...deriving these four elementary figures (notice the 1st, 2nd, and 4th decorate the interval of a third and the 3rd figure decorates a single tone)...

...each of which can be treated sequentially...

Use those kinds of figures (and their inversions) with repetition or melodic sequence, with simple quarter and whole notes - with or without dotted values - and it gives you endless ways to elaborate a basic harmonic framework.
Comment: I got it from 'Figuring Out Melody' by David Fuentes a while back. The book was free online for a long time, but not any longer. I thought it was a very practical book.
Comment: I too wasn't sure about the question. But with the number written out, incrementing up in sequence, I guessed that is the main concern. Maybe.
Comment: It`s interesting to show that the the different patterns can be derived from the one 1234 as permutations. And that the series are a sequence is also clear. I thought the question was: is there a name for the group. Now we could name them 1234 a, b,c,d. My idea is that I give them a name of well know songs or pieces like "2342"( =1234 b) is the "piggies motif" (Beatles) and othe sequences are named by me after well known passages of Bach inventions or  concertos.
Answer: I'm not sure what you are looking for exactly. If you want a term for the sort of exercise you play repeatedly in order to improve your fingering technique, etc., I'd call that a "drill".
Answer: This could be called 4th-passage (actually a scale passage of 4 notes is a tetrachord analogous the 3 notes passage within a scale must be a triachord.
But I would just call it a 3 or 4 note motif. (Knowing in this case they are in a ascending row opposite to e.g. 1231 2342 etc.)
Answer: Scale runs. Running scales.  +++


PDO not catching error when I SELECT a table that doesn't exist

Question: I am trying to try/catch a PDO::query to make sure whether a table exists or not. But Instead of catching the error and returning true or false it is just throwing an uncaught error:
public function __construct(){
    $this->db = parent::connect();
}

public function table_exists($table){
        try {
            $this->query("SELECT 1 FROM `$table` LIMIT 1");
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    public function query($sql){
        try {
            $this->result = $this->db->query($sql);
            return $this;
        } catch (Exception $e) {
            return null;
        }
    }

I also tried this $this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); inside the try's but it didn't make any difference. So I get

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[42S02]: Base table or view not found: 1146 Table
  'refritec.user' doesn't exist' in
  ...\DatabaseDriverMysql.php:34 Stack trace:
  0 ...\DatabaseDriverMysql.php(34): PDO->query('SELECT 1 FROM ...') 1
  ...\DatabaseDriverMysql.php(25):
  Core\DatabaseDriver->query('SELECT 1 FROM `...') 2
  ...\Pen.php(123):
  Core\DatabaseDriver->table_exists('user') #3 [internal function]:
  Core\Pen->update() #4 ...\index.php(97):
  call_user_func_array(Array, Array) #5 {main} thrown in
  ...\DatabaseDriverMysql.php on line 34
Comment: Try with `\Exception` instead of `Exception`. Or, since you are using PDO, use `\PDOException`.
Comment: Is the code above in a file that is namespaced?
Comment: ^^^ that's what I was getting at
Comment: @xjstratedgebx You didn't quite get to the point, so I made it for you.
Comment: you did it @SverriM.Olsen
Comment: No worries, so long as the OP gets the answer, that's what we're here for. I was using the comment to get clarification on the question, to then provide an actual answer, as I understand that to be the process. If we're right though, properly namespacing the Exception should do the trick.
Comment: @VictorFerreira you are getting `true` always right?
Comment: @VictorFerreira how you are using result returned from `table_exists()`?
Comment: @itzmukeshy7 Sverri found the answer. I'm using Namespace and I had to use \Exception to refer to the native class.
Answer: Apart from that silly typo explained in comments, your approach is essentially wrong.
First, you aren't checking the particular exception. Means there will be false positive in case of any error, not only absent table.
Second, your code is prone to SQL injection.
Third, you are writing a code that is raising a deliberate error. That's wrong again. As long as there are means to check the table existence the regular way, you have to use it:
$stmt = $pdo->prepare("SHOW TABLES LIKE ?");
$stmt->execute([$table]);
return $stmt->fetchColumn();

Fourth, such a function itself arises suspicions for the database design. Ina sanely designed application there is no need to create tables dynamically.
Answer: I´m not able to recreate your exact problem but did you try catching the PDOException like:
try {
    $this->query("SELECT 1 FROM `$table` LIMIT 1");
    return true;
} catch (PDOException $e) {
    return false;
}

Edited
You also have to use $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); on your connection. because PDO doesn't throw exceptions by default like seen here.
Comment: `PDOException` extends `Exception`. This shouldn't make a difference. Also, answers should *answer* the question, not guess at what it might be. If you need more information, or if you are not sure, then write a comment instead.
Comment: I didn't, my friend, but it still don't work. my version of PHP didn't allow me to use return inside `die`. without the `return`, only `false`, it gives me the same error
Comment: I edited my answer. Try the `setAttribute`, then you should be able to catch the exception.
Answer: I use the simple query to see if the table exists, if the value is different from "0" there is a value with that I can show the message I want.
    $res = $this->db->query("SHOW TABLES LIKE '".$tbname."perfil'");

    $count = $res->num_rows();


Find the probability function of $Z$

Question: Let  $X_1,X_2$ be a random variables with geometric distribution with $p$,
let as define $Z:=$max$\{X_1,X_2\}$

Find the probability function of $Z$

My start:
$$X_1,X_2\sim G(p)$$
Now I need to find $\color{blue}{(1)} P(X_1>X_2),\color{blue}{(2)}P(X_2>X_1),\color{blue}{(3)}P(X_1=X_2)$
$$\color{blue}{(3)}P(X_1=X_2=k)=(1-p)^{k-1}p$$
$$\color{blue}{(1)}P(X_1<X_2)=\frac{p(1-p)^{X_2-1}-1}{(1-p)-1}$$
$$\color{blue}{(1)}P(X_2<X_1)=\frac{p(1-p)^{X_1-1}-1}{(1-p)-1}$$

My attempt is correct?
Comment: You cannot still have $X_1$ or $X_2$ on the RHS: the RHS must be a real number, not a random variable. (To help solve the problem: typically, for the maximum of i.i.d. random variables, looking at the cumulative distribution function to characterize the distribution is a good idea.)
Comment: So $X_i$ in the RHS equal to $k$ for some $k \in \mathbb{N}$
Answer: It may be wiser to calculate the probility $Q(k)=P(X_1\le k\wedge X_2\le k)$ that both $X_1$ and $X_2$ take a value no more than $k$. Once you manage to calculate this, $Q(k)-Q(k-1)$ will give you what you want.
Answer: $Z$ is less or equal than $k$ if and only if both $X_1$ and $X_2$ (assumed independent here -- otherwise the exercise has a much different flavor) are both less or equal than $k$. Looking at the cumulative distribution function, for any $k \in \mathbb{N}$
$$\begin{align}
F_Z(k) &= \mathbb{P}\{ Z \leq k\} = \mathbb{P}\{ X_1 \leq k\}\cdot \mathbb{P}\{ X_1 \leq k\} \\
&= F_{X_1}(k)\cdot F_{X_2}(k) = (1-(1-p)^k)\cdot (1-(1-p)^k) \\
&= (1-(1-p)^k)^2
\end{align}$$
Now, since $\mathbb{P}\{Z=k\} = F_Z(k) - F_Z(k-1)$ (for $k\geq 1$) and $\mathbb{P}\{Z=0\} = F_Z(0) = 0$, you get
$$\begin{align}
\mathbb{P}\{Z=k\} &= (1-(1-p)^k)^2 - (1-(1-p)^{k-1})^2
\end{align}$$
(this may simplify a little, but I'm not sure how much.)
Comment: It nicely simplifies to $P(Z=k)=pq^{k-1}(2-q^{k-1}-q^k)=2P_k(1-\frac {P_{k}+P_{k+1}}{2p})\sim 2P_k$. This also strengthens the connection between geometric and exponential distributions.

Find the probability function of $Z$


Proxmox Virtualized Client (Network Configuration)

Question: first some information about me. I ordered a server from ovh and purchased one failover ip to test proxmox and do some training.
The main Server is hosting proxmox(Example IP: 220.127.116.11 to figure out my problem)
Now i want to create a virtualized client(debian). This debian client should use the failover ip, which i ordered(Example IP: 126.96.36.199).
The network adapter has to be bridged, right? I can choose between these models:

intel e1000
virtIO (paravirtualized)
Realtec RTL8139
VMWare vmxnet3

Which is the right one for me? How can i check it?
After coming to the network configuration in debian, i cant figure out my problem.

IP Adress:220.127.116.11
netmask: 255.255.255.255 (is this right?)
Gateway: 18.104.22.168(Because OVH is saying that i should use the .254)

After entering those information, i am getting an error, which says that this gateway is not reachable.
I hope my problem is clear.
Best regards,
Edit: I got some information about creating a virtual mac and binding it on proxmox to the debian client. Will it work after doing this with my configuration which i posted? I can try it in 2-3hours.
Answer: Here's what you need to do to add a public IP address to the VM :

In your OVH manager, add a new Virtual MAC address to the (additionnal) IP you want to assign to the VM.
In Proxmox web GUI, got to your VM and to the "Hardware" tab.
Double click on the Network Device to edit it, and copy-paste the previously created Virtual MAC to the "MAC address" field. (You should be using vmbr0 as bridge and Intel E1000 as model works fine.)
Validate the change and restart the machine (from Proxmox, not from the VM).
Configure the VM based on the OVH documentation : http://help.ovh.co.uk/BridgeClient

This should get it working !
If something else isn't clear, OVH's guide for Proxmox might help you : http://help.ovh.com/Proxmox
Comment: If my answer is correct, please accept it @Newbie2015 ;-)


What is the correct procedure to install a Drupal security patch?

Question: The back-end admin interface informs me that there is a new security patch for Drupal 6, but I can find any information about ho wto install it.
Answer: http://drupal.org/node/14231
this should help you out.
Answer: This page on the Drupal site explains the steps for upgrading as well: Introduction to upgrading


Como melhorar a segurança do asp.net Membership?

Question: Tem como proteger aquele cookie que fica evidente ao fazer login em um site que usa o asp.net membership ? Sei que basta copiar ele pra que "clone" a sessão de login e desse modo fica muito vulnerável principalmente a ataques man in the middle .
A única solução é usar SSL ?
Answer: Para qualquer Cookie que você precise criar, independentemente de linguagem/plataforma, é altamente recomendável que seja definida a flag HttpOnly que te ajuda a previnir manipulações do seu Cookie através de JavaScript, e consequentemente ataques XSS, além da flag Secure, que a própria W3C padronizou como uma forma de evitar que sejam aceitas requisições com Cookies através de canais inseguros.
De fato, se alguém conseguir de alguma forma gerar o conteúdo exato do seu Cookie de autenticação, ele pode muito bem alterar o Cookie no browser e utilizá-lo. Mas temos que considerar que o próprio Asp.Net já cuida bem da parte de encriptar seus Cookies através da configuração do machineKey, o que torna essa prática bem improvável.
Por outro lado, o usuário nem precisaria gerar o conteúdo se for facilitado o roubo dessas informações. Com a flag HttpOnly, você impede que scripts maliciosos em JavaScript consigam ler seus Cookies e a flag Secure garante que a aplicação só irá entender o conteúdo se o mesmo estiver trafegando por SSL, que é obrigatório hoje em dia para evitar tráfego de informações em texto puro, que poderiam ser facilmente lidas por ataques man-in-the-middle.
Em Asp.Net, as configurações podem ser feitas através de configurações no Web.config com o elemento httpCookies:
<httpCookies httpOnlyCookies="true" requireSSL="true" />

Para qualquer Cookie, você consegue setar programaticamente:
HttpCookie myCookie = new HttpCookie("myCookie");
myCookie.HttpOnly = true;
Response.AppendCookie(myCookie);

Especificamente no caso do Cookie de autenticação, é possível forçar a flag secure no elemento forms:
<authentication mode="Forms">
    <forms cookieless="UseCookies" requireSSL="true" />
</authentication>

Comment: @DiegoValadares você precisa contratar um certificado SSL e configurá-lo no seu servidor web para que ele possa servir as respostas como https. Para ambientes de desenvolvimento, você consegue instalar certificados próprios apenas para testar a sua instalação. No IIS existe uma configuração específica para [self-signed certificates](http://weblogs.asp.net/scottgu/tip-trick-enabling-ssl-on-iis7-using-self-signed-certificates)
Comment: Diego , tentei usar o requireSSL e recebi o seguinte erro "
O aplicativo está configurado para emitir cookies seguros. Esses cookies requerem que o navegador emita a solicitação sobre SSL (protocolo https). No entanto, a solicitação atual não é sobre SSL. ", vc sabe me dizer como implemento o SSL ?


Typescript - Jest: Mock indirect function call

Question: Let's say I have two files, that contain the following functions:
file-a.ts:
import { fnB1 } from "./file-b";

export function fnA(): number { return fnB1(); }

file-b.ts:
export function fnB1(): number { return fnB2(); }
export function fnB2(): number { return 5; }

To summarize it's like this:

In my test file file-test.ts, I now want to test fnA but I want to mock fnB2 to not return 5 but to return 42. How can I achieve that?
Answer: I think I found a possible solution:
file-test.ts:
import { fnA } from "./file-a";
import * as FileB from "./file-b";

it('should work', () => {
   jest.spyOn(FileB, 'fnB2').mockReturnValue(42);

   expect(fnA()).toBe(42);
}

But in order to make this work, I had to change file-b.ts. I had to add a exports. in front of the function call:
export fnB1() { return exports.fnB2(); }
export fnB2() { return 5; }


How to display default drupal search block in twig template

Question: In twig_tweak module before version 2 (for Drupal 8) I could place the following code in my page twig template and it would work:
<code>{{ drupal_block('exposedformsearch_contentpage_1') }}
</code>
This would display put the default site search box.
After upgrading to version 2, this doesn't work anymore and see the following message on the page:
<code>This block is broken or missing. You may be missing content or you might need to enable the original module.
</code>
I tried using the command:
<code>{{ drupal_block('search_form_block') }}
</code>
That displays the same error message.
Does anyone know what the the correct call is? I can't seem to find any documentation anywhere as to what the replacement call should be.
Thanks.
Answer: Ok I have found the solution after playing around for a bit. The correct call now is:
<code>{{ drupal_entity('block', 'exposedformsearch_contentpage_1') }}
</code>


Database Each table Usage

Question: Where can I see the each table usage, which is getting created in default installation of a Drupal site.
Likes node table - used to store all nodes in them. For other tables where i can get the information. Any documentation for each table usage in database??
Thanks in advance.
Answer: Run below query on your database and see last column in the result table.
SHOW TABLE STATUS

See Screenshot below for example.
Answer: For databases that implement information schema, use:
SELECT table_name, table_comment
FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema='my_cdrupal_database'

Answer: Just to add the Drupal-y answer...
You can install the Schema module for that, amongst its features is:

Schema documentation: hyperlinked display of the schema's embedded documentation explaining what each table and field is for.
Comment: Totally forgot about that. I guess because it was always faster for me to just look at schema in db client.
Comment: i don't want schema.I want each table description and looks like schema module doesn't provide me with that.
Comment: Did you read the description in the answer? That's exactly what it does

Database Each table Usage


How to generate a report by duplicate in VS 2008 with Microsoft Report

Question: I need the same document to be printed twice, but with one single different word when the user does one click. I have tried everything i could come up with but i can't find a way to do it. Any recommendations?
Comment: What word do you need changing? Is it in a field? It id always the same word that you need to change to another exact same word or is it variable? Do you need to change one occurence of the word or all? Is it in the body or header?
Also, is it a report run in server or client mode?
Answer: There are severals ways to do it, which depends of what you want to change and when.
You could use parameters in your report. What you do is define in your report a parameter and changes its value to whatever suits your need. In local mode, this usually works out pretty welll since you can use parameter pretty much everywhere. I do not know if it works with server mode.
I personally can't see a reason why it doesn't work, but should it happen, there is another way to do it but I don't recommend it. When you click on your button, you can create a copy of your report (i.e. create a new file) and modify the content of the report according to your need. In other word, change the content of the rdlc file to suit your need. RDLC is in fact a xml file so it's possible to modify it, then open the newly created file. Again, I do not know if it works with Server mode. Like mentionned, I do not recommend this option as it implies string manipulation and if you don't know where you're going, you might end up getting more frustation than solutions. If you know exactly what string to change and that this string is not repeated anywhere, you can use reg exp, but since XMl is not a regular language, you have to be really careful when doing so.
Hopes that help.


Sincronizar movimentos do player e do host

Question: Olá. Estou fazendo um projeto de escola e estou seguindo o tutorial do Unity Multiplayer Netorking. Tudo funcionou corretamente, porém o tutorial ensina a ter um player e um host, ambos cada um com um "personagem" que se movimenta independentemente do outro. O que eu preciso fazer é o "personagem" de cada um deles terem movimentos sincronizados. Por exemplo se eu mover um deles pro lado, preciso que o personagem do outro jogador também se mova para o lado. Alguém sabe como posso fazer isso?
O tutorial que segui pra fazer é esse: https://unity3d.com/pt/learn/tutorials/s/multiplayer-networking
Answer: Olá,
Não sei até que ponto do tutorial você seguiu, mas nesse tutorial, o que faz com que o os personagens tenham movimentos independentes (cada um controla o seu) é a verificação no código de movimentação do personagem.

if (!isLocalPlayer)
{
    return;
}

Ele checa se você é o localPlayer ou seja, o controlador daquele personagem, e então "cancela" a execução do script, caso você não seja.
Assim você acaba controlando só o seu personagem. Se você tirar esse if do código de movimentação. Quando o host ou o player se mexerem o outro se mexerá também.
Espero ter ajudado. Abçs


how to change src of an img element even before the DOM loads

Question: I was wondering if there exists a carousel which has a bunch of images  shown to the user, but lets say that based on the User, the img shown in the carousel needs to change to something else. How can one change the img src, even before the page loads?  The DOM does not actually exist for us to get the dom element for img element and change its src to the new image? how can one do it?
I was thinking may be have a inline script tag within the head section where the async is set to false which does not block the loading of the DOM. I am not sure. Please let me know if there are any other alternatives or html5 features for this
Comment: If you want to change the image source before page load you must do it on the server side.
Comment: You could potentially insert the image as soon as the page loads with AJAX, so it would appear to load as soon as the page loaded. But before page load is impossible with javascript, excluding node-js. You need a server side language like PHP, ASP.NET C#, or node-js.
Answer: You can't use JavaScript to access the DOM before it is loaded. The best way to deal with this is to compile your HTML on the server-side using a templating language like handlebars (depends on what your backend language is). However, if this isn't an option you could also just put a place-holder loading symbol in the place of your image and then dynamically add a src url once your  has loaded in the DOM and then use JS or jQuery to change the src attribute.
Hope that helps!
Answer: It doesn't make much sense to literally "change" the source before the DOM loads, otherwise why did you set that source to begin with, right?  But as others are saying, Javascript will be executed the moment it comes to the browser, so if you are having the image sources loaded as per any session criteria, etc. etc., you could use the event that when the page is loaded, to perform any particular AJAX requests, e.g. using jQuery:
$(document).ready(function() {
    $.ajax({
        url: '/getPhotos',
        success: function(res) {
            res = JSON.parse(res);
            for (var i in res) {
                $('ul#carousel').append('

');
            }
        }
    });
);

Something like what you are after?
Comment: could i use promises in javascript where the callback executes once teh dom is ready??
Comment: If jQuery is not your cup of tea, you could just use window.onload - And yes I don't see why you couldn't use that alongside a [promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)


Show via direct proof that $k(k+1)(k+2)$ is divisible by $6$.

Question: How do I show via direct proof that $k(k+1)(k+2)$ is divisible by $6$. I showed it was divisible by $2$ because at least one of the multiples is even but could not figure out how to show it is divisible by $3$. I tried making $k$ even or odd and substituting $2q$ or $2q+1$ but have not made much progress. Does anyone have any tips as to what direction I should take? Thanks!
Comment: look at $k+2 \choose k-1$ (if it counts as a direct proof)
Comment: How about three consecutive numbers have the form $3k, 3k+1, 3k+2$?  Or $3k-1, 3k, 3k+1$, or finally, $3k-2, 3k-1, 3k$...
Comment: Why is at least one of the *factors* even?  Why can't they all be odd?  Can you modify that to argue that one of the factors must be divisible by 3?  Is i possible that $k$ is not divisible by 3?  If so then can $k +1$ not be divisible by 3.  If so would it then be possible for $k +2 to be divisible by 3?  Hint what is the remainder of k/3?  What is the remainder of (k+1)/2?  What is the remainder of (k+2)/3?
Comment: Hint: exactly one of $n$ consecutive numbers is divisible by $n$.
Comment: Just relate it to $\Bbb Z_3=\{[0],[1],[2]\}$
Comment: $k(k+1)(k+2)=6\binom{k+2}{3}$ :P
Answer: By the division algorithm, $k$ divided by $3$ yields a remainder of $0$, $1$, or $2$. In other words, there are some integers $q,r$ such that $k=3q+r$ where $r=0,1,$ or $2$.
If $r=0$, then $k=3q$ is divisible by $3$. If $r=1$, then $k+2=(3q+1)+2=3(q+1)$ is divisible by $e$. If $r=2$, then $k+1=(3q+2)+1=3(q+1)$ is divisible by $3$. Therefore, in all cases, at least one of $k$, $k+1$, and $k+2$ is divisible by $3$.
Comment: Thank you so much! Could not ask for a better explanation!
Comment: Glad to help. When you need to prove a  "low level" fact about the integers (like at least one of three consecutive integers is divisible by 3), the division algorithm is probably your best tool. :)
Comment: @user6797501 if you like an answer, upvote it. accept the best one. this is how you say thank you.
Answer: If $k = 6a+b$,
where $0 \le b \le 5$,
then
$\begin{array}\\
k(k+1)(k+2)
&= k(k^2+3k+2)\\
&= k^3+3k^2+2k\\
&= (6a+b)^3+3(6a+b)^2+2(6a+b)\\
&= (6a)^3+3((6a)^2b+6ab^2)+b^3+3(36a^2+12ab+b^2)+12a+2b\\
&= 6(6^2a^3+18a^2b+ab^218a^2+6ab+2a)+b^3+3b^2+2b\\
&= 6(6^2a^3+18a^2b+ab^218a^2+6ab+2a)+b(b+1)(b+2)\\
\end{array}
$
By directly computing
$b(b+1)(b+2)$
for $0 \le b \le 5$,
the values are all divisible by $6$
(they are
$0, 6, 24, 60, 120, 210$).
Therefore,
the product is
always divisible by $6$,
being the sum
of two terms
each of which
is divisible by $6$.


Java ObjectOutputStream Not Writing to ZipEntry

Question: I am trying to serialize an object into a ZipEntry using an ObjectOutputStream, however it doesn't appear to be writing anything because when I print the byte array produced, it shows null. I tried writing a string with the ZipOutputStream, and upon printing the resulting byte array got a sizeable result. SO my question is: why is the objectoutput stream not correctly writing into the ZipEntry. (ConfigEntry does implement Serializable).
  String s = "Tired, Exhausted";
  ConfigEntry con = new ConfigEntry("rand", "random", 3);

  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  try {

  ZipOutputStream zos = new ZipOutputStream(baos);
  ZipEntry entry = new ZipEntry("test.txt");
  ObjectOutputStream obs = new ObjectOutputStream(zos);

  zos.putNextEntry(entry);

  obs.writeObject(con);
  obs.close();
  zos.closeEntry();
  zos.close();

  } catch(IOException ioe) {
  ioe.printStackTrace();
  }

  os = bs.getOutputStream();
  byte[] result = baos.toByteArray();
  String test = new String(result, "UTF-8");
  Log.v("Mac Address", test);
  Log.v("Mac Address", Arrays.toString(result));

Answer: ByteArrayOutputStream baos = new ByteArrayOutputStream();

This baos goes out of scope after the try block. You are writing to one baos and you are looking into another baos declared in an outer scope, probably an instance member of the class.
Comment: Sorry, that was actually my bad, I meant to put the try statement after the ByteArrayOutputStream, as it is in my code. Sorry for the poor code. Edited my question.


How to concat a number of arrays as a single array in C#?

Question: How to concat a number of arrays as a single array in C#?
using System;
using System.Linq;

namespace Exp2
{
    class Program2
    {
        static void Main(string[] args)
        {
            Program2 pgm = new Program2();
            Console.Write("Enter number of Arrays do you want : ");
            int numberOfArrays = int.Parse(Console.ReadLine());
            int[] narray = new int[numberOfArrays];
            int[] el=new int[100];
            int[] el1 = new int[100];
            for (int i = 0; i < narray.Length; i++)
            {
                Console.Write("Enter number of Elements do you want in Array {0}: ",i+1);
                int ai = int.Parse(Console.ReadLine());
                for (int j = 0; j < ai; j++)
                {
                    Console.Write("Enter the {1} Elements do you want in Array {0}: ", i+1,j+1);
                    el[j]= int.Parse(Console.ReadLine());
                }
                el1 =el1.Concat(el).ToArray();
            }
            foreach (int val in el1)
            {
                Console.Write(val+" ");
            }
            Console.ReadLine();

        }
    }
}

Input:
Enter number of Arrays do you want : 3
Enter number of Elements do you want in Array 1: 3
Enter the 1 Elements do you want in Array 1: 5
Enter the 2 Elements do you want in Array 1: 6
Enter the 3 Elements do you want in Array 1: 9
Enter number of Elements do you want in Array 2: 4
Enter the 1 Elements do you want in Array 2: 5
Enter the 2 Elements do you want in Array 2: 8
Enter the 3 Elements do you want in Array 2: 2
Enter the 4 Elements do you want in Array 2: 2
Enter number of Elements do you want in Array 3: 5
Enter the 1 Elements do you want in Array 3: 32
Enter the 2 Elements do you want in Array 3: 4
Enter the 3 Elements do you want in Array 3: 6
Enter the 4 Elements do you want in Array 3: 6
Enter the 5 Elements do you want in Array 3: 4

Output:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0         0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 6 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 8 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 4 6 6 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

How can I display only the input of user?
Comment: Essentially you have only one Int array and not multiple array
Comment: You can use `List` instead of `int[]` and create/fill them dynamically
Answer: If you don't know the number of elements, you can use List rather than array.
Concat is easy in list.
List<int> list1 = new List<int>();
List<int> list2 = new List<int>();
// Do your action to assign elements in list1 and list2

// To add list1 into list2
list2.AddRange(list1);

Comment: but using this solution you cannot differentiate between the sublist elements.
Answer: You can use a dictionary and a List :
The dictionary maps the list to its number.
var dict = new Dictionary<int, List<int>>();

Console.WriteLine("Enter number of Arrays do you want : ");

int numberOfArrays = int.Parse(Console.ReadLine());

for(int k = 1; k < numberOfArrays; k++)
{
    var currentArray = dict[k] = new List<int>();

    Console.WriteLine($"Enter array {k} Length:");

    int arrayLength = int.Parse(Console.ReadLine());

    for (int j = 0; j < arrayLength; j++)
    {
       Console.WriteLine($"Enter the {j}-th Element you want in Array {k}: ");
       currentArray.Add(int.Parse(Console.ReadLine()));
    }

}

foreach(var pair in dict)
{
     Console.WriteLine($"{pair.Key}-th array elements : ");

     foreach(var element in pair.Value)
     {
        Console.WriteLine(element);
     }
}

Answer: Don't use "foreach" loop use "for" loop like this .
for (int i= 0;i< el1.Length;i++)
{
   if (el1[i] != 0)
   Console.Write(el1[i] + " ");
   else continue;
}

warning: In some input cases you might get extra number as last element of output
Answer: It Work now,
using System;
using System.Collections.Generic;
using System.Linq;

namespace Exp2
{
    class Program2
    {
        static void Main(string[] args)
        {
            Program2 pgm = new Program2();
            Console.Write("Enter number of Arrays do you want : ");
            int numberOfArrays = int.Parse(Console.ReadLine());
            int[] narray = new int[numberOfArrays];
            int[] el=new int[100];
            int[] el1 = new int[100];
            List<int> list1 = new List<int>(100);
            List<int> list2 = new List<int>(100);
            for (int i = 0; i < narray.Length; i++)
            {
                Console.Write("Enter number of Elements do you want in Array {0}: ",i+1);
                int ai = int.Parse(Console.ReadLine());
                for (int j = 0; j < ai; j++)
                {
                    Console.Write("Enter the {1} Elements do you want in Array {0}: ", i+1,j+1);
                    //list1[j]= int.Parse(Console.ReadLine());
                    int kj = int.Parse(Console.ReadLine());
                    list1.Add(kj);
                }
                //el1 =el1.Concat(el).ToArray();
                list2.AddRange(list1);
            }
            foreach (int val in list2)
            {
                Console.Write(val+" ");
            }
            Console.ReadLine();

        }
    }
}

Thank you all..!


Why is Hausdorff needed here?

Question:
Let $\{X_i, i \in I\}$ be a family of Hausdorff spaces, where $I$ is an infinite index set and every $X_i$ is Hausdorff and contains at least two different points. Prove that the product space $X=\prod_{i\in I}X_i$ does not contain isolated points.

Attempt: Let $x = (x_i)_{i\in I} \in X$. Consider a basic open neighborhood $U$ of $x$. Then $U = \prod_{i \in F}U_i \times \prod_{i\in F^c}X_i$ where $F\subset I$ is finite and every $U_i$ is open in $X_i$. Define $y \in X$ as follows:
$$y_i = \begin{cases}x_i, \text{ if }i\in F \\ w_i, \text{otherwise}\end{cases}$$
where $w_i$ is a point in $X_i$ different from $x_i$. Now clearly $y \in U \cap (X\setminus \{x\})$ so $x$ cannot be an isolated point of $X$. Since $x$ was arbitrary $X$ contains no isolated points.
What's the problem with this proof? If it's correct then the assumption that every $X_i$ is Hausdorff is redundant!
Thanks.
Answer: You are right: in full generality, a product space contains an isolated point if and only if all its factors contain an isolated point and all but finitely many of them are one-point spaces.
If this is the case, then $x\in\prod\limits_{i\in I}X_i$ is isolated if and only if $x_i$ is isolated for all $i\in I$ (such that $X_i$ is not a singleton).
Answer: Another way to convince yourself that this statement does not require Hausdorffness assumption, without actually proving either version: fix any $(X_i)_i$ such that each $X_i$ contains at least two distinct points. For each $i$, let $X_i'$ have the same underlying set as $X_i$, endowed with the discrete topology.
Then it is easy to check the identity mapping $X'=\prod_i X_i'\to X$ is continuous and by the Hausdorff version of your statement, $X'$ has no isolated point. Since the preimage of an isolated point by a continuous bijection is obviously an isolated point, it easily follows that $X$ has no isolated points, either.

Why is Hausdorff needed here?


Repeated measures ANOVA in R with monotonically increasing, nonlinear timeseries data

Question: I am trying to determine whether there is a difference between two
treatments, in a response variable that was measured repeatedly over
time. We know (from theory and observation) that the response variable
increases monotonically but nonlinearly as a function of time,
asymptotically approaching some maximum.
It seems like repeated measures ANOVA would be the thing to use here,
but I am having difficulty with it. I definitely do not completely
understand repeated measures ANOVA. (I also don't think I really
understand what my null hypothesis is, other than 'are these two
treatements different').
First, I'll simulate some data using a saturating function plus random
noise:
library(dplyr)
library(tidyr)
library(purrr)
library(ggplot2)

# Function to create simulated data
mm_fun <- function(args) {
  time <- args$time
  Vmax <- args$Vmax
  half.sat <- args$half.sat
  y <- (time * Vmax)/(time + half.sat) + rnorm(length(time), mean=0, sd=1)
  df <- data.frame(time=time, y=y)
}

# The domain of the data
time <- 0:100 # All data sets have the same domain
set.seed(0)

# List of parameters with which to make 6 data sets
param_l <- list(
  a1 = list(time=time, Vmax = 20, half.sat=25),
  a2 = list(time=time, Vmax=22, half.sat=28),
  a3 = list(time=time, Vmax=18, half.sat=23),
  b1 = list(time=time, Vmax=5, half.sat=50),
  b2 = list(time=time, Vmax= 5.5, half.sat=53),
  b3 = list(time=time, Vmax=4.5, half.sat=48)
)

# Calculate data from parameters
d <- map_df(param_l, mm_fun, .id = "sample")

# Add column identifying reps
d$treatment <- substr(d$sample, 0, 1)

# Plot
ggplot(d, aes(x=time, y=y, colour=treatment)) +
  geom_line(aes(group=sample))

Clearly treatment a is behaving differently somehow than treatment
b, but within a treatment, there isn't much difference between
replicates.
I've coded repeated measures ANOVA as follows:
# Try a repeated measures anova
mod <- aov(y ~ time + Error(treatment/time), data=d)
summary(mod)

##
## Error: treatment
##           Df Sum Sq Mean Sq F value Pr(>F)
## Residuals  1  14169   14169
##
## Error: treatment:time
##           Df Sum Sq Mean Sq F value Pr(>F)
## time       1   3047    3047   2.463  0.361
## Residuals  1   1237    1237
##
## Error: Within
##            Df Sum Sq Mean Sq F value Pr(>F)
## Residuals 602   1410   2.343

I read this as reporting no significant difference by treatment and no
interaction between treatment and time, both of which seem wrong. But
then I don't really understand how Error() works, or what an appropriate null hypothesis for these treatments are different would be.
Answer: Why not use a linear mixed model instead? You can consider sample to be a random effect in this context. The relationship might not be linear, but a monotone transformation yields an approximately linear relationship:

Square-root transformation of time ($\sqrt{\text{time}}$)
Logarithmic transformation of time ($\log(\text{time} + 1)$, add one because your time series starts at 0 and $\log(0)$ is undefined)
Squared transformation of the response ($y^2$)

I don't know how to include the output on this forum yet, but here is an example using your data:
plot(y ~ log(time + 1), data = d)
plot(y ~ sqrt(time), data = d)
plot(y^2 ~ time, data = d)

library(lme4) # for linear mixed models
# Using a square-root transformation:
LMM.sqrt <- lmer(y ~ sqrt(time) * treatment + (1|sample), data = d)

# Or a logarithmic relationship:
LMM.log <- lmer(y ~ log(time + 1) * treatment + (1|sample), data = d)

# Squared response:
LMM.sqry <- lmer(y^2 ~ time * treatment + (1|sample), data = d)

Now sample is a random effect (I guess this is also what you will want to put in Error() for the RM-ANOVA) affecting the intercept.
The best model in terms of AIC turns out to be the log-transformed model:
anova(LMM.sqrt, LMM.log, LMM.sqry)

You can get the effect of treatment by looking at the fixed effects under the summary:
summary(LMM.log)

You can get confidence intervals for inference:
confint(LMM.log)

The effect of the random effect is small, but significant at $\alpha = 0.05$. Treatments differ significantly and the interaction between time and treatment is also significant. This means a starts higher than b and also increases with time more than b.
Answer:
I also don't think I really understand what my null hypothesis is, other than 'are these two treatements different'

In a traditional hypotheses setup, you would have:
H: Y differs between treatments A & B
H0 (null): Y does not differ between treatments A & B
And I'll definitely second Frans' advice to run this as a linear mixed model instead (you might also see it called a linear mixed-effects model - either way, abbreviated as LMM). Some of the advantages to this approach are explained here: http://www.theanalysisfactor.com/advantages-of-repeated-measures-anova-as-a-mixed-model/
Comment: When you estimate a slope for time, the null-hypothesis is that this slope is zero (i.e. there is no difference in $y$ as time increases).
Comment: The thing I don't understand is: what does "is different" mean? In the example I gave, the two treatments are the same at t=0 (and very close to one another for some time after that), and different at a later time. So H0 is both true (at time 0) and false (at later times).


Tablix in a RDLC report with fixed height

Question: I have a tablix inside a rectangle at middle of my report and when it grows in rows, the page grows too and borders fall in another page. How can I set the tablix to fill it's rows just until rectangle's borders?
Comment: What exactly means "when it grows in rows"? Does it mean you get more rows due to having more rows in the underlying data or does it mean the row height increased for example because of line breaks / longer text values?  I am not sure what problem you solved here and if I have the same or not.
Answer: On textboxes on Tablix, Rightclick and goto TextBox Properties, in Sizing Options uncheck Allow height to increase.


Apache Redirect directive stops working after 400 odd redirects

Question: A business partner asked us to implement a list of 1000+ URL redirects from http://site1.com to https://site2.com. We set up an (old) Apache 2.2 which we cannot upgrade as follows:
<VirtualHost *:80>
  ServerName site1.com
  ServerAlias *.site1.com
  Redirect 301 /url-0001 https://site2.com/...
  Redirect 301 /url-0002 https://site2.com/...
  Redirect 301 /url-0003 https://site2.com/...
  ...
  Redirect 301 /url-1234 https://site2.com/url-...
  RedirectMatch 301 ^(.*)$ https://site2.com/
</VirtualHost>

Problem:
Any redirect after the first 400+ does not work correctly, i.e., instead of the following redirect:
http://site1.com/url-410 --> https://site2.com/foo

we get:
http://site1.com/url-410 --> https://site2.com/url-410

It seems the URI is not being rewritten correctly.
Question:
Is there a limit of how many redirect directives one can use in a single vhost or am I missing something obvious here?
Answer: Root Cause: Redirect #400 looked as follows:
Redirect 301 / https://site2.com/

All URLs after this one got 404.
Solution: After removing this redirect everything worked as expected.


How to configure Apache to log IPs of invalid HTTP requests

Question: My Apache/2.4.29 (Ubuntu) creates access log entries with pseudonymized IPs:
220.127.116.11 22.214.171.124 - - [09/Aug/2020:11:30:51 +0200] "GET / HTTP/1.1" 200 279 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36"

When I connect with ncat and do an invalid HTTP request, the IP is not logged.
[09/Aug/2020:11:31:38 +0200] "test\n" 400 226

How do I configure Apache to log the IP in this case, too?

The following log format is used:
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined

Logging is enabled using this VirtualHost directive:
CustomLog ${APACHE_LOG_DIR}/access.log combined

Pseudonymization is done with mod_log_ipmask (https://github.com/webfactory/mod_log_ipmask).
Comment: How exactly did you already configure Apache's logging?
Comment: @TeroKilkanen I tried disabling the module, resulting in unmasked IPs for valid requests, but still no IPs for invalid requests.
Comment: @MichaelHampton I added some information on logging configuration. Please let me know if you need more.
Answer: The output of
apache2ctl -DDUMP_CONFIG | grep -vE "^[ ]*#[ ]*[0-9]+:"
showed that the logging configuration for <VirtualHost xxx:80> differed from the logging configuration for <VirtualHost xxx:443>. It works as expected now.


How to combine two tables in SQL with no relation between each other?

Question: Given two tables: Dim People (which contains all the sales people of the company) and Items (which contains all the items that the company sells).
I would like to combine both tables as follows. Let's say that in Dim People we have 3 rows (Sherin, Alvaro, Emad) and in Items we have 4 (1, 2, 3, 4), I would need to have something like this:
Sherin-1
Sherin-2
Sherin-3
Sherin-4
Alvaro-1
Alvaro-2
Alvaro-3
Alvaro-4
Emad-1
Emad-2
Emad-3
Emad-4

How would build the query to return this result?
Thanks in advance!
Didn't even know what to do because I've never combined two tables that have no connection between each other. I expect something like above.
Comment: Do a `CROSS JOIN`.
Comment: Tables do not need to have a "connection" in order to use them joined together in a query. (I assume that you mean a referential constraint when you say "connection", since I am not aware of any other way to "connect" tables.)
Answer: You can try cross join here:
SELECT *
FROM People, Items

Or explicitly:
SELECT *
FROM People
CROSS JOIN Items

Comment: I'd recommend an explicit CROSS JOIN, i.e. `FROM People CROSS JOIN Items`. It's 2022 now.


how can i update UI to show "WebRTC data channel" at match section in use by httptoolkit-server?

Question: enter image description hereI've installed all httptoolkit-server and also the httptoolkit-ui to capture data and mock it up, i've installed mockrt,mockttp,docker,... plugin's too but i cant see "WebRTC data channel" in the match section like the image below
(picture is from httptoolkit blog : https://httptoolkit.tech/blog/developer-tools-decentralized-web/
how can i capture and mock RTC connection's in httptoolkit as it shown ?
Answer: I'm the developer of HTTP Toolkit. The feature you're looking for does not exist yet.
That blog post is just a proposal and an announcement of funding, and the screenshot is only an example mockup of the future UI.
This will be available within the new few months (keep an eye on that blog and the mailing list for updates) but it's not available today.
(I think you also emailed me earlier asking about this, and I replied there - feel free to respond by email if you want to discuss this further).
Comment: Thank you,
I am counting down from now :D
Comment: Just an update: this is now released! If you launch a Chromium-based browser via HTTP Toolkit, all traffic sent & received over WebRTC connections will be intercepted and will appear in the app for debugging.


ASP.NET MVC 4 - Preventing Direct Access to Custom Error Pages

Question:
It won't let me submit with the codes above, had to take a screenshot.
As It can be seen above, I'm using customError pages to handle appropriate errors. Everything works as expected, for instance when a user gets an unhandled exception, on my local the URL is changing as expected :
http://localhost/SystemAdministration/Error
However, I don't want users to access this page by typing the url to their browser. Whats the best way to restrict direct access to these error pages and only show them when the related error has occured?
Thanks
Comment: You could create an `ActionFilter` that checks the status code for something other than 200. If it's 200, then redirect somewhere else (homepage perhaps?). Decorate your error page action(s) with this newly created filter.
Comment: Hello, It looks like a nice suggestion however couldnt get it work. Attached a new custom ActionFilter to my "NotFound" action and on it's onActionExecuting method, my  filterContext.RequestContext.HttpContext.Response.StatusCode returns 200. I gotta somehow get the statusCode prior to requesting the "NotFound" action, but how?
Answer: You can create a custom action filter to do that. It's explained in ASP.NET MVC Custom Action Filter To Restrict Direct Access To Action Method. Hope this helps


slope in a log-transformation

Question: Given y(x) = A*exp(x+c). I'm converting the y-axis into a log-scale. Then I calculate the slope at a certain point.
Am I'm allowed to re-transform this value dy(x)/dx? Hence: exp(dy(x)/dx)?
Comment: Presuming $A$ to be positive, it seems odd to have a multiplicative constant term $A$ *and* an additive term in the $\exp$, since they serve the same function. $A\exp(x+c) = Ae^c \exp(x) = A^* \exp(x)$ (or if you prefer, $A\exp(x+c) = e^{x + c+\log(A)}=e^{x + c^*}$).
Comment: Correct, didn't have these rules in my mind anymore. Thank you!
Answer: Exponentiating the derivative of the log is not the same as the derivative of the original function ($\log$ and $\exp$ aren't linear operators):
$$\frac{d}{dx} Ae^{x+c} = Ae^c \frac{d}{dx} e^x = Ae^{x+c}$$
If you take logs of $Ae^{x+c}$ you get $\log A + c + x$, and so the slope on the log scale is 1. If you exponentiate that you get $e$. Clearly that's not going to be correct; the slope isn't constant.
Comment: Thank you! I've a similar question: I'm interested in x(f(x)=1)=? and I perform a logarithmical transformation to get a better regression => log(x(f(x)=1)=log(?)? Then I can make a exp-transformation on this regressed x-value. And when I'm interested in the slope at this x-value, am I'm forced to apply the derivative on the log-transformation or am I'm also allowed to do it without?
Hope that is understandable?
Comment: Sorry I couldn't follow that at all. If you have a new question and can ask it in a clearer way, you could post it

slope in a log-transformation


Why is my twig variable not working inside my block twig?

Question: I have a field I'm pulling into a block twig template block--block-03.html.twig, and it outputs fine by itself (= {{content.field_content_side}}). But when I put it inside of a conditional it is not working.
Here's my code to illustrate what I mean:

{{ content.field_content_side }}

{% if content.field_content_side == 'left' %}col-sm-push-7{% else %}wtf{% endif %}

The output is here:

Why is it recognizing the twig variable correctly as left (= 1st line of my code), but in the conditional it is saying it's not left (= 2nd line of my code)?
Answer: Because the field is being rendered, which is different than evaluating its value. content.field_content_side is a render array which holds a lot more than just 'value'.
Try:
{% if node.field_content_side.value == 'left' %}

To get this in a block, you would add this to mytheme.theme:
/**
 * Implements hook_preprocess_block().
 * @param $variables
 */
function mytheme_preprocess_block(&$variables) {
  if (isset($variables['elements']['content']['#block_content'])) {
    $variables['block_content'] = $variables['elements']['content']['#block_content'];
  }
}

Then:
{% if block_content.field_content_side.value == 'left' %}

Comment: It is basically appending the field data in to the block so it is available in the template, similar to having access to the node object in a node template hence the initial `if node.field_content_side.value == 'left'`. So `block_content` is the block object and fields. Render arrays can't be used that way, and its one of the things many people run into when trying to do something like this.
Comment: I updated the question above to indicate its inside of a block twig template, not a node. I tried `content.field_content_side.value` which did not work either.
Comment: Then you need to add it in. I will update the answer.
Comment: `content.field_content_side.value` is never going to work from a render array.
Comment: you are a life saver. I dont entirely understand what the preprocess function is doing here, but it works and has saved me lots of time. Thank you!


Multithreading multiple locks seem slower than single lock

Question: I was reading on multithreading in Java and using synchronized blocks.  Suppose I have two different, independent synchronized blocks.  I can have them run in parallel, by using a lock each for both the synchronized blocks.  But if I use the same lock for both synchronized blocks, I think only one can run at a given time.
Am i wrong to think so? If no, why am I getting the below strange result?
Assume I have two independent operations, increment1 and increment2, called by a different thread each.
public class AppMultipleSynchronization {

    private static int counter1 = 0;
    private static int counter2 = 0;

    private static Object lock1 = new Object();
    private static Object lock2 = new Object();

    public static void increment1() {
        synchronized (lock1) {
            counter1++;
        }
    }

    public static void increment2() {
        synchronized (lock2) {
            counter2++;
        }
    }

    public static void main(String[] args) {

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100000000; i++) {
                    increment1();
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100000000; i++) {
                    increment2();
                }
            }
        });

        long startTime = System.currentTimeMillis();

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long endTime = System.currentTimeMillis();

        System.out.println("total time taken: " + (endTime - startTime) + "ms");
        System.out.println("counter1: " + counter1 + "\ncounter2: " + counter2);
    }
}

As you can see, I am using a different lock for for both increments.
To use the same lock, use the exact same program, replace with lock1 in both cases.
Output in case of two locks:
    total time taken: 13437ms
    counter1: 100000000
    counter2: 100000000

Output in case of single lock:
    total time taken: 5139ms
    counter1: 100000000
    counter2: 100000000

Comment: Using JMH, assuming I set everything up correctly, I don't see such a dramatic difference in average execution time: One lock, `487.514 ± 22.413 ms/op`; Two locks, `1064.114 ± 24.043 ms/op`. That's only just over a half second longer to execute. Note I looped ten million times instead of 100 million times.
Comment: How many processors do you have?  Try to find out the time taken instead of synchronized(AppMultipleSynchronization.class) use synchronized(lock1)
Comment: There are a bit too many factors to figure out experimentally... First, you're synchronizing on non-final fields. Even though descriptions on what final does for synchronized block only mention safety and you don't change the value, adding final cuts the time in half in my tests. Secondly, some big optimization must be kicking in - if I put the code of main method in a loop the times taken by different iterations are wildly inconsistent, sometimes 10 times longer. And thirdly, for me locally the approach with two locks is faster than both on lock1.
Comment: Almost every time a question like "the performance of this Java thing doesn't behave how I expect it to" comes up the correct answer is [your benchmark is wrong](https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java). Writing correct micro-benchmarks in Java is hard and if you don't at least use an existing tool/library for this, then the odds are extremely high that you're not considering all the possible pitfalls.
Comment: @Gunwant i had tried lock1 instead of AppMultipleSynchronization.class..but still same result...
Comment: Also : how many loops is `t1` able to do before `t2` even starts?
Answer:
am i wrong to think so? if no, why am i getting the below strange result?

No you are not wrong.  If you are using 2 locks then 2 threads can be executing the 2 different blocks at the same time.
What you are seeing is most likely because these sorts of fine grained, threaded, performance tests are very subtle.  This may have much more to do about branch and lock prediction than about true runtime.  The JVM makes guesses about whether a lock should be tested in a spin loop versus a true mutex wait/queue.  It can dramatically optimize this code given that the actual work is just ++.  It may also be that t1.start() starts and runs so fast that it finishes before the t2.start() can be executed.
If you change the lock body to be more substantial, you should start to see that the 2 locks will result in faster wall clock runtime.  For example, if you do a loop of ++ operations in the block:
public static void increment1() {
    synchronized (lock1) {
        for (int i = 0; i < 100000000; i++) {
            counter1++;
        }
    }
}
...
public void run() {
    for (int i = 0; i < 10000; i++) {
        increment1();
    }
}

Then with 1 locks I get:
total time taken: 62822ms
counter1: -727379968
counter2: -727379968

but 2 locks gets:
total time taken: 30902ms
counter1: -727379968
counter2: -727379968

Lastly, the JVM does a whole bunch of class loading, gcc -O3 equivalence, and machine code inlining during the first seconds and even minutes of runtime.  Anytime you are trying to run Java performance tests, you need to make sure your program is running for a long time to get some level of accurate numbers.
Comment: The inner loop can be completely optimized-out by the JIT. It can be replace e.g. "synchronized(..){counter+=100000000;}"
Comment: Could be, yes but it seems to prove the point in this case.  Did you try it @pveentjer?


VHDL - IF alternative

Question: I want write an alternative of the if, I have following if statement.
if val1(1)&val1(0) < val2(1)&val2(0) then
            r:="10";
    else
            if  val1(1)&val1(0) = val2(1)&val2(0) then
                r:="00";
            else
                r:="01";
            end if;
    end if;

And I want it to change to following.
s:=((data1(9)&data1(8)) < (data2(9)&data2(8)))?"01":(((data1(9)&data1(8)) = (data2(9)&data2(8)))?"00":"01");
But the compiler gives me following error.

"# Error: COMP96_0015: min: (111, 49): ';' expected."

How can I resolve this? Thanks.
Comment: For what reason do you want an alternative?  Coding style? Size of logic? something else?
Comment: Did my answer solve your question?
Comment: yes thank you. Another option was to do a function :)
Answer: Question: what's the type of val1 and val2?
Here are some improvements:

if val1 and val2 have only 2 bits: val1 < val2
use slices instead of single bit concats: val1(1 downto 0) < val2(1 downto 0)
you could use the y <= a when (condition) else b;statement
this is the VHDL equivalent to C's ternary operator y = cond ? val1 : val2;
you could define a if-then-else functions let's call it ite:
function ite(cond : boolean; val1 : std_logic_vector; val2 : std_logic_vector)
return std_logic_vector is
begin
  if cond then
    return val1;
  else
    return val2;
  end if;
end function;

Usage:
s := ite((val1(1 downto 0) < val2(1 downto 0)), "10",    -- less
     ite((val1(1 downto 0) = val2(1 downto 0)), "00",    -- equal
                                                "01"));  -- greater

you could define a compare function, let's call it comp:
function comp(val1 : std_logic_vector; val2 : std_logic_vector)
return std_logic_vector is
begin
  if (val1 < val2) then
    return "10";
  elsif (val1 = val2) then
    return "00";
  else
    return "01";
  end if;
end function

Usage:
s := comp(val1(1 downto 0), val2(1 downto 0));

VHDL - IF alternative


Filter a text file into a new text file

Question: Sorry about the dummy question here.
Under Windows I would like to be able to filter one .txt file into a new one. Filtering all lines that contain a specific string.
I know this could well be a really easy one, but would really appreciate a few pointers please.
Answer: Use the findstr command:
findstr my-string filename > new-file

findstr /? will give you a usage message telling you how to use findstr (including the /V switch if you wanted to filter lines out rather than filtering them in.)
Or if you're familiar with grep and wishing you had it on Windows, install Cygwin. :-)
Answer: Powershell has some neat string comparison features. You can pipe the output to a new file.
^^ There are some better links as to how to use Powershell - but I can't find them this minute. If you go the Powershell route there are lots of examples on the internet.
Answer: Visual Studio Add On  Text Power Tools contains a very powerful filter feature.
The one issue is the Visual Studio add-ons have a file size limit (this may be resolved by the time you read this). Visual Studio may open a large file that is not the issue, the issue is add-ons are restricted to a file size limit.
Answer: There's a logfile filtering utility Logfilter (www.casstor.com), that can easily do this.  You can define multiple filter strings as well as use regular expressions in your filters.  I think it might be what you're looking for.

Filter a text file into a new text file


Hardy / Wright's intro to number theory is highly praised but has no exercises

Question: "An introduction to the theory of numbers, G.H Hardy, E.M. Wright, revised by D.R. Heath-Brown, J.H. Silverman. Originally published 1938. Sixth edition 2008 with a foreword by Andrew Wiles" is AFAIK a highly praised book. - What seems odd to me is that there are no exercises in the book. This must be the first mathematics book I have ever seen that has no exercises in it. Exercises, with or without hints can't be missed IMO.
Question. Was this common for books written in that time, i.e. mathematics books without exercises? If not, it must have been noticed by the critics. What did they say about it? Or (shame ) have I perhaps missed an accompanying exercise book?
Comment: The book is one giant exercise.
Comment: I don't mind a research-level book with no exercises.  What annoys me is a research-level book with no index!!!!!!!!!!!!!!
Comment: "This must be the first mathematics book ... no exercises in the book." A random sample of 10 maths books I have handy shows that 4 doesn't have exercises. Their publication dates range from 1934 to 2000.
Comment: It just demands a little bit more discipline from you. Try to prove the theorems yourself.
Comment: Slightly off-topic apropos @GEdgar's comment: I had the hardest time with some French-published books until I realised that the table of contents which I assumed was missing was at the *other* end of the book.
Comment: Most (maybe all!) British math books, except for high school level ones, had no exercises. (High school level included the calculus). There were really no university level math *textbooks*.
Comment: @Willie: I have sometimes considered the possibility that Bourbaki's book were translated into English with the main purpose of getting the TOC to the *correct* end :)
Comment: @MarkBennet - By now, a decade later, I see a glimpse of what MarianoSuárez-Álvarez might have meant when he said that The Theory of Numbers IS an exercise. - I am still discovering new things in the book.
Comment: @Willie Wong. - If your point is that you have seen many more math books than I have than I believe that's true.
Comment: Hardy's "Pure Mathematics" has lots of exercises. So maybe it is a pedagogical choice.
Answer: Conspicuously, Lang's "Algebraic Number Theory" had no exercises in any of the 3 editions I've owned. I don't remember that Weil's "Basic Number Theory" did. Titchmarsh's "The theory of the Riemann zeta" does not. Artin-Tate's "Classfield Theory" does not. I had never thought about the fact that Hardy-Wright does not.
My own experience was contriving examples to illustrate the theorems, and trying to understand the (not always completely explicit) hypotheses or contexts of the theorems. I didn't think of looking for exercises-at-end-of-chapter.
When Lang's and Weil's books appeared, they were the first serious alg no th books in English. Lang's book is itself (as Mariano S-A says about Hardy-Wright, above) one large exercise. Ditto Weil's. What are "exercises" supposed to be, anyway? Derivative filler? Who'd want that?
As far as I know, the "textbook" concept, with exercises included, is a post-WWII invention of U.S. publishers, and/or publishers for the U.S. text-book market, which until recently may have been the dominant force in text-book publishing. Having published textbooks myself, I am well-acquainted with, and somewhat dismayed by, the fixation publishers have with "exercises".
The exercises in Rudin's "Real and Complex", and Lang's "Algebra" are notorious landmarks. One aspect that merits notoriety is that a certain small fraction of them is routine rewriting of definitions/theorems from the chapter, but many require a non-trivial idea. Really, is it true that exercises should test mathematical talent? Seems rather pointless, or even dishonest to make people pay tuition for "education" that is something else.
By this point, I am of the opinion that "the text" should give samples of all questions asked as "exercises", or it's a cheat. Trivial things oughtn't be given as exercises (busywork?), and non-trivial things need models.
Atiyah-MacDonald's "Commutative Algebra" is a crazy extreme case, in my opinion, despite its virtues: perhaps the hardest half (or 2/3) of the results in it are innocently-posed "exercises". Thus, the attractive slimness of the book. But it is a substantial dis-service to leave readers with dubious, un-enlightened, perhaps completely incorrect "solutions" to exercises... if the "exercises" are serious results worth executing well, and with emphasis on the critical features.
In many cases, in my experience, otherwise-conscientious students are too-often entrapped by pointless, make-work exercises, so find themselves feeling they've accomplished something by having spent much time, but, in fact, have not engaged with the central ideas.
The contrived necessity of homework, exams, and grades is very corrupting... Why is mathematics perceived as exclusively a "school subject", and its sense and habits defined by grading systems and publishers? It is bizarre.
In summary, I was at-first-surprised by the question, but soon recovered my equilibrium... and/but had the above reaction. :)
Edit/addendum: incorporating @Pete's comment and @Willie W's... :
Indeed, it is not accurate to criticize the idea of "exercises" by noting that too many exercises are bad. It is possible, but very challenging, to give guided-exercises-with-hints in a non-combative, non-challenging fashion. One should try to do so! The false challenge of grading should/must be separated from explanation. To with-hold explanation as a "test" is a bad thing (despite its being standard).
It took me decades, but I only recently realized that the U.S. system has taught everyone to perceive "teachers" as antagonists, not (to say the least) unqualified supporters. Thus, everything said in lecture or notes or text is a potential challenge, a potential expression of doubt that the reader/student/audience understands. The UK system is a bit different, but I do not understand the current mind-set.
Hilariously, my attempts to rise above the corruption of adversarial game-playing grading by promising everyone an "A"... with required [sic] homework have not been as happy as I would have wished: I think the conditioning is too strong, and that combative, adversarial mindset does continue into grad-school. Sigh...
I do also think that discussion of the role of "exercises" deserves attention. Many students (not to mention old people...) misunderstand the "drill".
Edit-2: Thanks to @Gerry M. Indeed! Hardy's "Course..." I'd need to investigate years-of-publication and such, but I know the provenance of that thing needlessly well. My father (a high school math teacher in the U.S. required to obtain a higher degree [sic] in mathematics) endured a night-school course whose text was Hardy's. I was not very old, but old enough to be ... stunned... by the tendentiousness of that text. I had a fair understanding of analysis in the late 1960s, and/but Hardy's text effectively expressed doubt that its reader "had a brain in their body". And would not explain anything to them, either. Ack. I don't hold Hardy morally responsible for that text.
The Bourbaki impulse suggested things ... and publishers solicit. That is not the same as sincere intellectual expressions.
Edit... and about Zygmund, I am truly interested to look at my copy (in my campus office, tomorrow...) That would be an odder (counter-) example than many, to my mind. Relatedly, did Banach's monograph have "exercises"? Did Hausdorff's book? I do srsly think that "textbooks" were not what people were thinking about in those years. Advancing mathematics, monographs, yes. (What kind of "exercises" does EGA have? I'll also look tomorrow...)
Edit-edit: in response to @Bill D's query about my reaction to Hardy's "Course...": (First, certainly Hardy was a very good mathematician.) Surely it's a matter of taste, all the more so about the importance of "logical order" in mathematics, but/and the comparisons one has at hand, or sees as relevant (at least for oneself). Thus, for example, I would not think of comparing Hardy's "Course" to "calculus textbooks", almost all of which make much ado about nothing, not to mention that Hardy was actually a real mathematician, not a textbook writer. For that matter, I do think it's a pity his promotion of big-Oh and little-Oh didn't manage to displace the epsilon-delta version, especially for introductory texts. Nevertheless, in my opinion, it is too careful, and too long. It is (at some level) "logically complete", but I have never been a big fan of logical completeness per se, insofar as this tends to swamp highlights with an ocean of details, all too easily undifferentiated or undifferentiate-able.
Rather than "logical thinking", I think mathematics yields best to "critical thinking", which (to my understanding/experience) is often very different. My choice of charged language would be that critical thinking tries to discern which details matter, and allocate far fewer resources to the others. In contrast, too often a mere "logical order and logical completeness" is alleged to be what we want, and it's not what I want, anyway.
In other words, while I might agree that Hardy's "Course" is vastly better than almost all extant "calculus textbooks", that is very faint praise. I wouldn't recommend that people use those textbooks to actually learn calculus, in any case, since they make it too complicated, too fussy, too deus-ex-machina, too unpersuasive.
And while I'm editing: we aren't usually disappointed when a novel doesn't have attendant exercises, nor when a piece of music doesn't. Why should mathematical writing have exercises? :)
Comment: Good exercises *can* engage a student in central ideas. The problem is (a) a lot of exercises are not good (b) a lot of good exercises are given without any solution in sight, so if the student is truly stuck he will learn nothing from the experience. Perhaps (for self studying) a better idea would be to write complete examples with appropriately inserted "pause" marks encouraging the students to think about it on their own first.
Comment: Maybe this is getting too off-topic, but it would be *wonderful* if somebody could point me to a book that interpolates between the "attractive slimness" of Atiyah-Macdonald and the daunting bulkiness of Eisenbud. Both these books are completely unreadable for someone like me with only a superficial interest in the topic. Good exercises: they exist, definitely. Look at Pedersen's *Analysis Now* or Takesaki's *Theory of operator algebra*. From routine to rather challenging but always something to take away and excellent hints/outlines. Outstanding is Bogachev's approach in his measure theory.
Comment: Wow, this is a very interesting reaction.  It gives me a lot to think about.  (When I write lecture notes / expositions, I find myself *both* (i) putting in a fair number of exercises, mostly of the follow-your-nose variety and (ii) incorporating solutions to others' nontrivial exercises as part of the text.)
Comment: Great answer! [No exercises in Weil's **Basic Number Theory** indeed. I'd have expected Serre's name to appear in such an answer...]
Comment: I'm not sure the "post WWII invention of US publishers" is accurate. I have the 1944 Cambridge U Press edition of Hardy's A Course of Pure Mathematics, and it's chock-full of exercises (he calls them examples, but typically they call for proofs, which are not supplied). Hardy includes part of the preface to the 1908 edition, which says "There are plenty of hard examples...." Also, Zygmund's Trigonometrical Series, published in Wilno (Vilna) in 1935, has plenty of exercises.
Comment: @Theo I don't know if this recent textbook [Basic Commutative Algebra](http://www.amazon.com/Basic-Commutative-Algebra-Balwant-Singh/dp/9814313629/ref=sr_1_11?ie=UTF8&qid=1313555269&sr=8-11) by Balwant Singh may fit your criteria, but it certainly seems to fall in between Atiyah-Macdonald and Eisenbud. I haven't read it but I'm considering buying it since I will take a Commutative Algebra class this Fall and we'll be using Eisenbud's book, so it will be nice to have something else to read from.
Comment: They still give out "example sheets" at Cambridge, right?
Comment: @Theo Have you ever looked at Matsumura's book? (The one that's still in print; I haven't read the older one.)
Comment: @paul I'm perplexed by your comments on Hardy's *Course*. Could you please elaborate.
Comment: @Dylan: yes. But most of them are nothing like the difficult example sheets of days of yore one may hear about in fond anecdotes. :)
Comment: Exercises in textbooks were invented by Cambridge University in the 19th century as a by-product of the training require for the math tripos. See Andrew Wrarwick's Masters of Theory.
Comment: Sierpinski's Elementary Theory of Numbers (1963, Warsaw) has exercises, although it also has the answers directly after them, so they are more like worked-out examples.
Comment: @Dylan: Thanks for the tip! Yes, I leafed a bit in it a few times but that's already many many years ago. I know that my previous comment reveals more of the seriousness of my attempts to learn about the subject than anything else...
Comment: @@Paul Garrett. Thank you very much for the answer.
Comment: @Adrián: Thanks a lot for this suggestion, this may indeed fit the bill! Unfortunately, I can't look at the later chapters and it is hard to tell if it suits me from the definitions of rings and ideals... I'll certainly check it out. .@paul: sorry about the rant in the first comment, I let myself go a little too much (I should refrain from opinionating in public when I'm too tired).
Comment: @Theo B., ... Thx, but/and your rant stayed well within the bounds of taste and sense! :)  Also, it's not a bad thing for absolute beginners to see that there can be considerable disagreement among more-or-less competent people! E.g., there is not just one "sacred" approach, ...
Comment: And, of course, Hardy's "Course ..." was written when there was really nothing good available in English to teach its subject. Hardy aimed to correct this deficiency. If someone reads it and does all the exercises, they will know the subject quite well (imho).
Comment: I am an undergrad who's just discovered this book and I too find it weird that there are no exercises.  I always thought exercises were key to learning mathematics.  It makes me wonder, are end of section exercises not of much importance?  Am I wasting my time doing exercises???  I'm now getting the feeling learning comes from questioning the material as you read and trying to come up with examples on your own as you read.  However, it is hard for everyone to come up with such questions and thus exercises are sort of basically the questions that should arise from reading the material.
Answer: Here is a link to a commutative algebra course by Prof. Kleiman at MIT:
http://web.mit.edu/18.705/www/syl11f.html
It has a link to his new text. It also includes a link to a pdf with problems and solutions.
Pertinent to this question, here is a quote from the syllabus page for the course:
"The solution set will also include solutions to the unassigned problems. Do try to solve each one before reading its solution, in order to better appreciate the issue. And do read the solution even if you think you already know it, just to make sure. Further, some problems have alternative solutions, which may enlighten you."
Perhaps this is a happy pedagogical medium.
Comment: @t.b. Was motivated to post my answer based on your query. Regards.


Understanding roles of 'Element' and 'TypeMirror' in `UnmodifiableCollection`

Question: If we consider any generic type, for example, the below given code taken from java.util.Collections,
static class UnmodifiableCollection<E> implements Collection<E>, Serializable {
        private static final long serialVersionUID = 1820017752578914078L;

        final Collection<? extends E> c;

        UnmodifiableCollection(Collection<? extends E> c) {
            if (c==null)
                throw new NullPointerException();
            this.c = c;
        }

        public int size()                   {return c.size();}
        public boolean isEmpty()            {return c.isEmpty();}
        public boolean contains(Object o)   {return c.contains(o);}
        public Object[] toArray()           {return c.toArray();}
        public <T> T[] toArray(T[] a)       {return c.toArray(a);}
        public String toString()            {return c.toString();}

        public Iterator<E> iterator() {
           ...
        }

        public boolean add(E e) {
            throw new UnsupportedOperationException();
        }
        public boolean remove(Object o) {
            throw new UnsupportedOperationException();
        }

        public boolean containsAll(Collection<?> coll) {
            return c.containsAll(coll);
        }
        public boolean addAll(Collection<? extends E> coll) {
            throw new UnsupportedOperationException();
        }
        public boolean removeAll(Collection<?> coll) {
            throw new UnsupportedOperationException();
        }
        public boolean retainAll(Collection<?> coll) {
            throw new UnsupportedOperationException();
        }
        public void clear() {
            throw new UnsupportedOperationException();
        }
        @Override
        public boolean removeIf(Predicate<? super E> filter) {
             throw new UnsupportedOperationException();
        }
    }

I would like to understand,
1)
How to identify TypeElement, ExecutableElement, VariableElement, AnnotationMirror roles of javax.lang.model.element package for the above code?
2)
How to identify DeclaredType, WildcardType, ExecutableType, MirrorType roles of javax.lang.model.type package for the above code?
3) Is AnnotationMirror a mirror based reflection system as mentioned in this paper?
Note: element & type package is meta level facility, which is different from traditional reflection system(Object.getClass() method or Type.class literal)
Comment: What do these have to do with `UnmodifiableCollection`? Do you have a specific problem with this class, or does your question apply to any generic type?
Comment: @Clashsoft I just took this as an example. My question applies to any generic type. I saw you partially answered
Comment: Fair enough, I already guessed that.
Answer: The *Type and AnnotationMirror classes are all part of the javax.lang.model.element package, which is used when building custom annotation processors. The base class for this is javax.annotation.processing.Processor, which is a good place to start looking for help.
Essentially, all of these types represent nodes in the Abstract Syntax Tree of a compiler that calls your annotation processor. They are read-only, which means that you can only add custom errors, but cannot modify the source code.
Comment: Can you please answer my 3 questions?
Comment: I don't really understand how you want to 'identify' these - it depends on how you 'walk' the Abstract Syntax Tree that the compiler passes to your annotation processor in the `process` and `getCompletions` methods.

An `AnnotationMirror` simply represents an immutable view of an annotation in the AST.
Comment: 1) What does 2 arguments of `process()` method i.e., `Set annotations` & `RoundEnvironment roundEnv` represent?  ## 2) What does argument of `init()` method i.e., `ProcessingEnvironment processingEnv` represent?
Comment: The `RoundEnvironment` describes the current annotation processing "run", while the `ProcessingEnvironment` sort of represents the compiler, allowing you to access useful data such as a `Messager` (which lets you print error messages) or the current source version. A `TypeElement` represents a type, such as `String` or `List`.
Comment: What is the meaning of "current annotation processing 'run' "? I did not get you.
Comment: I recommend you read the documentation for these methods and classes. Otherwise, there is not much I can help you with. Also, I am not sure why you are asking this question and what you need all the information for.


How to confirm the edit of user data using sweet Alert in ASp MVC

Question: I am developing an ASP MVC web application using stored procedures via SQL Server.
I am trying to establish a confirmation's alert (Sweet Alert) in order to confirm the update of the data for a logged user.
The edit's code work perfectly without the confirmation. But once adding the confirmation alert, I face a problem with passing the parameters of the user (client) from the view to the controller via javascript function.
I tried to pass the hole model as parameter inside the onClick() but I got a JavaScript error of :

Uncaught ReferenceError: Delivery is not defined at HTMLInputElement.onclick

This is a portion of my view code (Edit page):
     <input type="button" value="Save" class="btn btn-default" onclick="Update(@Model.ClientId)">

The Controller (ClientController):
 [HttpPost]
    public JsonResult Edit(int id, Client cmodel)
    {
        try
        {

                ClientManagement cdb = new ClientManagement();
            if (cdb.UpdateDetails(cmodel))
            {
                TempData["Message"] = "Client Details Edited Successfully";
            }

            return Json("edited");
        }
        catch
        {
           return Json("Error");
        }
    }

The ClientManagement class :
  public bool UpdateDetails(Client cmodel)
    {
        try
        {
            connection();
            SqlCommand cmd = new SqlCommand("UpdateClientsInfo", con);
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.AddWithValue("@CltId", cmodel.ClientId);
            cmd.Parameters.AddWithValue("@FirstName", cmodel.FirstName);
            cmd.Parameters.AddWithValue("@LastName", cmodel.LastName);
            cmd.Parameters.AddWithValue("@Email", cmodel.Email);
            cmd.Parameters.AddWithValue("@Phone", cmodel.Phone);
            cmd.Parameters.AddWithValue("@Address", cmodel.Address);
            cmd.Parameters.AddWithValue("@Password", cmodel.Password);

            con.Open();
            int i = cmd.ExecuteNonQuery();
            con.Close();

            if (i >= 1)
                return true;
            else
                return false;
        }

        catch (SqlException sqlexc)
        {
            foreach (SqlError error in sqlexc.Errors)
            {
                string msg = string.Format("{0}: {1}", error.Number, error.Message);
            }
            return false;
        }
    }

While debugging, all values of the Client (ClientId, LastName...) are Null.
Comment: Your current code is sending a js object with only one property(`id`). If you want `LastName`, include that in the js object. If you have a form, you can send the serialized version of the form instead of adding individual properties to the js object
Comment: you can use the jQuery serialize method. Refer this for sample https://stackoverflow.com/questions/10803292/how-to-send-data-in-jquery-post-to-mvc-controller-which-use-viewmodel-as-paramet/10803473#10803473
Comment: @Shyju yes thats what I mean, how can I send the hole object ? and I have a form, how can send its serialized version ?
Answer: You must need to pass parameter in '(single quote).
<input type="button" value="Save" class="btn btn-default" onclick="Update('@Model.ClientId')">
Comment: thx for your answer but it is not a problem of quote, the same cofirmation alert with the same code works perfectly in the example of Delete, but hier no because edit take as parameter ClientId and cmodel, and delete take only clientId