Proof that a homeomorphic image of a non-borel set is non-borel

Question: This question seeks to expand the proof given in the answer to this question.
I am weak in topology, and am wondering if someone can provide a proof of why a homeomorphic image of a non-borel set is non-borel?
Comment: Hint: A homeomorphism is continuous, bijective, and has a continuous inverse. Now, continuous functions are Borel measurable. Assume $f(B)$ is measurable for a homeomorphism $f$. Could $B$ be non-measurable?
Comment: Möbius, the claim is obviously false in that generality. And I'm positive the answerer there did not mean that.
Comment: What is a "topological map"?
Comment: Given that the linked thread describes the use of a homeomorphism between $[0,1]$ and $[0,2]$, constructed using the Cantor function, I assume that *topological map* = *homeomorphism* here.
Comment: @Wojowu I have edit the post to say "topological mapping" by which I mean some mapping $f$ from one topological space $X$ to another topological space $Y$; i.e. $f : X \to Y$.
Comment: @JyrkiLahtonen Okay I will edit the post to be more specific, as per your comment.
Answer: Since a homeomorphism $f: X \to Y$ is continuous, it is also Borel-measurable. The same is true of $f^{-1}: Y \to X$.
Let $\mathcal{B}_{x}$ and $\mathcal{B}_{y}$ be the Borel $\sigma$-algebras on $X$ and $Y$ respectively.
Since $f$ is measurable we know that for every $B_{1} \in \mathcal{B}_{y}$ we have that $f^{-1}(B_{1}) \in \mathcal{B}_{x}$, and that for every $B_{2} \in \mathcal{B}_{x}$ we have that $f(B_{2}) \in \mathcal{B}_{y}$.
Let $B_{0} \subset X$ be a non-Borel set. Then $B_{0} \notin \mathcal{B}_{x}$. Since for every $B_{1} \in \mathcal{B}_{y}$ we have that $f^{-1}(B_{1}) \in \mathcal{B}_{x}$, it must be that there is no set in $\mathcal{B}_{y}$ that is mapped to $B_{0}$ (i.e. no Borel set in $Y$ can be mapped by $f$ to a non-Borel set in $X$).
The same holds if $B_{0} \subset Y$ is not Borel; no Borel set in $X$ can be mapped by $f$ to a non-Borel set in $Y$.
By the fact that $f$ is bijective, this implies that no non-Borel set $B_{0} \subset X$ can be mapped to a Borel set $f(B_{0})$ as otherwise $f^{-1} (f (B_{0}))= B_{0}$ must be Borel (since borel sets are mapped to borel sets), which is a contradiction. The same holds for non-borel sets $B_{0} \subset Y$.
Therefore, a homeomorphic image of a non-borel set must be non-borel.


Given that a and b are integers, a ≡ 4 (mod 13), and b ≡ 9 (mod 13). Find c where c ≡ 9a (mod 13).

Question: The Problem
I had my first exposure to number theory today. Trying to work on some problems in hope that it will start to make more sense. Here is the problem (part a) I'm stuck on right now.

My Work
We know from the first congruence that $\frac{a-4}{13} = d $ where $d\in\mathbb{Z}$ and $\frac{b-9}{13} = e$ where $d\in\mathbb{Z}$. We also know $a = 4 + 13k$ where $k\in\mathbb{Z}$ and $b = 9+13j$ where $j\in\mathbb{Z}$. $\frac{c-9a}{13} =$ an integer.
My Question
I've derived what I can from what I was given. How can I use this information to help figure out this $c$? What is a good strategy for the rest of the questions?
Comment: THinking of it as $\frac {a-4}{13} = d\in\mathbb Z$ although correct is a really backwards way of thining about it.  We don't care at all about what $d$ is just that the is one.  It's better to think of it as simultaneously as i) a has remainder 4 when divided by 12 and ii) a-4 is divisible by 13 and iii) we can write a = 13k + 4 for some integer k.  It's best to think of those as as basic language phrases that make as much immediate sense as "a is even" or "a is odd".
Comment: ... so $c = 9a \mod 13$.  We know $a = 4\mod 13$ so $a$ has remainder of 4 when divided by 13 which means $a = 13k + 4$ which means $9a = 13*9*k + 36$.  What remainder does $13*9*k + 36$ have when you divide it by $13$?  $c = 9a \mod 13$ means $c$ will have that exact same remainder.  What is it.
Comment: arrgh, I just commented on another ghost thread!  I hate when that happens.
Answer: We want to find $c \equiv 9a$ (mod $13$).  But since $a \equiv 4$ (mod $13$), then we know $9a \equiv 9 \cdot 4$ (mod $13$) (do you understand why?).
But $9 \cdot 4 = 36 \equiv 10$ (mod $13$).  And since $c$ should be an integer between $1$ and $12$ such that $c \equiv 9a = 36$ (mod $13$), and $36$ (mod $13$) is equivalent to $10$ (mod $13$), then $c$ must be $10$.

EDIT: I think the whole point of the problem is for you to know that if $a \equiv b$ (mod $x$), and $c \equiv d$ (mod $x$), then $ac \equiv bd$ (mod $x$).  You should be able to prove this, and then once you understand it, you can use it freely to solve problems like this.  This property is essentially saying that if you have two things that are equivalent (mod $x$), and two other things that are equivalent (mod $x$), then it doesn't matter which representative you choose from the first two things and the second two things.  When you multiply the representatives together, you get the same result.  This means the operation of multiplying elements of different equivalence classes is well-defined.  Does this make sense?
Answer: We know $\color{red}{a}\equiv \color{red}{4}\pmod{13}$.  We want to find an expression for $c$.  Thus: \begin{align}
c&\equiv 9\color{red}{a}\pmod{13}\\
&\equiv 9(\color{red}{4})\pmod{13}\\
&\equiv 36 \pmod{13}\\
&\equiv 10\pmod{13}
\end{align}
Just like with normal equations, you can substitute values in congruences.
Answer: If you have only just started today you should probably leave the question for a couple of days until you have learned the necessary facts.
Just to give you a brief introduction: you can add, subtract and multiply congruences in the same way you can ordinary equations.  (But note, this does not apply to dividing or cancelling.)  So the first problem can be done this way:
$$\eqalign{a\equiv4\mod{13}\quad
  &\Rightarrow\quad 9a\equiv9\times4\mod{13}\cr
  &\Rightarrow\quad c\equiv36\mod{13}\cr
  &\Rightarrow\quad c\equiv10\mod{13}\ .\cr}$$
The last implication is true because $36=2\times13+10$.


Iptables counters restore, when using quotas, not working as expected

Question: I've set a quota for a certain computer:
iptables -A FORWARD -d 192.168.1.10 -m quota --quota 500000000 -j ACCEPT
iptables -A FORWARD -d 192.168.1.10 -j DROP

This works as expected. When the limit (500MB) is reached, all packets for this particular computer get dropped.
But, if I save the counters (iptables-save -c > /home/iptables.counters), restart iptables, and restore the counters (iptables-restore -c /home/iptables.counters), then no matter what the saved counters were, that computer will still be able to download 500 MB, so the total counter size, before that computer loses internet access will be X + 500MB, where X is the saved counter size.
I must be doing something wrong, since this is the whole point to saving/restoring counters: resuming from that byte count until the limit is reached. Any type of hint would be greatly appreciated...
Comment: This smells like a kernel bug, and I would report it as such.
Comment: If you inspect the counters after the iptables-restore command are they what you expect ?
Comment: Yes. They are restored properly. But it's as if they're not there. The user is still able to download 500MB.
Comment: Which distro is this on? Which virtualization technology (if any) is your system using ?
Comment: It's a Fedora 20 server running on VMWare VSphere ESXi 5.1.
Answer: The problem is a kernel bug.
In EL6 the quota code that does the matching shows this:
quota_mt(const struct sk_buff *skb, const struct xt_match_param *par)
{
        struct xt_quota_info *q = (void *)par->matchinfo;
        struct xt_quota_priv *priv = q->master;
        bool ret = q->flags & XT_QUOTA_INVERT;

        spin_lock_bh(&quota_lock);
        if (priv->quota >= skb->len) {
                priv->quota -= skb->len;
                ret = !ret;
        } else {
                /* we do not allow even small packets from now on */
                priv->quota = 0;
        }
        /* Copy quota back to matchinfo so that iptables can display it */
        q->quota = priv->quota;
        spin_unlock_bh(&quota_lock);

        return ret;

In F20 it shows this:
static bool
quota_mt(const struct sk_buff *skb, struct xt_action_param *par)
{
  struct xt_quota_info *q = (void *)par->matchinfo;
  struct xt_quota_priv *priv = q->master;
  bool ret = q->flags & XT_QUOTA_INVERT;

  spin_lock_bh(&priv->lock);
  if (priv->quota >= skb->len) {
    priv->quota -= skb->len;
    ret = !ret;
  } else {
    /* we do not allow even small packets from now on */
    priv->quota = 0;
  }
  spin_unlock_bh(&priv->lock);

  return ret;
}

Its basically the same (minus spacing changes) apart from one line;
        /* Copy quota back to matchinfo so that iptables can display it */
        q->quota = priv->quota;

This is meant as a display parameter.
So in EL6 if you setup a quota, pass some packets through, then do iptables -vnL SOMECHAIN you'll notice the quota value decrements.
In F20 doing the same thing the value doesn't decrement. I guess the designers believe its probably a better thing to make sure people know what quota was set rather than what the quota really is (seeing as packet counts make it clear what is left).
However, this has an unintended effect. When you run iptables-save you save the quota value as read via iptables. In EL6, if this value reaches 0 it displays 0 to iptables. Thus, when you restore, you restore the 0 back into the iptables chain.
With them removing it, this value never decrements and thus you never actually save the quota.
What really needs to happen is the module needs redesigning. There should be a quota entry and a remaining entry. Remaining should decrement like in EL6 and be what is used to enforce the quota, whereas "quota" should be the actual set value like in F20. This way you get the best of both worlds. A saved state of the quota and a actual description of what quota is set.
You should probably report this to the netfilter team.
Comment: Thank you very much for that thorough answer. I will report the bug ASAP!
Comment: I'm running into similar issues with Centos 6. Installed version iptables v1.4.21 and latest git v1.6.0 still seem to have this issue. Any news on this?


Autocovariance function in $AR(1)$ process

Question: Let a autoregressive process $AR(1)$ given by
$$x_t=\sum_{j=0}^\infty \phi^jw_{t-j}$$
where $|\phi|<1$ and $w_{t-j}$ is i.i.d a white noise with mean 0 and variance $\sigma^2$.
The autocovariance function is
$$\gamma(h)=cov(x_{t+h},x_t)=E\Big[\Big(\sum_{j=0}^\infty \phi^jw_{t+h-j}\Big)\Big(\sum_{k=0}^\infty \phi^k w_{t-k}\Big)\Big]$$
$$=E[(w_{t+h}+\dots+\phi^hw_t+\phi^{h+1}w_{t-1}+\dots)(w_t+\phi w_{t-1}+\phi^2 w_{t-2}+\dots)\qquad\textbf{(1)}$$
$$=\sigma^2\sum_{j=0}^\infty \phi^{h+j}\phi^j=\sigma^2\phi^h\sum_{j=0}^\infty \phi^{2j}=\frac{\sigma_2\phi^h}{1-\phi^2},\qquad h\geq 0$$
I know that last equality is the power series representation of that sum, but I'm having hard time to understand how they get
$$\sigma^2\sum_{j=0}^\infty \phi^{h+j}\phi^j$$
from $\textbf{(1)}$. I know that they are using $$E[w_{j}w_{k}]=E[w_t^2]=Var(w_t)=\sigma^2$$
in the expectations, but I don't understood how to get the exponents in $\phi$
Anyone can help me?
Answer: Because $w_i$ is a white noise, $\operatorname{cov}[w_i,w_j]=0$ when $i\ne j$.
It follows that $E[w_iw_j]=0$ when $i\ne j$.
When you expand formula (1) you can get rid of all the terms $w_iw_j$ where $i\ne j$.
The terms you are left with all have an offset of $h$ in the exponent of $\phi$, i.e. $(1)=E[(\phi^hw_t)(w_t)+(\phi^{h+2}w_{t-1})(\phi w_{t-1})+...].$
Comment: I'm doing something wrong: can you help me?  $\sum_{j=0}^\infty \sum_{k=0}^\infty \phi^j\phi^k\mathbb{E}[w_{t+h-j}w_{t-k}]=\sigma^2\sum_{j=0}^\infty \phi^j\phi^{j-h}$.  I deduced that $h-j=-k$ and thus $k=j-h$.


Como despertar a tela somente tocando na tela do android

Question: Seria possível despertar um aparelho com Sistema Operacional Android apenas tocando sua tela, sem pressionar nenhum botão físico como Power ou Home, tal como no Nexus 5 e LG G2, nos quais um duplo toque na tela apagada os despertam.
Necessito de algo já existente que realize esse procedimento pois desconheço meios de como proceder. Deixo um link para um vídeo do Youtube demonstrando o recurso em melhores detalhes.
Comment: Vocês têm certeza de que isto é amplo demais? Não parece.
Comment: @bfavaretto Concordo que não é amplo demais, mas ainda acho que deva estar fechada, pois não me parece uma dúvida sobre programação, e sim uma busca por códigos prontos que realizem a tarefa que ele deseja
Comment: Pra mim isto é fora de contexto, de amplo não tem nada. Está bem específica, mas não é uma questão de programação.
Answer: Não é uma funcionalidade do Android convencional e sim de uma ROM modificada chamada ElementalX. Na descrição do vídeo há um link para a versão dessa ROM para o Nexus 5 (funcionalidade doubletap2wake). Essa funcionalidade inclusive consome mais bateria quando habilitada, pois a CPU do dispositivo não entra em sleep mode pouco tempo depois da tela desligar, tendo que ficar ativa para detectar os toques na tela.
Comment: Certo, mas programar algo como no tipo, despertar a tela com 2 toques na tela não é possível, digo, sem o consumo de bateria exagerada? Porque, vi um LG G2 com a mesma função do Nexus 5 e não me aparenta consumir bateria assim. Com isso precisava desenvolver um meio de despertar o aparelho com o toque na tela.
Comment: Provavelmente não. Quem vai tratar os eventos de toque de tela é a CPU, que precisa já estar acordada (por meio de uma Wake Lock) para fazer esse tratamento. E vale lembrar que o LG G2 é um dos aparelhos com maior capacidade de bateria do mercado hoje.


rspec for helper class expects module even though there is no module

Question: I added a helper class to my rails project, Foo, at app/helpers/foo.rb. It looks like  this.
class Foo
   #....stuff
end

I use it in some models, and everything works fine. However, in spec/helpers/foo_helper_spec.rb, I have
require 'spec_helper'
describe Foo do
end

This causes rspec to crash (not report any failed tests, but actually crash), saying
/actionpack-3.2.12/lib/abstract_controller/helpers.rb:153:in `include': wrong argument type Class (expected Module) (TypeError)
If i remove the describe line and just have the file empty, everything works, but I'd like to add some tests soon.
Anyone know how I can fix this?
Thanks.
Comment: And the helpers are modules generally. you will have to define as `module Foo`
Comment: Change it to a module and your rspec should work fine
Comment: you class reads 'classs'. is that a typo?
Comment: @Vimsha, sorry that classs was a typo. It's correct in my code.
Comment: @Vimsha you mean just surround the class definition in a module?
Comment: nvm that seemed to work. Thanks.
Answer: rails follows the paradigm of convention over configuration. one of those conventions is, that you put modules into the helpers folder, because they get included into your controllers and views.
that's why rspec fails when it tries to include your module, which is actually a class.
if you need to have a real class in there, i think you should put it in a different directory to make it obvious, that this is not a usual rails helper!
for example, if you are implementing some kind of decorator for your views, put it in a decorators folder. if you are implementing some kind of adapter for your model, put it in the models folder or some model subfolder.
Comment: i didn't realize helpers was treated differently. Thanks.


Matrix representation, linear transformation , general question on linear algebra

Question: Let $X$ be a finite dimensional vector space over $K$ and define $T:X\rightarrow X$ to be a linear transformation on $X$. If $\alpha, \beta$ are two different basis for $X$ then we know that the matrix representation $A=[T]_\alpha$ is similar to $B=[T]_\beta$. Is the converse true? That is suppose $A$, $B$ are $n\times n$ ($n=\dim X$) matrix, then if $A=[T]_\alpha$ and $A$ is similar to $B$, is it true that there exists basis $\beta$ such that $B=[T]_\beta$.
Answer: Yes. Let $A$ represent $T$ in the basis $e_1,e_2,\ldots,e_n$. Since $A$ and $B$ are similar, there is an invertible matrix $P$ such that $A=PBP^{-1}$. Then $P^{-1}(e_1),P^{-1}(e_2),\ldots,P^{-1}(e_n)$ is another basis since $P$ is invertible. $A$ is uniquely determined by the vectors $A(e_1),A(e_2),\ldots,A(e_n)$, and you can get the columns of $A$ from this. Namely, if $A=(a_{ij})$ then
$$A(e_j)=\sum_{i}{a_{ij}e_i}$$
Let $f_j=P^{-1}(e_j)$. Let $B=(b_{ij})$ be the matrix representation of $B$ in the basis $(f_i)$. Notice that
$$B(f_j)=\sum_{i}{b_{ij}f_i}$$
and
$$A(e_j)=P(B(f_j))=\sum_{i}{P(b_{ij}f_i)}=\sum_{i}{b_{ij}P(f_i)}=\sum_i{b_{ij}e_i}$$
so $a_{ij}=b_{ij}$ for all $i,j$.
Comment: Thanks so much for your answer, I will look at it later.
Comment: Ok I think you made your matrix commute in the last line $P(B(f_j))=PBP^{-1}e_i$. In this proof, where did you use the fact $A$ is a representation of linear transformation $T$. How do you know $f_i$ represents $T$ as $B$?
Comment: See my edit. P can commute past the real numbers $b_{ij}$ since they are real numbers. $A$ is assumed to represent $T$ in the basis I chose, and the entries $b_{ij}$ represent $B$ in the transformed basis, and are the same as the $a_{ij}$. By possibly changing $P$, you may assume $B$ to be the matrix representation in the basis you desire.
Comment: I understand your argument. But I dont think $a_{ij}$ and $b_{ij}$ are equal because $\sum_{i}a_{ij}e_i$ is not the same as $\sum_{i}b_{ij}e_i$. If $a_{ij}=b_{ij}$, then you just proved similar matrix are the same ($A~B$ implies $A=B$), which is not true
Comment: Notice that $b_{ij}$ is the matrix representation of $B$ in a different basis than $e_1,e_2,\ldots,e_n$, namely $f_1,f_2,\ldots,f_n$. In other words, $A(e_j)=\sum_i{a_{ij}e_i}$ and $B(f_j)=\sum_i{a_{ij}f_i}$, but $B(e_j)\neq \sum_i{a_{ij}e_i}$.
Comment: I got it. thanks for your time.


How to store data in Keychain?

Question: I want to know how to store data or like username/password in keychain ?
Is it good to store data in NSUserdefault ?
Answer: Never store username/password in NSUSerDefaults because it is not secure. The data in NSUSerDefaults is stored in plain text in a .plist file and can be viewed with no jailbreak required using tools like iExplorer.
Here's how to save and read from Keychain: https://stackoverflow.com/a/11541791/1738639

How to store data in Keychain?


Creating stored procedure with multiple temp tables

Question: So I created a report that essentially runs a DML statement built off multiple volatile tables. The way I built it was that each of my temp tables would essentially derive off the prior.  For example, in my first table I define the 'dataset' while my other temp tables defining my "exclusions", then my last couple temp table combines it all and then executes it in a final query.
I want to automate this report to pull in data daily, but I'm not sure whether to create a macro or sp for it. The bigger problem with either approach, is how would I even be able to effectively utilize each temp table? I've thought about combining ALL of my tables into a GIANT (1000+ line) DML statement, but SURELY, surely there are better, easier options out there.
Any help is deeply appreciated, thanks!
Comment: Since you mentioned a daily data pull, you might not need temporary tables.  You might be able to use staging tables.  These are normal database tables which are not part of a normalized or star schema.  Their purpose is to help with the T part of an ETL process.  Instead of creating temp tables all the time, you simply replace the contents of your staging tables.
Comment: Another alternative would be to use global temporary tables. These are instantiated on access, are session local, and materialize in a users TEMP space instead of SPOOL. The table definitions are retained in the data dictionary, so you do not have to embed them in your overall SQL to build the report.
Answer: Alternatively you could use Common Table Expression (CTE) instead of temp tables:
WITH cte1 AS
(
    SELECT *
    FROM table_1
    WHERE
), cte2 AS
(
    SELECT...
    FROM cte2
    JOIN ...
    WHERE
)
...
SELECT *
FROM cte_n;

One CTE can be depend on previous one or not, you could also use recursion and combine result in final query.
Comment: After much testing, I found the CTE to be the most applicable. However when creating a view from it, I'm not sure what the syntax is, code below:

CREATE RECURSIVE VIEW db.Test_View AS

WITH CTE 3 AS
(
SELECT
FROM CTE 2
),
CTE 2 AS
(
SELECT
FROM CTE 1
JOIN ...
WHERE...
),
CTE 1 AS
(
SELECT
FROM ...
JOIN ON...
WHERE...
)
SELECT * FROM CTE3


Rules of logarithm

Question: Can anyone help me figure out how to go from the first expression to the second?
$$
\begin{equation}
\ln D=u+\delta(e-p)+\gamma y-\sigma r
\end{equation}
$$
$$
\begin{equation}
\pi \ \ln (D/Y)= \pi[u+\delta(e-p)+(\gamma -1) y-\sigma r]
\end{equation}
$$
where $y=\ln(Y)$
$u,\delta,\gamma,\sigma=$ Constants
$e=$ Current exchange rate
$p=$ Current price level
$r=$ Domestic interest rate
$D=$ Demand
Comment: Is it given that $y=\ln(Y)$?
Comment: Please at least give clear explanation to every variable appeared in your expressions.
Comment: $\ln(D/Y) = \ln D - \ln Y$.
Comment: Hint: $\ln(D/Y)=\ln(D)-\ln(Y)=\ln(D)-y$.
Comment: Yes $\ln (Y)=y$
Answer: First of you don't need that $\pi$ messing thins even more(*).
So, you have:
$$\ln D=u+\delta(e-p)+\gamma y-\sigma r$$
Since $\ln Y=y$,
 we can apply the rule of the logarithm: $$\ln(a/b)=lna-lnb$$
for $$b=Y$$ and $$a=u+\delta(e-p)+\gamma y-\sigma r$$
Then your equation simply follows.
(*)Note that:  $c\ln (a/b)=c(\ln a-\ln b )$ So for $c=\pi$ you got the desired expression.
Answer: Starting with the second equation, divide both sides by $\pi$, then distribute the $y$ on the RHS.  On the LHS, use the fact that $\ln \left(\dfrac{D}{Y}\right) = \ln D - \ln Y$.  Since $y = \ln Y$, rewrite the LHS as $\ln D - y$.  Then add $y$ to both sides and you end up with the first equation.
To go from the first equation to the second, just work backwards:

Subtract $y$ from both sides in the first equation.
On the LHS, rewrite $y$ as $\ln Y$.
On the LHS, rewrite $\ln D - \ln Y$ as $\ln \left(\dfrac{D}{Y}\right)$.
On the RHS, rewrite $\gamma y -y$ as $(\gamma -1)y$.  (i.e., factor the $y$)
Multiply both sides by $\pi$.  Done!

Rules of logarithm


How to use union type as a generic parameter in a record which in a function

Question: I'm confused about the generic union type in Record.
This is my code (TypeScript version: 4.6.3):
   const fn = <T extends number | string = string>() => {
      const map: Record<T, string> = {};
   };

I hoped it would work, but the editor shows an error with map:

'map' is declared but its value is never read.ts(6133);
Type '{}' is not assignable to type 'Record<T, string>'.ts(2322)

When I write it like this, it works:
  type GetRecord<T extends string | number> = Record<T, string>;
  type AAAA = GetRecord<string | number>;
  const map: AAAA = {};

So, how can I do it if I want to use a union type as a generic parameter in record which in a function?
And, if I write it like this:
  const fn = <T extends number | string = string>() => {
    const map: Record<T, string> = {} as Record<T, string>;
    const data: Record<string, string> = {};
    Object.keys(data).forEach((key) => {
      map[key] = data[key];
    });
  };

It shows an error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Record<T, string>'.
No index signature with a parameter of type 'string' was found on type 'Record<T, string>'.

I don't understand that, T is extends string or number, and key is a string type. Why can't I set the key as an object-key to map?
Comment: What editor? [Visual Studio Code](https://en.wikipedia.org/wiki/Visual_Studio_Code)?
Comment: What do you mean by *"record which in a function"*?
Comment: yes,i'm using  Visual Studio Code
Answer: Because extends checks if the LHS is assignable to the RHS. Let's write a few tests using extends to get a better feeling of how this behaves:
type T1 = {} extends Record<number | string, string> ? true : false;
//   ^? true
type T2 = {} extends Record<string, string> ? true : false;
//   ^? true
type T3 = {} extends Record<number, string> ? true : false;
//   ^? true

All of these work, as expected, but notice when we use literals instead:
type T4 = {} extends Record<1 | 2 | 3, string> ? true : false;
//   ^? false

It does not work! Why?
Well, Record<1 | 2 | 3, string> is actually:
{
    1: string;
    2: string;
    3: string;
}

Now you see that {} is not assignable to this type. But why would we even try to see if literals would work in the first place?
These literals (1, 2, 3) are subtypes of the more general number type. So are the literals "foo", "bar", and "baz" of type string.
The assignment in your code does not work because T could be any string or number type, including literals. In other words, TypeScript is not sure that T cannot contain literal types. Thus, TypeScript will not allow you to assign {} to Record<T, string>.
You can get around this with a cast:
const map = {} as Record<T, string>;

This playground demonstrates the above tests and workaround solution with a cast.

(update according to question edit)
Let's try to decrypt this error message from TypeScript:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Record<T, string>'.
No index signature with a parameter of type 'string' was found on type 'Record<T, string>'.

Odd indeed. Until you consider and remember the tests from above. We see that literals won't work because they are too specific.
So let's write some more tests with extends:
type T6 = 1 | 2 | 3 extends number ? true : false;
//   ^? true
type T7 = "a" | "b" extends string ? true : false;
//   ^? true
type T8 = number extends 1 | 2 | 3 ? true : false;
//   ^? false
type T9 = string extends "a" | "b" ? true : false;
//   ^? false

It is now apparent that literals can be assigned to their respective more generic parent type, but not the other way around. This is intuitive and expected. You cannot give something that expects 1, 2, or 3 any number, nor can you assign any string to only "a" or "b".
So what does this tell us?
The hint lies in the last line of the error message:

No index signature with a parameter of type 'string' was found on type 'Record<T, string>'.

Recall that T could be anything that extends string | number. This includes 1 | 2 | 3, "a" | "b" or even 1 | 2 | 3 | "a" | "b".
It is clear now that because T could be more specific than a plain string, you cannot use a plain string to index into Record<T, string>.
However, if you are sure that the key can be used with T, yet another cast can be used:
map[key as T] = data[key];

Another playground that demonstrates what we have just discovered.
Comment: please look my new code.and ,your answer is good to me.tks
Comment: and,i have understanded your answer,it's looks a simple question now.tks very much
Comment: @fatpillow I have updated the answer if you are still interested in why your new code does not work


SQL: line 5:5: Column 'c' is ambiguous

Question: I write such code in hiveql.
SELECT
    ttt1.rid,
    a,
    s,
    ttt2.num
FROM
    (
        (
            SELECT
                rid,
                r ['a'] AS a,
                r ['s'] AS s
            FROM
                l
            WHERE
                dt BETWEEN '20210914'
                AND '20210917'
                AND r ['act'] = 3
                AND r ['pos'] = 1
                AND r ['s'] = 50011
                AND r ['c'] = 'anti'
        ) ttt1
        JOIN (
            SELECT
                r ['a'] AS a,
                r ['s'] AS s,
                count(1) AS num
            FROM
                l
            WHERE
                dt BETWEEN '20210914'
                AND '20210917'
                AND r ['act'] = 3
                AND r ['pos'] = 1
                AND r ['s'] = 50011
                AND r ['c'] = 'anti'
            GROUP BY
                r ['s'],
                r ['a']
        ) ttt2 ON (
            ttt1.a = ttt2.a
            AND ttt1.s = ttt2.s
        )
    )

I am wondering why it got ambiguous err.

line 5:5: Column 'c' is ambiguous

CUZ a and s are the join keys for these two tables, it could ignore the <TABLE_NAME> before <COLUMN_NAME>.
Could anyone give me some explaination?
Thanks in advance.
Answer: i reckon the problem is in the final select, you have not specified from which tables the a and s is to be selected from
SELECT
    ttt1.rid,
    a, --change this to ttt1.a
    s, --change this to ttt1.s
    ttt2.num

Comment: but I think it is an `inner join`, so why have to use `.` like `ttt1.a` not just use `` like `a` so that I can ignore ``? CUZ I remember in some grammar restricted `` part could be ignored?

SQL: line 5:5: Column 'c' is ambiguous


How to play triplets & 16th notes together?

Question: First of all, I'm a beginner with only one year experience on the piano, I have studied musical theory on my own for 2 years prior to buying it, and I've been practicing a piece since I've gotten my hands on it, which is liszt's transcription of Beethoven's 7th symphony 2nd movement, and I've successfully memorized every single note in it, and can play most of the piece proficiently. The problem is, there are 9 measures (last 9 in the picture) where I can't even begin to comprehend how to play the two hands together (I can play each hand individually really well), it just seems like an impossible feat, basically too much for brain to take in as well as hard not to play inaccurately. How would you go about practicing them ? Should I leave something out for the sake of playability (like the 16th notes in the left hand)?
I am planning to release a video recording of the piece on Beethoven's 250th birthday on 16/12, so I am currently lost on how to get this part down in less than a month.
Comment: Well it definitely helps in getting me one step closer towards actually beginning to practice the measures, because I'm clueless.
Answer: Its astonishing that you can even attempt a piece such as this after just one year of playing.  I look forward to seeing your recording.
So to your issue.  Many people like to work out the maths and get everything to line up and that is one way to tackle it.  It must work because lots of people do it.
But there is another way which may help you if, as you say, you can already play the indivdual hands without difficulty.  What you need to do is learn to subdivide the beats mentally without counting those subdivisions.  Practice this enough and it becomes sort-of instinctive.  So when you encounter something like this just keep the beat (in this case in quarter notes or crotchets) in your head and play the correct number of subdivisions required to fill each one.  Its different in each hand which makes it harder but if you have put in the prep you will find yourself just doing it almost without thinking.
This sort of 3 vs 4 is actually quite a simple one compared with many that you will find, especially if you are interested in Romantic period piano music.  Things like 5 vs 7 and 6 vs 7 and many other combinations are found fairly fequently in Chopin and Liszt among others. Theres a place in one of Chopins Ballades where there are three different rhythms going on at the same time all in the same hand, which is, I admit, a bit of a swine.
And as to leaving something out: - you could do that of course but please don't think of it as being for the sake of playability;  its because your technique is not there yet and, like the rest of us, you need to do more practice.
Good luck
Comment: Well thank you very much for answering, this was insightful.


How to count how many data points fall in a bin

Question: I have set the parameters of my bins and I want to find how to add one to the bin when a data point falls in the range of a particular bin, essentially count how many data points fall in each bin range, so that I can use that as the "frequency" when I graph it out.
My bins ranges are set by:
 bins = [(i*bin_width, (i+1)*bin_width) for i in range(num_bins)]

and my data looks something like:
2.55619101399
2.55619101399
2.55619101399
3.615
4.42745271008
2.55619101399
2.55619101399
2.55619101399
4.42745271008
3.615
2.55619101399
4.42745271008
5.71581687075
5.71581687075
3.615
2.55619101399
2.55619101399
2.55619101399
2.55619101399
2.55619101399

Comment: It sounds like you are asking how to do a histogram, or am I missing something?  Look up "histogram" ...
Comment: No I understand how to make a histogram, but does that automatically count the frequency in the bins?
Comment: I guess I really don't understand what you're asking ... "number of points in the bin" is exactly what a histogram gives you. What do you mean by "frequency"?
Comment: But histogram will graph it, and I don't want to graph the number of data points per bin, I want to manipulate that data before graphing, which is why I want to be able to have a  counter in each bin.
Comment: @Wana_B3_Nerd: I'm pretty sure Ajean is suggesting [`NumPy.histogram`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html), not `matplotlib.histogram`.
Comment: OK, I wrote a second answer explaining why `numpy.histogram` is exactly what you want, as Ajean said in the first place.
Answer: Since you're using NumPy, you (a) shouldn't be trying to create lists and loop over them instead of using arrays, and (b) should look to see if what you want to do is already built-in (or available in SciPy or Pandas or some other library built on NumPy), because often it is.
And numpy.histogram is exactly what you want.
It takes a total width rather than a bin width, but other than that, it's trivial to plug in the values you already have and get back the values you want:
hist, edges = np.histogram(
    data_points,
    bins=num_bins,
    range=(0, bin_width*num_bins),
    density=False)

The hist array will contain the counts for each bin (like bin_counts in my other answer), which is what you want to post-process and eventually graph.
The edges, you may or may not need. It's the same information as the bins in your original question, but in different format—instead of [(0, .1), (.1, .2), (.2, .3)] it's [0, .1, .2, .3].
Answer: Well, first, each of your bins is just a tuple of the start and end values of that bin, so there's no way to add anything to it. You could change each bin into, say, list of [start, stop, 0] instead of a tuple of (start, stop), or, maybe even better, an object. Or, alternatively, you could keep a separate bin_counts list, parallel to the bins list, and, e.g., zip them up when needed.
Next, if each bin goes from i * bin_width to (i+1) * bin_width, then how do you get the i value from a data value? That's easy: the opposite of multiply is divide, so it's just data_point // bin_width.
So:
bin_counts = [0 for bin in bins]
for data_point in data_points:
    bin_number = data_point // bin_width
    bin_counts[bin_number] += 1

Showing one of the other options, because I think you were asking about it in the comments:
bins = [[i*bin_width, (i+1)*bin_width, 0] for i in range(num_bins)]
for data_point in data_points:
    bin_number = data_point // bin_width
    bins[bin_number][2] += 1

Here, each bin is a list of [start, stop, count], instead of having a list of (start, stop) bins and a separate list of count values.
Comment: So I am a little confused on whats wrong with the way I am creating the bins, is your solution to just do:bins = list[(i*bin_width, (i+1)*bin_width) for i in range(num_bins),0] ?
Comment: @Wana_B3_Nerd: There's nothing _wrong_ with the way you're creating the bins, as long as you want `bins` to be an array of `(start, stop)` values. If you want them to be something different, then of course you should be creating that something different instead.
Comment: Okay so if I want to make the bins into the list format should I take off the "for I in range(num_bins) or just should it look like the format that I put in my first comment.
Comment: @Wana_B3_Nerd: I don't really understand what you're asking. The format in your first comment isn't even valid Python, and just taking off the `for i in range(num_bins)` just means you'll have a list of one `(start, stop)` bin instead of a list of `num_bins` of them… Does my updated answer help?
Comment: Yes it helps, but when I run it I get the error:TypeError: 'numpy.float64' object is not iterable
Comment: @Wana_B3_Nerd: Without knowing what you're running, what the variables around it are holding, and where that error comes from (the traceback), it's hard to debug that. But the fact that you're using NumPy changes things. If you ever find yourself creating lists instead of arrays with NumPy, or looping instead of broadcasting, you're probably doing something wrong. Especially if you're trying to do something very common, like binning values, that's likely to have a built-in solution in NumPy (or SciPy).
Answer: from collections import Counter

frequency_data = Counter()

    for d in data:
        new_bins = bins
        median = len(new_bins)/2
        while not new_bins[median][0] < d < new_bins[median][1]:
            if d < new_bins[median][0]:
                new_bins = new_bins[:median]
            elif d > new_bins[median][1]:
                new_bins = new_bins[median:]
            median = len(new_bins)/2
        frequency_data[new_bins[median]] += 1

Comment: Re: "[defaultdict] adds a queried key if it does not find it, Counter does not". I don't know what you mean. Counter appears to work in the way you say it does not. ` >>> from collections import Counter
>>> c = Counter()
>>> c["a"] += 4
>>> c
Counter({'a': 4})`
Comment: Why make finding the bin O(N) instead of O(1)? Why use a dict when you have a contiguous index as your key? And why use `defaultdict` to make a `Counter` when you can just use `Counter` from the same module?
Comment: My concern was that using contiguous indexes in a list wouldn't handle bins of fractional size. For example (2.3, 2.4), size 0.1.
Comment: And the reasoning for default dict is that it adds a queried key if it does not find it, Counter does not.
Comment: `if bin[0] < d < bin[1]`. Also, you have better options for finding the bin to put an item in. You can binary search in O(logn) time or you can figure out a way to create the appropriate key and use a dict for O(1) lookup.
Comment: @Jonk: "My concern was that using contiguous indexes in a list wouldn't handle bins of fractional size." The OP has already solved that exact problem in his question: just multiply the bin number by the bin size to get the bin value; divide the value by the size to get the number.
Comment: @hughdbrown: Exactly, and it's specifically [documented](https://docs.python.org/3/library/collections.html#collections.Counter) to do so: "Counter objects have a dictionary interface except that they return a zero count for missing items instead of raising a `KeyError`."
Comment: My mistake, you are correct about Counter. @hughdbrown: Out of curiosity, is my edit above what a typical binary search algorithm would look like for this problem?


Why are paredit keybindings showing incorrect instructions in emacs

Question: I installed paredit in emacs (gui not terminal and no spacemacs or doomemacs, just emacs) and then checked some of the commands and their corresponding key bindings.
Ex. paredit-forward-slurp-sexp C-<right>

I believe the <right> is the right arrow on the keyboard.  In other emacs configurations like spacemacs, C-<right> worked.
However, I noticed the commands paredit-forward-slurp-sexp worked but the key bindings C-<right> did not.
Then I found a paredit cheatsheet that had different key bindings that worked.
Ex. paredit-forward-slurp-sexp C-)

So my question again, why are the keybinding for paredit in emacs that are actually displayed in emacs when you start to write M-x paredit-forward- then tab to see what options that are available, showing the commands with incorrect keybindings?
Note:
I did look at this related question that speaks about the difference in aliased keybindings in gui vs terminal emacs (depending on the terminal).  However, when I tried to use any of the key bindings in the terminal, none of them worked.
Answer: There could be a few reasons why the paredit keybindings are showing incorrect instructions in Emacs. One possibility is that the keybindings may be conflicting with other keybindings in your Emacs configuration. Another possibility is that there may be a bug or issue with the paredit package itself.
To troubleshoot this issue, you could try resetting your Emacs configuration to its default settings and then reinstalling the paredit package to see if the keybindings work correctly.
Comment: You're welcome! If you continue to experience issues with the keybindings despite resetting your configuration, please add comment anytime. Good luck with your work!
Comment: Thanks. Presently I am using the keybindings from the cheatsheet, as I am finishing up some work, but will try resetting things.


Packages interfering with other packages on R?

Question: I am working on a long R studio script for an experiment (more than 3000 lines) with different kinds of analyses that are not too complicated but combined there a lot of different kinds of analyses there. I come across problems where I have loaded one package from the library (e.g. "MASS") and then I can no longer do a function from another package, e.g. select() because it produces an error message when I use it. My way around it so far has been to restart R and to be really careful with the order of the packages that have loaded; so that I have done all of the necessary parts with e.g. select() before I load e.g. "MASS". I am reluctant to start a new script for every analysis that I do, because it seems like it is so much easier to work with one script and e.g. pinch bits of code from other analyses. Is there a better solution to resolve this?
Comment: This is exactly the problem the operators `::` and `:::` were created to solve.  You have a more fundamental problem, though: no script of 3000 lines can be adequately tested and verified.  Restructuring it (using principles of encapsulation, modularization, and unit testing) will help you assure its correctness--to the extent that can be done--by allowing you to test a collection of smaller simpler components.  In the process you can create isolated namespaces (`R` "environments") to protect against object name collisions.
Comment: Hey thanks, sure I would never run the script all at once- it is more like a document with many different analyses and then I run a subset of the analysis that I want to do for a specific statistical test or visual representation. The actual analyses are checked separately. Thank you for your advice
Answer: Yeah MASS affects and masks functions from dplyr and plyr. As annoying as it is, one way I've gotten around it is doing dplyr::select(). Alternatively you can add and remove MASS where you need it, which is also annoying. Sorry! Hope this helps
Comment: Thank you for answering! Gosh I am glad that there is a quicker way for dealing with it than restarting the program. Annoying! Thanks for explaining! :)


Diferença entre AWT e Swing na renderização de componentes

Question: Quais são as principais diferenças entre as bibliotecas de construção de interface Swing e AWT, no que diz a respeito da forma de renderização dos componentes de ambas e a performance?
Answer: Existem dois tipos de componentes envolvidos, os componentes heavyweight e os lightweight. Os componentes heavyweight dependem fortemente de detalhes implementados em código nativo para funcionar (ou seja, C e C++) e por causa disso, o desempenho deles tende a ser (mas não necessariamente é) um pouquinho melhor, mas deixando-os bem mais difíceis de se utilizar, além de por vezes dependerem de detalhes específicos do sistema operacional sacrificando-se compatibilidade. Já os componentes lightweight são feitos 100% em Java, sem requerer código nativo.
Os componentes heavyweight são do AWT (por exemplo, java.awt.Button), enquanto que os lightweight são os do Swing (por exemplo, javax.swing.JButton). O uso direto de componentes heavyweight é desencorajado há muito tempo.
Todos os componentes do AWT são subclasses de java.awt.Component. Uma dessas subclasses, java.awt.Container é especial porque ela corresponde a um componente que pode conter subcomponentes. Uma subclasse especial de Container é a classe javax.swing.JComponent que é a superclasse de todos os componentes Swing. Essa hierarquia também significa que quaisquer componentes Swing podem conter subcomponentes.
O desenho de todos eles se baseia no método paint(Graphics) da classe Component. Entretanto, não é recomendável se sobreescrever ou invocar este método diretamente.
Um redesenho de um componente pode ser forçado com o uso do método repaint().
Um componente heavyweight que tem o seu desenho de tela sujo, pode ser redesenhado pelo AWT por meio do método update(). A implementação padrão, apenas limpa a área de desenho de todo o componente e chama o paint() para redesenhá-lo, mas implementações mais especializadas podem fazer atualizações incrementais ou determinar quais são as áreas que estão sujas e redesenhar apenas essas. Novamente, o método update() não deve ser chamado diretamente.
Entretanto, o conceito de desenho incremental e o uso do update() se mostrou confuso e quase sempre desnecessário, portanto isso não é utilizado para os componentes lightweight. Nos componentes lightweight, uma chamada a update() é na prática o mesmo que uma chamada a paint(). Nos componentes lightweight, o método paint() implementado na classe JComponent apenas chama os métodos paintComponent(Graphics), paintBorder(Graphics) e paintChildren(Graphics) nesta ordem (fonte). Como os nomes sugerem, eles respectivamente desenham o componente, desenham a borda do componente e desenham os subcomponentes. Embora você possa sobreescrever qualquer um desses métodos, normalmente você vai querer sobreescrever apenas o paintComponent(Graphics).
No final, em ambos os casos, quem realiza o desenho é a classe Graphics. Entretanto, o AWT sempre vai usar uma instância da subclasse Graphics2D, então você pode fazer o cast seguramente se precisar para ter acesso a um conjunto maior e melhor de métodos disponíveis.
E lembrando que no final das contas, quem controla tudo é o AWT. O Swing é apenas uma camada por cima do AWT, e não um substituto completo. O Swing só é um substituto do AWT no que concerne a substituir componentes heavyweight por componentes lightweight.
Há mais um detalhe importante a se notar: JFrame, JDialog e JWindow não são subclasses de JComponent, então elas não têm o método paintComponent(Graphics), mas têm o método paint(Graphics). Neste caso, você pode então preferir sobreescrever paint(Graphics) invocando um super.paint(g) dentro dele. No entanto, no caso de JFrames e JDialogs, talvez seja melhor acrescentar um JPanel dentro e então sobreescrever o paintComponent(Graphics) do JPanel.
TL;DR: Ou seja, no fim das contas, o que importa é que para implementar o desenho da sua subclasse de JComponent, você deverá sobreescrever o método paintComponent(Graphics). Para subclasses de JFrame, JDialog e JWindow, você sobreescreve o paint(Graphics) mesmo.
Mais detalhes em http://www.oracle.com/technetwork/java/painting-140037.html
Comment: @diegofm Sim. Os componentes do AWT foram algo meio feito as pressas utilizando-se ganchos para os componentes em C e C++ que o Windows e o Solaris ofereciam na época do Java 1.0 porque o pessoal da Sun não tinha tempo para implementar isso e não daria para atrasar o lançamento do Java por causa disso. Entretanto, esses componentes não são flexíveis, são difíceis de se usar e dependem do sistema operacional específico. Isso foi uma das amarras que o Swing veio libertar como uma biblioteca externa no Java 1.1 e incorporado na JRE do 1.2, sendo muito mais portável que os componentes do AWT.
Comment: Com base na sua resposta, então pode-se afirmar que uma interface em swing é mais portável que uma feita em AWT? Já que ela independe do SO?
Answer: Na implemenação, a diferença básica é que AWT usa as APIs de componentes visuais do sistema operacional onde a VM está rodando para criar componentes inteiros com praticamente todo o comportamento sendo controlado pelo SO.
Já o Swing, desenha do zero os componentes usando APIs gráficas básicas do SO, gerenciando a maior parte do funcionamento dos componentes por conta própria.


Clean up Unused Tables

Question: I have installed some analytics module for my drupal sites. Because it's on company's internal network, I couldn't use it. Now I have the tables created by the module sitting in my database (after I just forcefully removed the module folder from drupal installation).
Is there a way to clean unused tables in Drupal 7?
Note: I tried Schema, but it doesn't seem doing anything but displaying tables are in use and not used
Answer: Most Drupal modules that installed their own database tables also remove them upon uninstall. I have bolded uninstall due to the fact that modules can have two states when they are turned off namely disabled and uninstalled.
Disabled implies that you have simply turned the module off, but have chosen to keep the module's settings and database tables intact in the event that you turn it back on again at some point. Disabling is done by simply unchecking the module on the module administration page and clicking on "Save configuration".
Uninstalled on the other hand indicates that you have decided that a previously disabled module will never be used again. Consequently, you are happy to remove all the settings and database tables created. This is done by clicking on the "Uninstall" tab on the module administration page, checking the module that you want to uninstall and then clicking on "Uninstall".
If for some reason the module does not have an uninstallation script in its <code>.install</code> file, then you will need to remove the tables manually. You can also try creating an issue in the module's issue queue asking for this oversight to be remedied.
If you have removed the module's files from the server, then you will (obviously) be unable to run the uninstallation script (as the module will no longer be listed under the uninstall tab). To fix this, simply download/restore the module again to the file system (you do not need to install it). This should list it again under the uninstall tab and you can proceed to run its uninstallation script as above.
Comment: Then you should restore the module folder so that you can properly run the uninstall script.
Comment: sorry, I didn't specify that I removed the folder of the module instead of uninstalling
Comment: Added note about deleted module files to the answer.
Answer: If the module does not provide the usual .install hooks which should remove the tables automatically up on uninstall, you can examine what's in .install to add the tables to find what you have to remove manually.

Clean up Unused Tables


Check if nested JSON structure contains key

Question: I'm trying to figure out how to check if a deeply nested JSON object, with several unknown arrays and properties contains a property that I'm looking for. I'm looking for a property that is called "isInvalid". If the field is there and the value of that key is true. I want to return false.
var checkValidity = function (data) {
    for (var property in data) {
        if (data.hasOwnProperty(property)) {
            if (property == "isInvalid" && data[property] === true) {
                return false;
            }
            else {
                if (typeof data[property] === "object" && data[property] !== null) {
                    this.checkValidity(data[property]);
                }
            }
        }
    }
};

This is the code I've been trying out but I'm unable to get that to work. I have been looking into underscore also, but cant find the needed functions. Anyone has an idea? (No reg exp please)
Comment: `this.checkValidity` is invalid, `checkValidity` is a variable, not a property of an object unless you are attaching it to some object and not showing it
Comment: @peter you can use Object.keys then check if the isInvalid is existing in the array of keys
Comment: please use a named function for recursion.
Comment: Is `isInvalid` key of the input object or you want to apply logic over there to test valid object ?
Comment: I just wan't to check if the object, and the nested properties actually contains that key, and check if the value is true. I don't wan't any more logic what so ever.
Answer: If you really just want to check for property presence regardless of its particular location within JSON, then the easiest/fastest way is substring search in the source JSON string. If the latter is well-formed, then the property should be encoded in JSON as '"isInvalid":true'.
var checkValidity = function (jsonstr) {
    return jsonstr.indexOf('"isInvalid":true') >= 0;
}

Comment: Perfect, really like this solution. No recursive methods needed.
Answer: You can check like this
var s = {a:'1',b:'2'};

if(Object.getOwnPropertyNames(s).indexOf('a') != -1){
console.log('available');
}else{
  console.log('Not available');
};

editing answer... UPDATE
var s = {
  a1: '1',
  b: '2',
  c: {
    a: '11'
  }
};
var checkValidity = function (data) {
  if (Object.getOwnPropertyNames(data).indexOf('a') != - 1) {
    console.log('Found that key!!!');
  } else {
    for (var property in data) {

      if (Object.getOwnPropertyNames(property).indexOf('a') != - 1) {
         console.log('Found that key!!!');

      } else {
        if (typeof data[property] === 'object' && data[property] !== null) {
          console.log('not found continue in inner obj..');
          this.checkValidity(data[property]);
        }
      }
    }
  };
};
checkValidity(s);

Comment: Please read the question. This only checks one level of the JSON.
Comment: @petur I was editing the answer! I just post an idea to test that. You can check with update.
Answer: It tests for every nesting level the property isInvalid and if not, all other properties as object and their content. Array#every breaks if one return is false.

function checkValidity(data) {
    return !data.isInvalid && Object.keys(data).every(function (property) {
        if (typeof data[property] === "object" && data[property] !== null) {
            return checkValidity(data[property]);
        }
        return true;
    });
}

var data = {
    a: 1,
    b: 2,
    c: {
        isInvalid: true,
        a: false
    }
};

document.write('checkValidity() should be false: ' + checkValidity(data) + '
');
data.c.isInvalid = false;
document.write('checkValidity() should be true: ' + checkValidity(data));
Answer: For complex json searching like this, I would use jsonpath ( http://goessner.net/articles/JsonPath/ ) which is the JSON equivalent of xpath.
To find the isInvalid field no matter where it is in the json, you would use it like this:
 jsonPath(data, "$..isInvalid")


Exportar datatable para PDF

Question: Estou usando Java,JPA,Primefaces,Wildfly, tenho uma datatable que preciso exportar para PDF,no excel é só adicionar o poi.jar que funciona mas no PDF não sei qual poi que devo adicionar, alguém poderia me ajudar?
Answer: Você pode usar o
:
<h:form>

        <f:facet name="{Exporters}">
            <h:commandLink>

            </h:commandLink>
        </f:facet>

<h:form>

Você pode exportar para diversos outros formatos, inclusive XLS. É só mudar a propriedade type para type=xls.

EDIT:
Para a exportação para PDF funcionar você deve incluir a bibliotecaiText no seu projeto.
Para a exportação para XLS funcionar você deve incluir a biblioteca apache poi no seu projeto.

Mais informações no site do PrimeFaces.
Comment: Pelo o que entendi você precisa adicionar uma lib chamada `iText` também.
Comment: Pode ser a versão 2.1.7
Comment: consegui, deu certo, esta é a versao correta, Obrigado
Comment: Este trexo é exaamente como esta no site do primefaces,inclusive estou usando desta forma, mas para utilizar precisa de um poi, eu adicionei esse jar par ausar o exel mas nao seu qual é o do PDF
Comment: voce sabe me dizer qual é a versão desta lib que devo tomar como parametro?

Exportar datatable para PDF


Meaning of correlation

Question: In probability books it is sometimes mentioned that correlation is a measure of linearity of a relationship between random variables.
This claim is supported by the observation that $\left| \rho(X,Y)\right|=1 \iff X=b+aY$.
But let consider a less extreme case: $X,Y,Z$ are random variables such that $\rho(X,Y)=0.5$ and $\rho(Y,Z)=0.8$. Does it mean that the relationship between $X$ and $Y$ is "less" linear than between $Y$ and $Z$? How at all the degree of linearity in a relationship can be defined (especially given the fact, that a relationship between random variables can be non-functional, so one can not always use the second derivative)?
Edit:
I am talking about Pearson correlation here.
Answer: For ease of exposition, let us consider zero-mean unit-variance jointly continuous random variables $X$ and $Y$ with joint density $f(x,y)$. Then,
$$\begin{align}
\rho = E[XY] &= \int_{-\infty}^\infty \int_{-\infty}^\infty
x\cdot y\cdot f(x,y)\,\mathrm dx\,\mathrm dy\\
&= \int_0^\infty \int_0^\infty xy\big[f(x,y)+f(-x-y)-f(-x,y)-f(x,-y)\big]
\,\mathrm dx\,\mathrm dy.
\end{align}$$
If $\rho > 0$, then the term
$\big[f(x,y)+f(-x-y)-f(-x,y)-f(x,-y)\big]$ cannot be negative for all
$(x,y)$ in the first quadrant; indeed, roughly speaking,
$$f(x,y)+f(-x-y) > f(-x,y)+f(x,-y)$$
quite often, that is, there is generally more mass in the vicinity of $(x,y)$ and $(-x-y)$ (i.e. in the first and third quadrants) than in the
vicinity of $(-x,y)$ and $(x,-y)$, (i.e. in the second and fourth quadrants). For $\rho$ close to $1$, very roughly speaking, the probability mass lies in the vicinity of the line $x=y$.
For $\rho < 0$ and for $\rho$ close to $-1$, similar remarks apply
mutatis mutandis.
The simulations in
this answer of Michael Hardy illustrate this notion very well. My point is that this sort
of behavior (more mass in two opposite quadrants than in the complementary
opposite quadrants when $|\rho|$ is close to $1$) is a general feature shared by all (zero-mean unit-variance) random variables. Similar
remarks apply when the mean point is not the origin (the quadrants
are defined w.r.t. the mean point) and the variances are different
(the slopes of the lines near which the mass lies are different)
Answer: It depends on what measure of correlation you use.
The Pearson correlation (the most commonly used one) measures the linearity of a relationship between two random variables.
The Spearman rank correlation however, also measures nonlinear (monotonic) relationships. This is defined as the Pearson correlation coefficient between the ranked variables.
Comment: Good point, introduced an edit in the OP.
Answer: Perhaps rather than saying "less linear" you might say "less well modeled by a line". If you think of a scatter-plot of $(x,y)$ pairs, it might be sort of a disk or filled ellipse of points, or an amorphous blob. If it's an ellipse, then you'd say that a line drawn along the major axis of the ellipse "sort of fits" the data, especially if the ellipse is highly eccentric. This is exactly the situation in which the correlation is large. If the scatter plot is amorphous, like the standard drawing of an amoeba, then you'd say that it's hard to fit any particular line to the shape; in this case, correlation tends to be small.
I don't think that there's anything deeper here than that; the idea is simply that when the correlation is high, a scatter plot of the data tends to look pretty much like a highly eccentric ellipse, which itself looks a  lot like a line.
Comment: This answer certainly falls short of the whole truth.  For example, consider $(x_i:i=1,\ldots,8)$ $= (1,2,3,4,5,6,7,1000)$ and $(y_i:i=1,\ldots,8)$ $=(7,6,5,4,3,2,1,1000)$.  My software is telling me the correlation is $0.9999355$.  But "pretty much like a highly eccentric ellipse" isn't how I would describe this. ${}\qquad{}$
Comment: Or, if $(x_i:i=1,\ldots,21)=(-10,-9,-8,\ldots,8,9,10)$ and $y_i=x_i^2$ for $i=1,\ldots,21$ then the correlation is exactly $0$, but it's very far from being an "amorphous blob". ${}\qquad{}$
Comment: Thanks for that answer, I also never saw anything deeper than the idea you presented, but can we even mathematically show that the higher the correlation is, the more eccentric plot we get (so for $\rho=0,5$ the plot is always going to be less eccentric than for $\rho=0.8$), otherwise how can we be sure, that it is true for all bi-variate distributions?
Comment: I think the idea is that in many cases of actual statistical analysis, when you are looking for relationships between various properties of a set of observations, you often just see an amorphous blob with correlation near zero, and occasionally something that looks like a tilted ellipse or even something close to a diagonal line (where correlation is near 1 or -1). But this seems to me to be an oversimplification.
Comment: I agree completely with these comments, although if you tried to draw an ellipse around (or near) Michael's first set of data, I think  it'd be pretty highly eccentric, mostly aligned along the $x=y$ line. It was not clear to me at what level the OP was confused, and I figured that a broad-strokes description might be a good place to start.
Answer: correlation $=0.99$:

correlation $=0.95$:

correlation $=0.9$:

correlation $=0.7$:

correlation $=0.5$:

correlation $=0.3$:

correlation $=0$:

correlation $=-0.3$:

correlation $=-0.5$:

correlation $=-0.7$:

correlation $=-0.9$:

correlation $=-0.95$:

correlation $=-0.99$:

Appendix: Here is how I created these plots.
First I took a sample from a bivariate normal distribution with correlation $0$.  This of course gave me a scatterplot with non-zero correlation.
Then I replaced each $y$ value with the corresponding residual $y-\hat y$ where $\hat y$ is the fitted value, i.e. the $y$-coordinate of the least-squares line for predicting $y$ based on $x$.  This has two effects: $(1)$ It makes the correlation exactly $0$, and $(2)$ it makes the average of the $y$ values exactly $0$.
Then I divided the $y$ values by the standard deviation of the $y$ values.  I also subtracted the average $x$ value from all of them, and then divided them all by their standard deviation.  At this point I had a scatterplot in which the two averages were $0$, the two standard deviations were $1$, and the correlation was $0$.  That is the plot with correlation $0$ that you see above.
Then, to get a plot with correlation $\rho$, I replaced each data point $\begin{bmatrix} x \\ y \end{bmatrix}$ with
$$
\frac 1 2 \begin{bmatrix} \sqrt{1+\rho}+\sqrt{1-\rho}, & \sqrt{1+\rho}-\sqrt{1-\rho} \\ \sqrt{1+\rho}-\sqrt{1-\rho}, & \sqrt{1+\rho}+\sqrt{1-\rho} \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix}.
$$
That $2\times 2$ matrix is the positive-definite symmetric square root of the correlation matrix $\begin{bmatrix} 1, & \rho \\ \rho, & 1 \end{bmatrix}$.
Comment: Thanks a lot for the effort you take to explain me the concept, but I do not see how all these graphs address the point of the comment to the first answer. To produce the graphs you simulated a specific parametric bi-variate distribution (I would guess standard normal) with various $\rho$s, and you demonstrated that higher $\rho$ are associated with more eccentric plots. But it does not prove that it is always going to be the case for all bi-variate distributions. So it does not prove that $\rho$ can measure how eccentric a plot for an arbitrary distribution is, can it?
Comment: Actually, if I had simulated a sample of $200$ points from a bivariate normal distribution with correlation $0.7$, it would not be the least bit unusual to get a sample of $200$ points in which the correlation is $<0.65$ or $<0.7$, whereas if the correlation in the scatterplot labeled $0.7$ above is in fact exactly $0.7$, and similarly for the others. ${}\qquad{}$
Answer: I've added a graphical answer, and I think many books are deficient in this sort of graphics.
Here's another aspect of the meaning of correlation.
For vectors $(x_1,\ldots,x_n),\ (y_1,\ldots,y_n)\in\mathbb R^n$ suppose the coefficients $\hat\alpha,\hat\beta$ are so chosen as to minimize the sum of squares of the residuals $\hat y_i-y_i$ where $\hat y_i$ is the fitted value $\hat y_i=\hat\alpha + \hat\beta x_i$. ("Residuals" should not be confused with "errors".) Let $\bar y = (y_1+\cdots+y_n)/n$.  Then
\begin{align}
\sum_{i=1}^n (y_i-\bar y)^2 & \text{ is the total sum of squares.} \\[6pt]
\sum_{i=1}^n (\hat y_i - \bar y)^2 & \text{ is the explained sum of squares.} \\[6pt]
\sum_{i=1}^n (y_i - \hat y_i)^2 & \text{ is the unexplained sum of squares.}
\end{align}
The total sum of squares it he sum of its explained and unexplained components.  (Note that this statement relies on the orthogonality between the vector of fitted values $\hat y_i$ and the vector of residuals $y_i-\hat y_i$, which the reader may verify.)
Then the square of the correlation is the proportion of the total sum of squares that is explained.
Comment: Thanks, I think it is much closer to what I am looking for, I would only recast your answer in terms of the probability theory: say we have r.v $X,Y$ and we try to approximate $Y$ using $X$, so we decide to do it with a linear function $a+bX$, then we select $a,b$ such that $E(Y-a-bX)^2 \to \min_{a,b \in \mathbb R}$ we find optimal $a ,b$ and then $\rho(X,Y)=\frac{E(b+aX-E(Y))^2}{Var(Y)}$ for the optimal $a,b$, right?
Comment: So $\rho$ can be viewed as a measure of how good one variable can be approximated with another if one does his/her best with a linear function.
Comment: Your last comment is how it is usually stated.  But notice that in your statement that $\rho(X,Y)=\text{something}$, they cannot be equal when the correlation is negative.  Also, I think the expression on the right side is not right. ${}\qquad{}$
Comment: You need $\dfrac{\operatorname{E}((b+aX - Y)^2)}{\operatorname{var}(Y)} =(\rho(X,Y))^2$, not the version where you have $\operatorname{E}(Y)$. And of course you need to _square_ the correlation. ${}\qquad{}$
Comment: I think the right formula would be $\dfrac{\operatorname{E}((b+aX - Y)^2)}{\operatorname{var}(Y)} =1-(\rho(X,Y))^2$
Comment: You're right: it's the _explained_ proportion of the variance that is $\rho^2$, and the numerator of this fraction is the _unexplained_ mean square. ${}\qquad{}$
Comment: I would try to make the meaning of $\rho$ even more precise and would say that $\dfrac{ \operatorname{var}(Y) -  \operatorname{E}((b+aX - Y)^2)}{\operatorname{var}(Y)} =(\rho(X,Y))^2$ is a relative precision gain we have if we use the best linear function of $X$ to predict $Y$ instead of using just a real number $E(Y)$ to predict $Y$ ($Var(Y)$ is the expected mistake one has if s/he uses $E(Y)$ as a predictor).
Answer: Pearson correlation indicates how close the scatter-plot of $(x,y)$ points are to a line. It does not tell you if the relationship between them is linear.
Consider the following graph from Sturdy Econometrics:

Suppose you had planned a regression to estimate the Cuban consumption function and, using income and expenditure data from the Cuban national accounts, you find the estimated equation to be
$$ \mathrm{Expenditure} = 1.9 + 0.69 \times \mathrm{Income} $$
with an $R^2$ of 0.71. This seems like a pretty good equation with a high $R^2$ and a coefficient with the right sign. But suppose further that you had the presence of mind to look at a scatter of observations [as shown below]. The message in these data is very different than the one suggested by the estimated regression. Clearly, the chance that any batch-oriented processing could have picked up this message is very remote indeed. … You would therefore be wise to reserve the right to do some interactive processing and to adjust the way you interpret the data if something unanticipated is discovered.
Comment: Maybe you'll understand and enjoy [Correlations Genuine and Spurious in Pearson and Yule](http://projecteuclid.org/euclid.ss/1177009870) maybe not.
Comment: "It does not tell you if the relationship between them is linear". it actually does, as I pointed in the OP $\left| \rho(X,Y)\right|=1 \iff X=b+aY$
Comment: Sure. But if you have $r_{xy} = 0.9$ and $r_{wz} = 0.85$ it doesn't automatically follow that there is a "more linear" relationship between between $x$ and $y$ than there is between $w$ and $z$. It just means $(x,y)$ pairs are closer to a line than are $(w,z)$ pairs. See also http://en.wikipedia.org/wiki/Correlation_and_dependence#/media/File:Anscombe%27s_quartet_3.svg
Comment: I would say, the term "more linear relationship" is so undefined, I would not use it at all, but the argument about how plots will look like for different $\rho$ is totally valid as Dilip Sarwate demonstrated.
Comment: No ... whether the variables are linearly related (except in the case of perfect correlation) cannot be determined via the correlation coefficient. Being close to a straight and being linearly related are different things.
Comment: Look this expression (which is a proved theorem) $\left| \rho(X,Y)\right|=1 \iff X=b+aY$ literally says, that two variables are linearly related ONLY IF $|\rho|=1$
Comment: And that is devoid of meaning for the real world as to whether you can deduce from a high $\hat{\rho}$ that $y = a + bx + \mathrm{noise}$ based on observations on $x$ and $y$.
Comment: I would not want to mix statistics in this discussion, intended to keep it at the level of the pure mathematical probability theory.
Comment: Thinking further about it, is not it always the case that when you have two random variables $X,Y$, then the following equality always holds $Y=a+bX+Z$, where $Z=Y-a-bX, a,b \in \mathbb R$, so you kind of do not need correlation at all to learn that $Y=a+bX+noise$, it is just always true.
Answer: Late, but it is rather for myself.
Let $X,Y$ be random variables. We want to check if one variable can be linearly approximated well enough by another variable. So take the loss function $R(a, b)=E[X-(aY+b)]^2$. We want to find $(a, b)$ such that $R(a, b)$ is minimal. Note that $R(a, b)$ is convex, so a local minimum coincides with the global minimum.
$$\frac{\partial R(a,b)}{\partial a}=-2EXY+2aEY^2+2bEY=0$$
$$\frac{\partial R(a,b)}{\partial b}=-2EX+2aEY+2b=0$$
Solving these equations, we get $a^*=\frac{EXY-EXEY}{EY^2-(EY)^2}=\frac{Cov(X,Y)}{Var(Y)},\ b^*=EX-\frac{Cov(X,Y)}{Var(Y)}EY$. Then after some lengthy calculations we get that
$$R(a^*,b^*)=Var(X)(1-\frac{Cov(X,Y)^2}{Var(X)Var(Y)})=Var(X)(1-r^2)$$
Where $r=\frac{Cov(X,Y)}{\sqrt{Var(X)}\sqrt{Var(Y)}}$ is the correlation coefficient. When $r=\pm1$ (and $r^2\leq1$ by the Cauchy inequality) we have that $0=R(a^*,b^*)=E[X-(a^*Y+b^*)]^2$, so $X=a^*Y+b^*$ almost surely.
Also $r^2>0$ shows some degree of linear dependence as $X$ can be approximated by a linear function of $Y$ with the loss, which is better than the worst possible case $R(a^*,b^*)=Var(X)$.
As $a^*=r\frac{\sqrt{Var(X)}}{\sqrt{Var(Y)}}$, the correlation coefficient shows positive or negative linear dependence.
And from $R(a^*,b^*)=Var(X)(1-r^2)$ it is clear why $r^2$ is "the proportion of the variance in the dependent variable that is predictable from the independent variable(s)". wiki

Meaning of correlation


Category where every object is a retract of every other object

Question: Are there non-trivial* categories where every object is a retract of every other object?
Does having this feature impose strong constraints on the structure of the category?
*meaning there are two objects that are not isomorphic
Comment: @AlvinL are you sure? I think that if you take the free category on two objects $A$ and $B$ generated by a retraction $f\colon A\to B$ (and its left inverse $g$) and a retraction $g'\colon B\to A$ (and its left inverse $f'$), $A$ and $B$ are not isomorphic.
Comment: @JonasLinssen I don't follow your argument. Why cannot there be such a functor? Or what do u mean with "meaningful functor"?
Comment: @AlexKruckman Doesn't this example already answer the question here?
Comment: By "non-trivial", do you mean "at least two non-isomorphic objects"?
Comment: Ok. Just saying that deleting comments is not a good practice. Now, both the comment by Alex Kruckman to AlvinL and my comment to you don't make sense anymore to future readers.
Comment: @AlexKruckman oop, good catch!
Comment: @AlexKruckman Yes, that is what I meant
Comment: If the category has a terminal object it must be trivial. I'm wondering if such a category can have all finite coproducts in a non-trivial way
Comment: @MartinBrandenburg It was a silly mistake. The idea was that for a forgetful functor, which reflects isomorphism classes (a rather strong condition tired me confused with being conservative), if the target category satisfies a Cantor-Schröder-Bernstein property this forces our example to be trivial. But these assumptions already fail for abelian groups as your example shows.
Answer: There is an abelian group $A$ such that $A$ is isomorphic to $A^3$, but not isomorphic to $A^2$. So the full subcategory $\{A,A^2\}$ is an example.

Another example has already been mentioned by Alex Kruckman in the comments: Consider the category with two objects $A,B$ and generated by morphisms $i,s : A \to B$, $j,r : B \to A$ with $r \circ i = \mathrm{id}_A$ and $s \circ j = \mathrm{id}_B$. So $A$ is a retract of $B$, and vice versa. To really prove that $A$ and $B$ are not isomorphic in this category (without refering to a more concrete example), we need to figure out all the morphisms. For example, $j \circ s$, $r \circ s$, $j \circ i$ are distinct morphisms $A \to A$, and they generate $\hom(A,A)$ as a monoid, but not freely since for example

$(j \circ s) \circ (j \circ s) = j \circ s$
$(j \circ s) \circ (j \circ i) = j \circ i$
$(r \circ s) \circ (j \circ s) = r \circ s$
$(r \circ s) \circ (j \circ i) = 1$

So this seems to be the monoid $\langle x,y,z \mid x^2=x, \, xz=z,\, yx=y,\, yz=1 \rangle$.
You would have to work out a normal form for all the elements in $\hom(A,A)$, and then do the same for $\hom(B,B)$, $\hom(A,B)$, $\hom(B,A)$, and then verify that indeed there is no isomorphism $A \to B$.
So even though it is easy to describe this (universal) example of two objects which are rectracts of each other, it is not so easy to verify directly that the objects are not isomorphic. Maybe it is in fact easier to write down a more concrete example (as above for abelian groups).
Comment: A more elementary concrete example is the full subcategory of the category of topological spaces consisting of two objects: a closed disc, and the union of two closed discs intersecting in a point on the boundary of both discs. Probably there are even more elementary examples. And of course, once you have a concrete example, that proves that Alex's universal example is an example.
Comment: Can you post this as a separate answer (brings extra visibility)?
Answer: A more elementary concrete example than the abelian group example in Martin's answer is the full subcategory of the category of topological spaces consisting of two objects: a closed disc, and the union of two closed discs intersecting in a point on the boundary of both discs. Probably there are even more elementary examples.
And of course, once you have a concrete example, that proves that Alex's universal example in comments is an example.


How to call external scripts and img links in master page of "asp.net empty web site" in VS2019

Question: I want to call external scripts and img links in HomeMaster page and also I have created a Home.aspx page under the homepage folder and I have created this project using asp.net empty web site in VS2019. So while I'm running the Home.aspx page the page is executing but the related css,js,img links are not loading properly.
This is my project structure :-

And I'm calling the scripts, img links in HomeMaster page like this.
In header

   <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">

  <title>Path</title>
  <meta content="" name="description">
  <meta content="" name="keywords">

  <link href="../assets/img/favicon.png" rel="icon">
  <link href="../assets/img/apple-touch-icon.png" rel="apple-touch-icon">

  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">

  <link href="../assets/vendor/aos/aos.css" rel="stylesheet">
  <link href="../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="../assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <link href="../assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
  <link href="../assets/vendor/glightbox/css/glightbox.min.css" rel="stylesheet">
  <link href="../assets/vendor/remixicon/remixicon.css" rel="stylesheet">
  <link href="../assets/vendor/swiper/swiper-bundle.min.css" rel="stylesheet">

  <link href="../assets/css/style.css" rel="stylesheet">

    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>

And in body after footer content(at the end) calling the js related files :-

    <form id="form1" runat="server">

      <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
     </asp:ContentPlaceHolder>

    </form>

And in Home.aspx page  calling the img links like below :-
<%@ Page Title="" Language="C#" MasterPageFile="~/HomeMaster.master" AutoEventWireup="true" CodeFile="Home.aspx.cs" Inherits="homepage_Home" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

</asp:Content>

So while I'm running the Home.aspx page I didn't get any error and the images are not displaying in Home.aspx page
I'm very new to this web site forms development.
Suggest me where I did the mistake and how to achieve this.
Please Help me.
Answer: Ok, so your master page?
The master page is in your root, so no need to "cork" down one folder as you have
eg this:

That should be this

(Assuming above is in your master page).
You can always test/check by opening the master page, and then from one of those folders, simple drag in the js file into the master page.
So, say like this:

    <title></title>

    <asp:ContentPlaceHolder ID="head" runat="server">

    </asp:ContentPlaceHolder>

    <form id="form1" runat="server">

My Master page part

            <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
            </asp:ContentPlaceHolder>

    </form>

Note the path name is from your "master" page
So, the above js script file is this:
function myhello() {

    alert("Hello")

}

So, now say if I add a web page (with master) say in this folder:

So, ok, that new web page (with master) is nested, but I can still in code use that js function myhello()
eg:
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

        <asp:Button runat="server" Text="Button"
            OnClientClick="myhello();return false" />

</asp:Content>

So, your script references need to be starting from root (same as master page).
The above (or any page) can now freely use that myhello() function I included in the master page - and nesting will not matter.
Of course if you want ONLY some pages in a given web page (master, or not with master), then relative path names WILL be required.


How is $\mathbb{N}$ with only projections $n\to 1$ equivalent to $\text{FinSet}^{op}$

Question: In the nLab article on Lawvere theory, it states that the category with objects $\mathbb{N}$ and morphisms generated by $\pi_i\colon n\to 1$ is equivalent to $\text{FinSet}^{op}$.
How can this be? For example, in the former category, it seems all morphisms have codomain 1. While in $\text{FinSet}$, there are many morphisms $m\to n$ for $m\neq 1$, and hence many morphisms whose codomain is not 1 in $\text{FinSet}^{op}$.
Comment: @DanielSchepler: Right, although they don't say it in the section I excerpted, I guess it's meant to be clear from the context of the article on Lawvere theories that they must mean $\mathbb{N}$ as a category with finite products. "Include these morphisms and also any products of these morphisms".
Comment: Yes, "generated" has to be understood to mean "generated as a Lawvere theory,"
Comment: $\pi_n: n \to 1?$
Comment: @AlfredYerger: I guess there are $n$ different projection morphisms $n=1\times1\times\dotsb\times1 \to 1$
Comment: @AlfredYerger: I guess it's clear now. If there is a projection morphism $\pi_1\colon 1\times1\to 1$, then there is also a morphism $\pi_1\times 1\colon 1\times1\times1\to 1\times 1$, i.e. an arrow $3\to 2$. So it's _not_ the case that all morphisms have codomain 1...
Comment: Well, probably what you meant is all morphisms are either an identity or have codomain 1.  Still, there's also the fact that there are endomorphisms $n \to n$ which are not isomorphisms.
Comment: But wouldn't you then need it to be something like "the category with finite products" with that presentation, not just the general category with that presentation?
Comment: @QiaochuYuan: Right on. Thanks for confirming.
Answer: You seem to have resolved this issue, but for future visitors:
The first thing to note is while $1$ is often used to indicate the terminal object of a category, in the context of Lawvere theories it is instead meant to represent the 1-fold product of some "dummy" object. So $\pi_i : n \to 1$ means a projection from the $n$-fold product to the $1$-fold product. To minimize this sort of confusion, I usually put the numerals in square brackets, e.g. $\pi_i : [n]\to[1]$. With this notation, the terminal object is actually $[0]$.
The statement on the nLab page is that the Lawvere theory generated from no operations and no equations is equivalent to $\mathbf{FinSet}^{op}$. That is, the category with finite-products freely generated from a single object, $X$, with no additional arrows or equations is equivalent to $\mathbf{FinSet}^{op}$.  The objects of this category up to canonical isomorphism will be finite products of the single object, $X^n$, for each $n\in\mathbb{N}$. The arrows are composites of the projections, $\pi_i:[n]\to[1]$ for each $i\in\{1,\dots,n\}$ for each $n\in\mathbb{N}$, and the $n$-fold tupling of any $n$ arrows with a common domain, i.e. $\langle f_1,\dots,f_n \rangle : X^m\to\prod_{i\in\{1,\dots,n\}}X^{n_i}\cong X^{\sum_{i\in\{1,\dots,n\}}n_i}$ where $f_i : X^m \to X^{n_i}$. This includes the $0$-fold case, $\langle\rangle: X^m\to X^0$. These arrows satisfy the usual laws for categorical products.
To make the connection to $\mathbf{FinSet}^{op}$, we note that the universal property of products means that every arrow $X^m\to X^n$ is a tupling of arrows $\langle f_1,\dots,f_n \rangle$ for $f_i : X^m\to X^1$. By induction on the length of a composition, we can show any arrow $X^m\to X^1$ is equal to one of the projections $\pi_i$ for $i\in\{1,\dots,m\}$. That is, every arrow $X^m\to X^n$ looks like $\langle \pi_{\varphi(1)},\dots,\pi_{\varphi(n)}\rangle$ for some function $\varphi: \{1,\dots,n\}\to\{1,\dots,m\}$, i.e. $X^{\varphi}$. Thus, every arrow gives rise to a finite set function, and clearly each finite set function produces an arrow. It's easy to check functoriality using the universal property of products. Explicitly constructing the equivalence (i.e. the pair of natural isomorphisms) rather than relying on full, faithful, and essentially surjective implies equivalence is straightforward.


Calculating Trapezoid's three equal sides with just knowing: base and height?

Question: It is really an architectural problem. For example when you have a bay window and you want to find out the three equal sides of bay window by just having window opening size and how far out is protruding Bay window
That what I'm trying to calculate: the given are the base and the height.
I want to calculate three equal sides of the trapezoid.
Any help greatly appreciated.
Thank you,
Answer: The trapezoid can be labelled as follows, where $b$ is the base, $h$ is the height, and $k$ is the length of one of the three equal sides.

When the altitude $h$ is dropped, there is a gap between where it touches the base and where $k$ touches it. Let the length of this gap be $g$. Then
$$g=\sqrt{k^2-h^2}$$
and
$$b=k+2g$$
so
$$b=k+2\sqrt{k^2-h^2}$$
And we want to solve this for $k$.
$$b-k=2\sqrt{k^2-h^2}$$
$$(b-k)^2=4(k^2-h^2)$$
$$b^2-2kb+k^2=4k^2-4h^2$$
$$=3k^2+2bk-4h^2-b^2$$
Then solve using the quadratic formula:
$$k=\frac{-2b+\sqrt{4b^2-4(3)(-4h^2-b^2)}}{6}$$
$$k=\frac{-2b+\sqrt{4b^2+12(4h^2+b^2)}}{6}$$
$$k=\frac{-2b+\sqrt{16b^2+48h^2}}{6}$$
$$k=\frac{-2b+4\sqrt{b^2+3h^2}}{6}$$
$$k=\frac{-b+2\sqrt{b^2+3h^2}}{3}$$
I believe that this is the answer.
Comment: Amazing, that's exactly what it is. I have been battling with this question repeatedly. Coming up with the answer= Genious and following the formula pretty straight forward. Just for my future information- in the beginning, to solve for "g" you used Pythagorean theorem and what is the second line? Is that a formula for the trapezoid. I never came across that before.
Comment: No, it is the same as my $x+2y=L$. side is $k$ this is the length between the dashed lines, and there are 2 parts outside the dashed lines, of same length $g$. When you add all in order this gives $b=g+k+g=k+2g$ where $b$ is the whole aperture.
Comment: @AdrianWysocki Since I defined $g$ as the gap between the altitude and one of the sides where they intersect the base, and since the top is parallel to the base and there are two identical gaps on either side of the base, the length of the base is equal to the length of the top plus two gap lengths.
Answer: Let the base be $b$, the height $h$, the length to be found $a$, and the angle between the base and the sloping sides be $\theta$. (Similar triangles implies both such angles are the same). Then we have the two equations
$$ h = a\sin{\theta}, \\
b = a+2a\cos{\theta}. $$
We now eliminate $\theta$: we have
$$a^2\sin^2{\theta} = h^2, \qquad a^2\cos^2{\theta} = \frac{(b-a)^2}{4}, $$
and then adding and using the Pythagorean identity $\cos^2{\theta}+\sin^2{\theta}=1$ gives
$$ 4a^2 = 4h^2+(b-a)^2, $$
(we could get to here by using just Pythagoras and the length from the corner to the foot of the perpendicular), so
$$ 3a^2 +2ba = 4h^2+b^2 $$
Completing the square gives
$$ (a+b/3)^2 + \frac{b^2}{9} = \frac{4h^2+b^2}{3}, $$
so
$$ a = \frac{-b \pm 2\sqrt{3h^2+b^2}}{3} $$
Of course we want a positive root since $a$ is a length, so we have to take the $+$.
Comment: Another Amazing way, to calculate Trapezoid three equal sides.
Answer: Let's call $L=230$ the opening size and $h=66$ the protruding depth.
I'll call $x$ the sides and $y$ the complement, i.e. $x+2y=L$.
Applying pythagoras' theorem in one of the rectangle triangle we have $y^2+h^2=x^2$
Now we solve in $y$ : $y^2+h^2=L^2-4Ly+4y^2\iff3y^2-4Ly+L^2-h^2=0$
$\Delta=16L^2-12(L^2-h^2)=4L^2(1+\frac{3h^2}{L^2})$
$y=\frac{4L-2L\sqrt{1+\frac{3h^2}{L^2}}}{6}$

$\displaystyle x=L-2y=\frac L3(2\sqrt{1+\frac{3h^2}{L^2}}-1)$
Comment: Amazing, slightly more difficult to follow as a non-mathematician, but the result is correct.
Comment: The only difference with other answers is that I factorized $L$ outside the square root. If you put it back you get $\frac{2\sqrt{L^2+3h^2}-L}3$ which is Frpzzd formula with different letters.


Building a Data Warehouse

Question: I've seen tutorials articles and posts on how to build datawarehouses with star and snowflakes schemas, denormalization of OLTP databases fact and dimension tables and so on.
Also seen comments like:

Star schemas are for datamarts, at best. There is absolutely no way a true enterprise data warehouse could be represented in a star schema, or snowflake either.

I want to create a database that will server for reporting services and maybe (if that isn't enough) install analisys services and extract reports and data from cubes.
My question was : Is it really necesarry to redesign my current database and follow the star/snowflake schemas with fact and dimension tables ?
Thank you
Answer: There are few things I would look at before redesigning your database.

I'm pretty sure that reporting services doesn't need a star/snowflake to do its work so you might see what you can build with your nomalized database.
Try building views that denormalize your OLTP data.  It will get you thinking about the design aspects that you will need if you do redesign your database.
Answer: It pretty much is, unless you dump the whole SQL side and build the repository in a Cube - in which case you MAY get away with an OLTP schema underlying the data.
The main problem is that a non-star-schema approach simply puts a lot of burden on the server for analysis. That said, the idea to sue analysis services is terrific - they shine in this area. Just try whether you can directly load them from... the OLTP schema, possibly a snapshot of that.
Comment: If you give me a good resource (tutorial) on how to build and make best use of OLAP you've got yourself a winning answer :)
Comment: Sorry, no online resource I know of. This is something requiring experience.
Answer: Another part of the rationale of the data warehouse is that any computations to massage or transform data are done prior to loading it into a particular schema so that much what is pulled from a data warehouse is "ready to use".
Answer: I'd recommend a good book on the subject: http://www.amazon.co.uk/Microsoft-Data-Warehouse-Toolkit-Intelligence/dp/0471267155/ref=sr_1_3?ie=UTF8&s=books&qid=1272019644&sr=8-3
Although it is targeted at 2005 (2008 version I think is in the pipeline) the general theory holds well, and the design and planning steps are almost platform independent anyway.
Worth it's weight in gold if you are looking to get into DW :)

Building a Data Warehouse


Segment facet_wrap into multi-page PDF

Question: I have searched around for a solution to this, but it appears that most deal with individually generated plots being combined into PDF format, rather than separating out plots generated using faceting onto separate pages of a PDF.
Example Data
In the above data using the following code, selecting all items in the generated list:
Ex<-read.csv("StackOverflowEx (3).csv")
library(ggplot2)
library(reshape2)
vars <- select.list(names(Ex),multiple=TRUE,graphics=TRUE)
Cases<-subset(Ex,select=vars)

gg<-melt(Cases,id=c("Item","Total","Admin"))
print(ggplot(gg, aes(x=Total,y=Admin))+
  geom_point(colour="dark green",size=1.5)+
  geom_point(aes(y=value,color=variable))+
  geom_smooth(aes(y=value,fill=variable),
              method=loess,size=1,linetype=1,se=T)+
  facet_wrap(~variable,ncol=2,nrow=1000)+
  ylim(0,1)+
  labs(x="Expected",y="Admin",title=vars))

...should generate a facet wrap of all 8 (A-H) Cases.  However, generating this tends to cramp the plots and make them less readable, and in practice, I intend to use this on 500+ cases (which just returns bars labeled with the column name with no readable charts).
Is it possible to specify the number of charts in the faceting to appear on an individual page when converting to PDF, rather than having all plots compress into a single page?  For example, using the above data, generating two 2x2 plots on separate pages that contain all 8 cases individually (i.e. Cases A-D on pg 1, Cases E-H on pg 2).
I could do this by highlighting 4 cases + "Item", "Total" & "Admin" and repeating for the next 4 cases and combining the resultant PDFs.  However with upwards of 500 cases in practice this would mean more than 100 iterations with lots of potential for human error.  Some help with automating the process would be great.
Comment: Hadley suggested manual intervention [in 2011](http://osdir.com/ml/ggplot2/2011-06/msg00248.html). I'd try figuring out what # facets/pg works and then sandwich the loop or "apply' over that `n` between `pdf(…)` & `dev.off()` calls.
Comment: I would loop over the 500 variables in groups of 4 or 5 and then generate a chart for each, dumping all to pdf. I recently did something similar where I used a loop to generate 4 plots per page and grid.arrange to plot 4 in each pdf page
Comment: All very helpful.  Unfortunately, my comprehension exceeds my coding ability, so my efforts thus far have not been very fruitful.
Comment: if you search for `marrangeGrob` you might find a few ideas, e.g. [here](http://stackoverflow.com/q/16809488/471093)
Comment: Data link at top of post is currently protected. Would be helpful to future users if reproducing example didn't depend on sending a request for permission to access that info on a Google Drive.
Answer: As there is no answer yet. Here is one:
library(ggplot2)
library(reshape2)

Ex <- read.csv("C:/Users/Thomas/Desktop/StackOverflowEx (3).csv")
gg <- melt(Ex,  id = c("Item", "Total", "Admin"))

# put in number of plots here
noPlots <- 4
# save all variables in a seperate vector to select in for-loop
allVars <- unique(gg$variable)
noVars <- length(allVars)

# indices for plotting variables
plotSequence <- c(seq(0, noVars-1, by = noPlots), noVars)

# pdf("plotpath.pdf") # uncomment to save the resulting plots in a pdf file
# loop over the variables to plot
for(ii in 2:length(plotSequence)){
  # select start and end of variables to plot
  start <- plotSequence[ii-1] + 1
  end <- plotSequence[ii]

  # subset the variables and save new temporary data.frame
  tmp <- subset(gg, variable %in% allVars[start:end])
  cat(unique(tmp$variable), "\n")

  # generate plot
  p <- ggplot(tmp,  aes(x = Total, y = Admin))+
    geom_point(colour = "dark green", size = 1.5)+
    geom_point(aes(y = value, color = variable))+
    geom_smooth(aes(y = value, fill = variable),
                method = loess, size = 1, linetype = 1, se = T)+
    facet_wrap(~variable, ncol = 2, nrow = 1000)+
    ylim(0, 1)+
    labs(x = "Expected",  y = "Admin")
  print(p)
}
# dev.off()

Comment: Wow.  Thank you.  I had put this project on the back burner, but your code did exactly what I was looking for.  Again, very appreciated.

Segment facet_wrap into multi-page PDF


Como obter informações do computador com C#?

Question: Como informações do computador onde está sendo executado a aplicação C#, como nome do computador, IP, status do firewall, se tem antivírus instalado, se o antivírus esta ativo, etc.
Answer: A pergunta é um pouco ampla. Vou mostrar o caminho que é o mais importante. Se tiver dúvidas específicas você poderá fazer perguntas novas específicas.
Tenha em mente que nem todas informações podem ser obtidas facilmente. Algumas talvez precise ser de uma forma bastante específica e/ou com pouca confiabilidade. Então nestes casos provavelmente nem vale o esforço.
Um dos namespaces que fornecem essas informações é o System.Management. Lá existem diversas classes que fornecem boa parte das informações que você deseja. Tem que pesquisar cada uma das classes e ver quais são úteis. A maioria delas possuem exemplos de uso. Todo namespace é limitado no Mono e no .NET Core. Então considere que só funciona no Windows e na implementação completa do framework. Dê uma olhada também no System.Management.Instrumentation.
Algumas classes fornecem as informações como uma consulta SQL, então tem que aprender todas as possibilidades de queries. Na documentação vai dando o caminho para aprender tudo. Esta linguagem chama-se WQL.
Algumas classes para começar seu estudo: ManagementObjectSearcher. ManagementObjectCollection.
Se gosta de usar LINQ tem uma biblioteca para acessar algumas destas informações desta forma. Não sei nada sobre a qualidade dela.
Outra classe bastante útil que fornecem outras informações é a Environment. Há exemplo de uso na documentação. A maioria dos elementos são obtidos de forma simples através de propriedades. Algumas precisam ser enumeradas.
Alguma coisa ainda pode ser obtida com a classe SystemInformation.
Algumas informações podem ser obtidas através do registro do Windows. Estuda a classe Registry e outras classes relacionadas. Como eu disse, provavelmente teria que saber o que buscar para obter informações relevantes sem muito ruído. É mais fácil quando você quer saber se algo está presente.
Algumas informações só podem ser obtidas com permissão elevada.
Um exemplo de código:
using System;
using System.Collections.Generic;
using System.Management;

var consulta = new ManagementObjectSearcher("SELECT * FROM Win32_BIOS");
ManagementObjectCollection bios = consulta.Get();

foreach (ManagementObject obj in bios) {
    var item = new Win32_BIOS();
    item.BiosCharacteristics = (ushort[])obj["BiosCharacteristics"];
    item.BIOSVersion = (string[])obj["BIOSVersion"];
    item.BuildNumber = (string)obj["BuildNumber"];
    item.Caption = (string)obj["Caption"];
    item.CodeSet = (string)obj["CodeSet"];
    item.CurrentLanguage = (string)obj["CurrentLanguage"];
    item.Description = (string)obj["Description"];
    item.IdentificationCode = (string)obj["IdentificationCode"];
    item.InstallableLanguages = (ushort?)obj["InstallableLanguages"];
    item.InstallDate = (DateTime?)obj["InstallDate"];
    item.LanguageEdition = (string)obj["LanguageEdition"];
    item.ListOfLanguages = (string[])obj["ListOfLanguages"];
    item.Manufacturer = (string)obj["Manufacturer"];
    item.Name = (string)obj["Name"];
    item.OtherTargetOS = (string)obj["OtherTargetOS"];
    item.PrimaryBIOS = (bool?)obj["PrimaryBIOS"];
    item.ReleaseDate = (string)obj["ReleaseDate"];
    item.SerialNumber = (string)obj["SerialNumber"];
    item.SMBIOSBIOSVersion = (string)obj["SMBIOSBIOSVersion"];
    item.SMBIOSMajorVersion = (ushort?)obj["SMBIOSMajorVersion"];
    item.SMBIOSMinorVersion = (ushort?)obj["SMBIOSMinorVersion"];
    item.SMBIOSPresent = (bool?)obj["SMBIOSPresent"];
    item.SoftwareElementID = (string)obj["SoftwareElementID"];
    item.SoftwareElementState = (ushort?)obj["SoftwareElementState"];
    item.Status = (string)obj["Status"];
    item.TargetOperatingSystem = (ushort?)obj["TargetOperatingSystem"];
    item.Version = (string)obj["Version"];
}

Coloquei no GitHub para referência futura.