Combine separate RRD files to a single graph

Question: Using rrd4j, how can I combine several .rrd files either into a single .rrd or (ideally) to a single graph?
More details:
I have several copies of essentially the same .rrd. Each file records several sensor data readings, all with the name sensor-1, sensor-2 across files. So data1.rrd, data2.rrd will all contain data sources of sensor-1 etc.
The DS definition is as follows.
DS:sensor-1:GAUGE:35:U:U DS:sensor-2:GAUGE:35:U:U DS:sensor-3:GAUGE:35:U:U

I can generate a graph for each individually by adding a data source to a graph like this;
val graph = new RrdGraphDef()
graph.datasource("sensor-1", data1.rrd", "sensor-1", AVERAGE)
graph.datasource("sensor-2", data1.rrd", "sensor-1", AVERAGE)
graph.line("sensor-1", green)
graph.line("sensor-2", red)

but if I do the same but for data2.rrd (adding another datasource to the same graph instance), it seems to loose the preceding data and graphs just one of the file's data.
I suspect that each DS having the same name across files may be a problem.
Suggestions on how to achieve the same with regular RRD tool might also be helpful as I might be able to translate to rrd4j
Answer: This statement:

graph.datasource("varname", "filename.rrd", "dsname", AVERAGE)

defines a new variable to use called varname, which corresponds to the DS dsname in the file filename.rrd, consolodated using the AVERAGE Consolodation Function.
Clearly, you cannot have two variables in the same graph with the same name; however, there is nothing to prevent you from pulling data from multiple different RRD files, and nothing to prevent you from using a different varname to the DS name.
However, you should only use alphanumerics in the variable name -- in particular, avoid '-', even though it is supposed to work.  Underscores are OK.
So, this is perfectly valid:

graph.datasource("sensora", "sitea.rrd", "sensor", AVERAGE)
graph.datasource("sensorb", "siteb.rrd", "sensor", AVERAGE)

and will define two variables, sensora and sensorb corresponding to the same named DS in two different RRD files.
Do not use sensor-1 as a varname, as it contains a '-' symbol.
Not having seen the RRD4j code that is failing I can't say for certain, but I would suspect it is either because you are not renaming the varname, making both variables share the same name and overwrite one another, or because of the '-' in the varname.


Probability of a slot having exactly $K$ elements

Question: From this question asked in an interview:

Consider a hash table with $M$ slots. Suppose hash value is uniformly
  distributed between $1$ to $M$. Suppose we put $N$ keys
  into this $M$-slotted hash table, what is the probability that there
  will be a slot with $K$ elements? $K$ could vary from $0$ to $N$.

I'm not very good in statistics, that's why I'm asking for your help.  What is the probability and how to compute it?
I could think of the following. Let $a_i$ be the number of elements in slot $i$. Then $P(a_i = K) = P(a_j = K) = P_K, \forall i, j$. And the answer is given by $P^* = 1 - (1 - P_K)^M$. But how to comupte $P_K$?
PS. The only question I could answer is "what is the expected value of the number of elements in a single slot?". And the answer is $N/M$. Am I right?
Comment: I doubt that this is a question from an interview.
Comment: Related: http://mathoverflow.net/questions/104948/distribution-of-maximum-of-a-uniform-multinomial-distribution  http://www.math.dartmouth.edu/archive/m19w03/public_html/Section6-5.pdf
Comment: Thanks for the links! Would you bother checking my answer?
Answer: Ok, I think I get the answer thank to the link posted by leonbloy.
Consider the first slot. We have $N$ trials and every trial may put a value in first slot or not. Let $X_i$ be equal to $1$ if $i$-th trial puts a value into first slot or $0$ otherwise. Thus we have $P(X_i = 0) = \frac{M-1}{M}$ and $P(X_i = 1) = \frac{1}{M}$.
Now $P_K$ is the probability, that exactly $K$ of all $X_i$ are equal to $1$. Since $i$ varies from $1$ to $N$, there are $C_N^K$ possible situations. And in every situation we have $K$ ones and $N-K$ zeros for $X_i$. So the probability of each situation is $P(X_i = 0)^{N-K} P(X_i = 1)^K$.
Hence we have the following formula for $P_K$:
$$
P_K = C^K_N \left(\frac{M-1}{M}\right)^{N-K} \left(\frac{1}{M}\right)^{K} = C^K_N \frac{(M-1)^{N-K}}{M^N}
$$
And the answer is given by:
$$
P^* = 1 - (1 - P_K)^M
$$
Could anyone bother checking this solution?
Comment: The calculation of $P_K$ (probability that the first slot has $K$ keys) is correct, it's just a binomial.  But what follows ($P^*$) is wrong, because it assumes the probabilities of each slot are independent. The correct answer would be quite more difficult, that's why I suspect this is not an interview question, or that something is missing or wrong in the statement.
Comment: Seems like you're right. Thanks a lot!


arithmetic mean of a sequence converges

Question: We had a theorem that the means of a sequence also converges:

Let $(a_n)_{n\in\mathbb N}$ be a convergent sequence. Then $\displaystyle \overline a_n=\sum_{k=1}^n \frac{a_k}n$ also converges.

I've tried to prove it:
$|\overline a_n-a|=\frac1n|\sum_{k=1}^n(a_k-a)|\leq\sum_{k=1}^{M-1}|a_k-a|+\sum_{k=M}^n|a_k-a|$
The second sum is $<\frac{\varepsilon}2$, because there is an $M\in\mathbb N$ so that $(a_n)_{n\in\mathbb N}$ converges. Now you can consider all $n\geq\max\{M,\frac2{\varepsilon}\sum_{k=1}^{M-1}|a_k-a|\}$ and so $|\overline a_n-a|<\varepsilon$.
But can you also say that there is a $K\in\mathbb N$ such that $\frac1n\sum_{k=1}^{M-1}|a_k-a|<\frac{\varepsilon}2$ for all $n\geq K$? And do I have to take the first sum from $k=1$ to $M$ or can you do it as above?
Thanks for helping.
Answer: There are still some typos in your proof (and it isn't written down clearly, in my opinion).
So your proof seems to use this idea: Let $\varepsilon>0$, then there exists $M \in \mathbb{N}$ such that for all $n \geq M: |a_n-a| \leq \frac{\varepsilon}{2}$. Thus
$$|\bar{a}_n-a| \leq \frac{1}{n} \underbrace{\sum_{k=1}^{M-1} |a_k-a|}_{=:N} + \frac{1}{n} \underbrace{\sum_{k=M}^n |a_k-a|}_{\leq \frac{1}{2} \varepsilon \cdot n}$$
Now let $n \geq \max \{M, \frac{2}{\varepsilon} \cdot N\}=:M'$, then $|\bar{a}_n-a|\leq \varepsilon$.
Whether you take the first sum from $k=1$ to $M$ or to $M-1$ doesn't matter. Important is that

the first sum is finite and does not depend on $n$
in the second sum there are only $|a_k-a|$ such that $k$ is bigger or equal than $M$.

You could also sum from $k=1$ to $M+j$ for some $j \geq 0$.
Moreover, choose $K := \frac{2}{\varepsilon} \cdot N$, then
$$\frac{1}{n} \underbrace{\sum_{k=1}^{M-1}|a_k-a|}_{N} \leq \frac{1}{K} \cdot N \leq \frac{\varepsilon}{2}$$
for all $n \geq K$, so the answer to your (first) question is "yes".
Comment: @kathystehl By converse you mean that the convergence of the arithmetic mean implies the convergence of the sequence? This does not hold true, just consider $a_n = (-1)^n$.
Comment: Why does the first inequality hold?
Comment: Is the converse true?
Comment: Yes, that's what I meant. Thank you!
Comment: The second sum doesn't have n elements
Comment: @Whyka No, but it has at most $n$ elements.
Comment: @YoTengoUnLCD Write $a = \frac{1}{n} \sum_{k=1}^n a$ and use the triangle inequality.
Comment: I am joining on the discussion a bit late, but what is the importance of Max{M, 2N/eps}? why is M in there at all?
Answer: Since $\{a_n\}$ converges, it is bounded, and so is $\{a_n-a\}$. Choose $M$ such that
$$
|a_n-a|\le M\quad\forall n\in\mathbb{N}.
$$
If $1\le m<n$, then
$$
\Bigl|\frac1n\sum_{k=1}^na_k-a\Bigr|\le\frac1n\sum_{k=1}^m|a_k-a|+\frac1n\sum_{k=m+1}^n|a_k-a|\le M\,\frac{m}{n}+\frac1n\sum_{k=m+1}^n|a_k-a|.
$$
Let $\epsilon>0$ be given. First choose $m$ such that $|a_n-a|\le\epsilon/2$ for all $n>m$. Once $m$ is chosen, choose $n_0>m$ such that $M\,m/n_0\le\epsilon/2$. Observe that $n_0$ depends $m$ that depends on $\epsilon$, so hat $n_0$ depends on $\epsilon$. Then, if $n\ge n_0$ we have
$$
\Bigl|\frac1n\sum_{k=1}^na_k-a\Bigr|\le M\,\frac{m}{n}+\frac1n\sum_{k=m+1}^n|a_k-a|\le\frac\epsilon2+\frac{n-m}{n}\frac\epsilon2\le\epsilon.
$$
Comment: No. Example: $(-1)^n$.
Comment: Is the converse true?
Comment: the sequence is not bounded both-side
Answer: This problem is a direct application of Dirichlet's test for series convergence. Note that, since the sequence $(a_n)$ converges, then the sequence of partial sums is bounded.
Comment: Wouldn't that imply that since $1/n\to 0$, it also holds that $\sum_{n=1}^M 1/n$ is bounded?

arithmetic mean of a sequence converges


Hide views tab display on user profile to profile owner

Question: I have a use case where I need to create a page for members of two specific roles (Contributor and NAD Contributor) to see their own unpublished content. Using views relationships and filters, I've created a tabbed page display at the path user/%/unpublished that only displays unpublished content belonging to the logged in user. All that works great except for one thing; the tab itself is visible on all user accounts, even though it's only visible to users of the specific roles. What this means is that there is a Unpublished tab (with no content) for other roles that don't need this page, so for instance the two Contributor roles would see an Unpublished tab on users of other roles.
Is there a way within Views to control the display of this tab to only be displayed on the profile pages of the roles specified in the Access settings for the display?
Thanks.
Comment: The way the access is meant, those are the roles users need to have to see the tab. Definitively, it's not what you want.
Answer: You might have already thought about this, but you could make a Panel Variant that only shows to those roles.
Comment: Yeah, good thought, since I'm already using the built in user panel page for the profile. However, we're just using a single column layout and I don't want to add another pane in the mix. I think I might just have to do it as a block and display it in the sidebar. The list will usually be pretty small.
Answer: I assume that your context filter is Content: Author uid. In that case, you can add a validation criteria, following these steps.

Under When the filter value IS available or a default is provided, select Specify validation criteria
As Validator, select User
Select Restrict user based on role
Under Restrict to the selected roles, select the roles you need the view visible
On Action to take if filter value does not validate, select Hide view

This is also applicable when the contextual filter is Content: User posted or commented.


How can I show these properties of $B^TB$?

Question: Let $B$ be some matrix in $\Bbb{R}^{k*n}$ and define $A=B^TB\hspace{0.5cm}(A\in\Bbb{R}^{n*n}$)
How can I show that $A$ is symmetric and positive-semidefinite and that A is strictly positive-definite if and only if $ker(B)=\{0\}$?
I've tried this: $x^TAx=x^TB^TBx=(Bx)^T(Bx)\geq0$, hence it is positive-semidefinite. Then, how can I show that it is symmetric?
Comment: Does this answer your question? [Is $AA^T$ a positive-definite symmetric matrix?](https://math.stackexchange.com/questions/730421/is-aat-a-positive-definite-symmetric-matrix)
Answer: Keep going.

Showing that $A$ is symmetric is trivial:
$$
A^t=(B^tB)^t=B^t(B^t)^t=B^tB=...
$$

Notice that $y^ty=\|y\|^2\ge 0$ for any vector $y$; particularly for $y=Bx$. This, with your attempt together, gives you the positive semidefiniteness of $A$.

Suppose $A$ is strictly positive definite. Then your attempt shows that $Bx=0$ implies $x=0$. On the other hand, if $Bx=0$, then your attempt also shows that
$x^tAx=0$ and thus $x=0$.


Can't Recover Space from qcow2 image without deleting wanted snapshots

Question: I have a virtual machine that started out with 5 snapshots 1,2,3,4,5.
I used qemu-img to delete snapshots 1,2,3. Snapshots 4 and 5 are still needed and were not deleted.
How can I release the space used by snapshots 1,2,3 and retain snapshots 4 and 5?
I have spent a lot of time searching for a solution, and the solutions I have tried got the following results:

Using qemu-img convert (Deleted needed snapshots)
qemu-img convert -O qcow2 Linux.qcow2 Linux_s.qcow2
Reduces the space used by Linux.qcow2, but deletes snapshots 4 and 5.

Using virt-sparsify (Doesn't recover any space)
cp Linux.qcow2 TEST.qcow2
sudo virt-sparsify --in-place TEST.qcow2
Retains the two undeleted snapshots, but doesn't recover the space that was
originally occupied by snapshots 1,2,3.

How can I recover the space in a qcow2 file after deleting snapshots, while retaining remaining snapshots?
I find it difficult to understand why there isn't an easy way to achive this that is clearly documented
Edit: Is there any way to copy Snapshot 4 to a new file as a snapshot, and then add the delta for snapshot 5.  Then I could just discard the extra file with the wasted space.
Comment: @shodanshok in my case the Virtual Disk size is 20GB, but the image file is well over 50GB.  Any possibility of coping the snapshots beginning with the first one manually to a new file (offline with he VM not running of course)?

If so any suggestions as to hos I might do this?.
Answer: Unfortunately, deleting a snapshot does not shrink a QCOW2 file below its max permitted logical size.
Using a 2 GB max-logical-size file as example:

if, due to snapshots, its current, real size is above 2 GB (ie: 3 GB), deleting previous snapshots will shrink it at 2 GB (as reported by du -hs, while ls -al continue to show its "enlarged" size);

if its current size is less than 2 GB, then deleting snapshots will not release any additional space (unless using qemu-img convert to create a new, shrunk file).

This is one of the reasons while Red Hat does not recommend using internal QCOW2 snapshots for production workloads: while very convenient and easy to use, they are less flexible (and somewhat more "opaque") than external snapshots.


Why does this TransactionScope not block subsequent requests until the first request is done?

Question: I've been looking into transactions for two days now, perhaps I'm missing something obvious after taking in so much information. The goal here is to block simultaneous request. If condition is true, data is inserted, after which condition will be false. Simultaneous requests will both check condition before data could be inserted and then will both try to insert data.
public async Task<ActionResult> Foo(Guid ID)
{
    Debug.WriteLine("entering transaction scope");

    using (var transaction = new TransactionScope(
        TransactionScopeOption.Required,
        new TransactionOptions() { IsolationLevel = IsolationLevel.Serializable },
        TransactionScopeAsyncFlowOption.Enabled
        ))
    {
        Debug.WriteLine("entered transaction scope");

        var context = new DbContext();

        Debug.WriteLine("querying");
        var foo = context.Foos.FirstOrDefault(/* condition */);
        Debug.WriteLine("done querying");

        context.Foos.Add(new Foo());

        /* async work here */

        Debug.WriteLine("saving");
        context.SaveChanges();
        Debug.WriteLine("saved");
        Debug.WriteLine("exiting transaction scope");
        transaction.Complete();
        Debug.WriteLine("exited transaction scope");

        return View();
    }
}

This is the debug output when executing two requests at once with Fiddler:

entering transaction scope
entered transaction scope
querying
done querying
entering transaction scope
entered transaction scope
querying
done querying
saving
saving
saved
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
exiting transaction scope
exited transaction scope

This is my understanding of how the code is supposed to work:

A transaction with serialisable isolation level is required, to prevent phantom reads.
I cannot use DbContext.Database.Connection.BeginTransaction, when executing a query an error is thrown:

ExecuteReader requires the command to have a transaction when the connection assigned to the command is in a pending local transaction.
  The Transaction property of the command has not been initialized.

TransactionScope normally causes causes problems when using task-based async.
http://entityframework.codeplex.com/discussions/429215
However, .NET 4.5.1 adds additional constructors to deal with this.
How to dispose TransactionScope in cancelable async/await?
EF 6 has improved transaction support, but I'm still on EF 5.
http://msdn.microsoft.com/en-us/data/dn456843.aspx

So obviously it's not working like I want it to. Is it possible to achieve my goal using TransactionScope? Or will I have to do an upgrade to EF 6?
Answer: Serialization does not solve the old 'check then insert' problem. Two serializable transactions can concurrently evaluate the condition, conclude that they have to insert, then both attempt to insert only for one to fail and one to succeed. This is because all reads are compatible with each other under serializable isolation (in fact they are compatible under all isolation levels).
There are many schools of thought how to solve this problem. Some recommend using MERGE. Some recommend using a lock hint in the check query to acquire an X or U lock instead. Personally I recommend always INSERT and gracefully recover the duplicate key violation. Another approach that does work is using explicit app locks.
EF or System.Transactions really add only noise tot he question. This is fundamentally a back-end SQL problem. As for the problem of how to flow a transaction scope between threads see Get TransactionScope to work with async / await (obviously, you already know this, from reading the OP... I didn't register in first read). You will need this to get your async code to enlist in the proper context, but the blocking/locking is fundamental back end problem, still.
Comment: Read http://stackoverflow.com/questions/4034976/difference-between-read-commit-and-repeatable-read/4036063#4036063
Comment: Ah, I get it now. A second transaction can't insert new data until the first transaction is committed, but a second transaction can still read data.
Comment: Then I fundamentally misunderstood [how transaction isolation levels work](http://blogs.msdn.com/b/sqlcat/archive/2011/02/20/concurrency-series-basics-of-transaction-isolation-levels.aspx). In hindsight, gracefully recovering is the easiest solution, but I found out about transaction isolation levels early in my search for a solution to this problem and it looked like the correct way to do it.


How to make a query based on multiple checkbox value

Question: I want to make a query based on the input of the checkboxes.
This is wat i made:
       <form action="#" method="GET" id="filter">
<input type="checkbox" name="toe[]" value="ja">ja

<input type="checkbox" name="toe[]" value="misschien">misschien

<input type="checkbox" name="toe[]" value="nee">nee

 <input type="submit" name="kies" value="Kies" />
</form>

 if(isset($_GET['toe']) && count($_GET['toe'] > 0)) {
$toeid = implode(',', $_GET['toe']);
$toeid = mysql_real_escape_string($toeid);
}

$sql = "SELECT  *
FROM `table`
WHERE TOEGEZEGD = '$toeid'
ORDER BY $field $sort";

This works, but only if 1 checkbox is checked, otherwise i get an output of ja,nee and that doesn't work.
I also want (if possible) that on return the checkbox ticked in the query will kept ticked. But the first is the important, the rest will come.
Comment: **WARNING**: `mysql_query` is an obsolete interface and should not be used in new applications as it's being removed in future versions of PHP. A modern replacement like [PDO is not hard to learn](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/). If you're new to PHP, a guide like [PHP The Right Way](http://www.phptherightway.com/) can help explain best practices.
Comment: Thank you for the warning, but this is not a option at this moment for me
Answer: What you need is a WHERE TOEGEZEGD IN (...) clause instead of what you have here. This requires escaping all of the incoming parameters individually and joining them with a comma.
Comment: Can i make the query like this you mean ?  WHERE TOEGEZEGD IN ('$toeid') ?
Comment: It will look like `IN('ja','nee')` when it's properly escaped.
Comment: Oke, i made the query like this:                                 $sql = "SELECT  *
FROM `sponsoren`
WHERE TOEGEZEGD IN ('$catid')  which does not give error but also not the right outcome, when echo $catid it says ja,nee and not 'ja','nee'. How do i change that ?
ORDER BY $field $sort";
Comment: What you need to do is use [`array_map`](http://php.net/manual/en/function.array-map.php) to convert the arguments: `$cat_ids = implode(",", array_map('mysql_real_escape_string', $_GET['toe']))` It's worth noting this is is a complete non-issue in a modern
[development framework](http://codegeekz.com/best-php-frameworks-for-developers/) like [Laravel](http://laravel.com/) that has a full database layer.
Comment: I do understand that my way (mysql,php) is old and out of date but for this moment i just have to get i working so that we (very small organization of 6 people) can use it until the summer. I'm not able to stop it and learn myself a new way and get i working in a few weeks. When it works i will have time to set up a new 'version' using more mordern ways.  thanks for the help
Comment: Good to hear. It's just a lot easier to develop little apps like this using a framework than to have to hack around with stuff like writing raw SQL queries, *especially* for a small group of people.
Comment: if(isset($_GET['toe']) && count($_GET['toe'] > 0)) {
$toeid = implode(",", array_map('mysql_real_escape_string', $_GET['telefoon']));
}   Using this does not solve it, it still only works when using one checkbox
Comment: What sort of query does that generate? You should be seeing stuff like `IN ('a','b')` for checkboxes "a" and "b". Are you sure `$_GET['toe']` is an array? Also why are you using the `telefoon` identifier in there?
Comment: (telefoon = toe , misstype).  i echo $toeid, it comes back with whatever i check. ja or nee or misschien. In that case the query returns rows where TOEGEZEGD is one of these. But when i checked 2 boxes it echo's ja,nee (or whatever i checked and the query comes empty (no rows). Then i tried instead of WHERE TOEGEZEGD IN ('$toeid') , WHERE TOEGEZEGD IN('ja','nee') and then it works. So i get the impression that $toeid put in: ja,nee instead of: 'ja','nee'
Comment: You may need to write a wrapper function that puts the quotes on the beginning and end of each string. It's massive irritations like this that make `mysql_query` such a waste of time.


C++ : memory leak for just constructor

Question: I am creating a class from a huge external package.
And I ran:
Foo* foo = new Foo("bar", 100);
if(!foo)
{
    delete foo;
}

with
Foo::Foo(TString bar, int num)
{
    setnull();
}

and the setnull() is just setting every class pointers in NULL, like:
void Foo::setnull()
{
    fooArray = NULL
    ...
}

and the destructor
Foo::~Foo()
{
    if(fooArray != NULL)
            delete[] fooArray;
    ...
    setnull();
}

There are actually a lot of pointers to the classes from the external packages setting to NULL as well in the .hh file. As a result I got:
definitely lost: 332 bytes in 1 blocks

I also get indirect lost from adding in constructor:
fooArray = new (nothrow) bool [5];
    if (fooArray == NULL)
    {
        cout << "ERROR: memory could not be allocated"<<endl;
    }
fooArray[0] = 0;

with
indirectly lost: 26 bytes in 2 blocks

(one other thing, somehow the title for Stackoverflow tends to eat up the "++" sign)
Comment: Why the obsession with pointers? Pointers are generally an **inferior** solution.
Comment: @BeTheSame well, you made an attempt to use a pointer and you immediately created a memory leak. Any solution that lets you do that should be treated with care :-)
Comment: Is it? I would consider that.
Answer: Foo* foo = new Foo("bar", 100);
if(!foo)
{
    delete foo;
}

You're only deleting foo if it's NULL, if new returns an object, you won't delete it.
Answer: As has been pointer out in other answers, this logic is wrong:
if(!foo)
{
    delete foo;
}

But you don't have to perform the check anyway: calling delete in a null pointer is a no-op and completely safe. So you could simplify your code to
Foo* foo = new Foo("bar", 100);
delete foo;

Of course, the simpler, safer option would be
Foo foo("bar", 100);

C++ : memory leak for just constructor


Central Limit Theorem with (linear) weights

Question: I have a question about the CLT. Suppose we have the independently and identically distributed random variables $X_i$ with mean $\mu$ and variance $\sigma^2$. Then, by the Central Limit Theorem
$$
\sqrt{n}\left(\frac{1}{n}\sum_{i=1}^n X_i-\mu\right) \rightarrow N\left(0, \sigma^2\right)\Longleftrightarrow \sum_{i=1}^n X_i \rightarrow N(n\mu, n\sigma^2),
$$
as $n\rightarrow \infty$. But what if we have $\sum_{i=1}^nc_iX_i$, where $c_i$ are constants? Is it simply to say that
$$
\sum_{i=1}^nc_iX_i \rightarrow N\left(E\left[\sum_{i=1}^nc_iX_i\right], \;V\left[\sum_{i=1}^nc_iX_i\right]\right),
$$
that is,
$$
\sum_{i=1}^nc_iX_i \rightarrow N\left(\mu\sum_{i=1}^nc_i,\; \sigma^2\sum_{i=1}^nc_i^2\right),
$$
or am I missing something here?
Comment: What is the meaning of a convergence in distribution to a normal distribution with **variable** mean and variance? The question applies to the convergence to $N(n\mu,n\sigma^2)$ at the beginning of the question as well as to the convergence you are trying to establish later on.
Comment: I'm not sure I understand your question. A sum (and a sample mean) converges to $n$ times variable mean and variance, no? Or do you mean that it has to be expressed in terms of convergence to a standard normal?
Comment: In probability as in other branches of mathematics, the statement that $x_n\to y_n$ has no meaning. The convergence of a sequence $(x_n)$ is expressed as $x_n\to y$, for some $y$ which does not depend on $n$. The two statements my previous comment addresses both fail this requirement.
Comment: Ah, yes, of course. That makes sense and is something I didn't think about. Thank you for your help, and excuse my mathematical recklessness!
Answer: You might be after central limit theorems à la Lindeberg or Lyapunov, see here. These yield the convergence you are interested in, but stated more correctly, for example, some conditions ensuring that the sequence of general term
$$
\frac{\sum\limits_{i=1}^nc_iX_i-\mu\sum\limits_{i=1}^nc_i}{\sigma\cdot\sqrt{\sum\limits_{i=1}^nc_i^2}}
$$
converges in distribution to a standard normal distribution.


Filezilla client and VSFTPD : GnuTLS error -12: A TLS fatal alert has been received

Question: so right now i'am trying to configure vsftpd server for FTP(e)S.
It seems i am encountering issues with different clients.
Secure FTPD works fine for me.
Filezilla not.
The output from Filezilla
tatus:  Connecting to foo:21...
Status: Connection established, waiting for welcome message...
Trace:  CFtpControlSocket::OnReceive()
Response:   220 "Welcome to FTP!"
Trace:  CFtpControlSocket::SendNextCommand()
Command:    AUTH TLS
Trace:  CFtpControlSocket::OnReceive()
Response:   234 Proceed with negotiation.
Status: Initializing TLS...
Trace:  CTlsSocket::Handshake()
Trace:  CTlsSocket::ContinueHandshake()
Trace:  CTlsSocket::OnSend()
Trace:  CTlsSocket::OnRead()
Trace:  CTlsSocket::ContinueHandshake()
Trace:  CTlsSocket::Failure(-12, 53)
Trace:  GnuTLS alert 40: Handshake failed
Error:  GnuTLS error -12: A TLS fatal alert has been received.

Paste from vsftpd:
# Could be whatever you like, or 990 if you want to use the now-deprecated ftps port.
listen_port=21

# Limit passive ports to this range to assis firewalling
pasv_min_port=30000
pasv_max_port=30003

#May be needed to help packets through some NAT/firewall setups. The address
# is the external ip of the machine, assuming it is a static one.
pasv_address= "foo" ---> we NAT everything so this has the EXTERNAL IP

# Set to ssl_enable=YES if you want to enable SSL
ssl_enable=YES
anon_mkdir_write_enable=NO
anon_root=/srv/ftp
anon_upload_enable=NO
idle_session_timeout=900
log_ftp_protocol=YES
pasv_enable=YES
ssl_sslv2=NO
ssl_sslv3=NO
ssl_tlsv1=YES

# Path to the certificate and key files (which should be the same file)
rsa_cert_file=/etc/vsftpd2.pem
rsa_private_key_file=/etc/vsftpd2.pem

# No ssl for bad boys
#allow_anon_ssl=NO

# All local logins (i.e. non-anonymous) are forced to use ssl.
force_local_data_ssl=NO
#force_local_logins_ssl=YES
#dsa_cert_file=/etc/vsftpd.pem
require_ssl_reuse=NO

So question is: what goes wrong here?
BTW: I am furthermore not completely sure what the difference is between ftps and ftpEs
Thank you
Answer: ok, found it. Apparently there is some strange behavior between the latest filezilla 3.5 client and ftps.
for vsftpd, the solution was simply to add: ssl_ciphers=HIGH in the vsftpd.conf file
I'am not sure whether i am allowed to post this as well, but there is a threat about this in the filezilla forums.
http://forum.filezilla-project.org/viewtopic.php?f=2&t=23280
Comment: I know it's 2 years later, but i'm having this problem now but do not appear to have a file located in "/etc/vsftpd.conf".
Answer: If chroot_local_user=yes is used then ssl_ciphers=HIGH wont work.


IQueritable MVC can't find the database

Question: I'm working on a MVC project and I can't fix the following:
   public class localitatiRepository
{
    public IEnumerable<SelectListItem> GetLocalitati()
    {
        IQueryable<localitati> loc = db.localitatis;  //ERROR at db
        SelectList lst = new SelectList(loc, "idlocalitate", "localitate");
        return lst;
    }
}
}

Can't find the db.Isn't that the table from the databases? Or that line
  db.localitatis

where should it be implemented? No idea where to find to fix this issue.Ideas?
Answer: Which database framework are you using, and which programming language? Is it Entity Framework and C#, for instance?
Also, think about this: does it make sense to assign a database table object reference to a IQueryable? Probably not. Most likely, you have to run some other method on your table - such as db.mytable.get(someId) - which (might) return an IEnumerable of some sort.
Actually, if you are programming in C#, you might consider not setting the expected return type for your variable explicitly, and instead use the generic var type that automatically assigns the correct type:
var loc = db.mytable.someGetterMethod(xyz);

Hope that helps!

IQueritable MVC can't find the database


Enviar um comando sem atualizar a pagina

Question: Estou desenvolvendo uma aplicaçao web utilizando o PlayFramework, e estou com um problema ao clicr o comando gostaria de exibir um alert e nao redirecionar a pagina como ele esta fazendo, redireciando para uma tela em branco. Ao invez disso mostrasse somente o alert informando que o comando foi enviado e manter a pagina atual na tela.
Minha pagina html onde eu envio os comandos: onde no datatable tenho os comandos ativar, desativar e reiniciar, sao esses os botoes onde é pra enviar o comando e somente mostrar um alert

                         Detalhes Patch panels

                                    Patch panel
                                    MAC
                                    IP
                                    Número de portas
                                    Status

                                #{list items:t.patchpanels, as:'p'}

                                    ${p.nome}
                                    ${p.mac}
                                    ${p.ip}
                                    ${p.numPortas}
                                    ${p.status}

                                             Ativar
                                             Reiniciar
                                             Desativar
                                             Detalhes

                                #{/list}

Quando clico no botao de comando ele a classe MQTT:
public class ComandosMqtt extends Controller {
@AuditoriaOctopus
public static void ativar(String ip, String porta, String comando) throws MqttException {
    Mqtt mqtt = Mqtt.getInstance();

    mqtt.comandoMqtt(ip, porta, "active"); //envia os valores como parâmetro para a função
    //renderJSON("Ativado");//mostra apenas o IP na tela, é necessário alterar para poder mostrar novamente a página recarregada

}
@AuditoriaOctopus
public static void reiniciar(String ip, String porta, String comando) throws MqttException {
    Mqtt mqtt = Mqtt.getInstance();

    mqtt.comandoMqtt(ip, porta, "restart");
    //renderJSON("Reiniciado");
}
@AuditoriaOctopus
public static void desativar(String ip, String porta, String comando) throws MqttException {
    Mqtt mqtt = Mqtt.getInstance();

    mqtt.comandoMqtt(ip, porta, "deactive");
    //renderJSON("Desativado");
}

public ComandosMqtt(String ip, String porta) {
    try {
        Mqtt.getInstance();
    } catch (MqttException e) {
        e.printStackTrace();
    }
}

}

Comment: Qual a função que captura os cliques nos links?
Comment: Se vc não quer que haja redirecionamento, um código em jQuery resolveria: `$(".table-responsive td a").click(function(e){e.preventDefault();});`
Comment: @dvd voce poderia me dizer como ficaria no meu codigo? nao consegui abstrair o codigo que me passou
Comment: Era só colocar esse código no final da página: ``, considerando que esteja usando jQuery
Answer: isso resolve:

Palhetas

 ${palCount} Novas

                   #{list items:palhetas, as:'p'}

                  <input type="hidden" name="palheta.id" value="${p?.id}" />

                         <input type="hidden"name="palheta.id" value="${p.id}" />
                        Agente: ${p.agente.nome}  Bairro: ${p.endereco.bairro}

#{/list}

Denúncias

 ${denCount} Novas

                  #{list items:denuncias, as:'d'}

                  <input type="hidden" name="denuncia.id" value="${d?.id}" />

                        Nome: ${d.nome}  Bairro: ${d.bairro}

#{/list}


jquery - drag/drop an image from desktop and make it resizable

Question: I am trying to make a simple page where I can drag/drop an image from desktop and make it resizable inside div. I can drag, drop and resize an image that is already defined inside the page, but once I upload it from desktop, it is not resizable.  Here is my code.
    <!doctype html>

      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>jQuery UI Draggable - Default functionality</title>
      <link rel="stylesheet" href="css/jquery-ui.css">

      Drop file here.

Waiting for dragging the image get started...

Waiting image getting dropped...

Drag me around

me, too

Is it because I dynamically upload an image?
Answer: You have to execute $( "#resizable" ).resizable(); after image loading and after having added new img element to the DOM:
reader.onload = $.proxy(function (file, $fileList, event) {
    var img = file.type.match('image.*') ? " " : "";
    $fileList.prepend($("").append(img + file.name));
    $( "#resizable" ).resizable();
}, this, file, $("#fileList"));

Check my fiddle for a working demo: https://jsfiddle.net/beaver71/g73p7skk/


How to alter account activation mail Depending on roles

Question: In account settings ,Account Activation mail settings is general i think so.
I want the account activation mail to be altered. I want to check roles, according to that display the mail messages .
how will i do that?
Answer: You can create a new rule like this
EVENT saying  After saving a new user account
Conditions saying  User has role(s)  check your role there.

Actions saying send mail you can send the mail what you want in that.
Comment: Then two mail will be send I think
Comment: @RajeevK: how two mail will go. In the account settings he can disable that account activation mail.So only this will go.is that right ?
Comment: Then default mail will be disabled for each user type registration. Suppose there are 5 user type & I want to send custom mail to only 3 type of user registration but simple authenticate user registration will have default alert mail then your solution doesn't work..
Comment: @RajeevK: Yes understood, but he can create new rules and check for roles according to that mail will send for each rules. That is what is question meant i think. Roles and messages.
Comment: You mean several rules for each role. Then it can be done..
Answer: You should look into the hook_mail_alter for overriding the mail, which get send after user_save. You can look into the answer given for this question here --
Override _user_mail_notify() to NOT send email on user_save() if user status is changed
Though question is not relevant but the answer is.
Comment: I want to alter only for account activation.Not for all.
Comment: @NewToDrupal - This won't alter all the mail but you can write your logic inside and alter only that mail which you want to target. Like for account activation of usertype one.. It totally depends upon you to write the logic..


Creating New GUID automatically while inserting a new row to an existing table Not Working

Question: I have an existing table in MS SQL called myTab.
It has the following fields
empno(PK) nchar(10),
 age int

Now, i want to add a myGUID column and fill it up with a GUID whenever i insert a new row as well as Updating existing rows.
So i added the statement

ALTER TABLE myTab ADD myGUID uniqueidentifier DEFAULT NewId() NOT NULL;

Updating existing rows works correctly.
But, when i try to insert values,

INSERT INTO myTab VALUES ( 1000, 22 );

It fails, and gives the following message
**Column name or number of supplied values does not match table definition.**

When i do

insert into sourav_test2 values (20055711,23,NEWID());

The above statement works.
I want a GUID to be filled without changing the insert statement. Is it possible via a Trigger or a Function?
Comment: When you do inserts without providing the fields you are inserting into you have to insert all fields.  So either way you have to update your insert statements
Answer: Always list the columns you are inserting!
INSERT INTO myTab (empno, age)
    VALUES ('1000', 22);

Also use correct types for the values.  Unmentioned columns will be assigned their default values, or NULL if there is no explicit default.
Your table has three columns, so if you leave out the column list, then the insert expects three values.  You can still set a default, if you want by using the DEFAULT keyword in the VALUES clause:
INSERT INTO myTab (empno, age, myGUID)
    VALUES ('1000', 22, DEFAULT);

Comment: @SouravDas . . . Huh?  A default value sets `myGUID` on insert.  A trigger is utterly unnecessary.
Comment: Can't we use a trigger here which can do it?
Answer: Sourav's question about triggers got me thinking, so I tried a little test.  Why?
Imagine a scenario where an application has already been written with thousands of INSERT statements that leave off the column list.  In this case, if you could write an INSTEAD OF INSERT trigger that provides the column list, you could hopefully save yourself from correcting thousands of INSERT statements due to a newly added column.
Off the top of my head, I admittedly did not know if this could work.
So I wrote this little test:
CREATE TABLE tt (ColA varchar(1));

INSERT INTO tt VALUES ('a');

ALTER TABLE tt
ADD ColB uniqueidentifier DEFAULT NEWID();

GO

CREATE TRIGGER tr_tt
ON tt
INSTEAD OF INSERT
AS

INSERT INTO tt (ColA)
SELECT ColA FROM inserted;

GO

INSERT INTO tt VALUES ('a');

SELECT * FROM tt;

DROP TABLE tt;

I also tried a variation of the TRIGGER with the following INSERT just to be thorough:
INSERT INTO tt (ColA, ColB)
SELECT ColA, NEWID() FROM inserted;

The result was the same in both cases:   The same error as reported in the question.   So to answer the question:

Can't we use a trigger here which can do it?

The answer is NO.   Even if you put an INSTEAD OF INSERT TRIGGER on the table, the parser will still not let you write an INSERT..VALUES() statement unless the number and order of VALUES exactly matches the definition of the table.  A TRIGGER cannot be used to get around it.
Sooner or later, lazy coding exacts its price.


Clustering - Use ARI to compare different clustering

Question: I have a data set of 54000 genes and I used different methods for clustering such as HAC, K-means, model based clustering and CLARA. The objective is to compare these methods. I used the Adjusted Rand Index. But there is something that I do not understand.
With my data set, the ARI value between a clustering result obtained by K-means and another clustering result, also obtained by K-means, with the same number of clusters (i.e I effectuated K-means two times) , is only 0.40, which is not a high value.
My question is, if the ARI value is not high for the same method compare to itself, can we use ARI to compare the clustering results for different method? And is there other index or method to compare them? I already read the topic How to select a clustering method? How to validate a cluster solution (to warrant the method choice)? but I still do not understand which methods are used to compare the clustering results.
Comment: In which respect did your two k-means analyses of the same dataset differ?
Comment: Are your data quantitative? K-means is appropriate mostly for quantitative data.
Comment: "At different times" What do you mean? You mean you took the same data once then again? Was initial centers the same? Well, even if they aren't we should expect (with quantitative continuous data) quite similar results anyway. Perhaps you ought to tell more about your cluster analysis.
Comment: Are you sure there is any cluster structure in your data? And are you correct at your number of clusters? Did you check results first by some internal cluster validity indices (such as Calinski-Harabasz)? Also see if there are redundant dimensions (do PCA - maybe better to do clustering on few PCs than on 18 dimensions?). Before that is all checked there is no much sense in doing comparisons by external validity indices such as Rand or Adj. Rand.
Comment: Thank you for your answer. My data is quantitative and in R, I used the command kmeans(data, centers = 9) to obtain the two k-means analyses. I just run at two different times. I also ran many times, and the ARI varies between 0.11 and 1. Can we use ARI for a method which is very sensitive to the initial choice of center like K-means?
Comment: I took the same data, and in each command, I just specify the number of clusters, which is always 9, and the initial centers are randomly chosen.
Comment: Just to be more specify about the command. The command I used in R is as follows: `adjustedRandIndex(kmeans(data, centers = 9, iter.max = 100)$cluster, kmeans(data, centers = 9, iter.max = 100)$cluster)`, where 'data' is always the genomic data that I need to do the clustering.
Comment: What is the dimensionality of your data (how many variables)?
Comment: My data is a matrix of dimension 54000 x 18
Comment: Thank you for your answer. My data is a RNA-sequencing, obtained by different experiments, and I am sure that it has cluster structure. I've just calculated the CH index for a clustering results obtained by K-means, it returns a value of 21878.45 , but I'm not really sure that this value can say anything about my cluster.
Comment: Take a search about Calinski-Harabasz on this site.
Answer:
You are making a fallacy when saying if the ARI value is not high for the same method compare to itself, can we use ARI to compare the clustering results for different method. Cluster analysis results, most methods including K-means, are much dependent on its input "tuning" parameters (for K-means these are initial center seeds), and on data preprocessing. Your two runnings of K-means - which results you are comparing - differed, I suppose, in some of this respect (which, by the way? you haven't expressed it). Why do you expect the results must be very similar? They have not to. Especially if there is hardly any cluster structure in the data or the number of clusters was wrong. There is no reason to think,  a priori and generally, that the difference in results between two runnings of the same method under different parameters ought to be less than of between two different methods.
ARI's baseline (value 0) is not the absence of matching (similarity in results) but the level of chance matching. So value $0.40$ is not a low value, it is medium size value, I would say. But what is unadjusted Rand value, did you check? It will be higher.
There are many "external clustering criteria" besides Rand or Adjusted Rand. See some of their formulae in the description of !cluagree SPSS macro of mine on my web page (download collection named "Compare partitions" there).
Answer: K-means is randomized.
Running it two times may result in quite different clusterings. In particular when it does not work well, it tends to produce very different results. On those few data sets where k-means works well, it usually produces similar results. It is perfectly in line with theory if k-means results are not similar to each other.
As mentioned in the other answer, 40% more than random (ARI, not Rand index. You may want to also report the Rand index itself) is not too bad. It probably means some of the k-means clusters agree, while others don't. That is to be expected that some do and some don't.


Recurrent points and rotation number

Question: I need to show that if $f:S^{1} \rightarrow S^{1}$ is a preserving-order diffeomorphism and $f$ has irrational rotation number, then $f$ has at least one recurrent point. How can I prove that?
Definition: $x_0$ is a recurrent point under $f$ if, for any neighborhood $U$ of $x_0$, there exists $n>0$ such that $f^{n}(x_0) \in U $.
*It is known that a preserving-order diffeomorphism has irrational rotation number if and only if it has no periodic points.
**Maybe the hypothesis of preserving-order diffeomorphism is too restrict, and we only need homeomorphism.
Comment: Every continuous dynamical system on a compact metric space has a recurrent point, so it is certainly true in much more general cases.
Comment: @LukasGeyer But that is what I want to prove...
Answer: This is a corollary of a more general result, that every continuous self-map $f:X \to X$ of a (non-empty) compact metric space $X$ has a recurrent point. Here is a proof, stolen from Katok / Hasselblatt, Modern Theory of Dynamical Systems, Cambridge University Press 1995, Proposition 3.3.6 and Corollary 3.3.7.
Let $\mathcal{C}$ be the collection of all non-empty compact subsets $A \subseteq X$ with the property that $f(A) \subseteq A$, partially ordered by inclusion. If $(A_i)_{i \in \mathcal{I}}$ is a non-empty chain in $\mathcal{C}$, i.e., a totally ordered subset, then the intersection $A = \bigcap_{i \in \mathcal{I}} A_i$ is again non-empty and compact and satisfies $f(A) \subseteq A$, so $A \in \mathcal{C}$. By Zorn's lemma $\mathcal{C}$ has a minimal element $A^*$. Pick $x \in A^*$ and let $A_x$ be the closure of the forward orbit of $x$. Then $A_x \subseteq A^*$ and $A_x \in \mathcal{C}$, so $A_x = A^*$, and in particular $x$ is recurrent.

Recurrent points and rotation number


Problem in understanding the mathematical induction

Question: Suppose we have a subset of the set of natural numbers. This set includes 100  numbers that is the first 99 numbers is even and the last number is odd. now, induction can be said that the first number is even(first number mod 2 = 0)  and number n + 1 is even, and so on. consequently all  numbers are even.this is wrong because last number is odd.why is the wrong answer?
Comment: How can you do the general step?, this is, how can you show that if $n$ is even then $n+1$ is even?.
Comment: Whether induction is overall conclusion from minor conclusion ? So if, for example, 50 first numbers are even. induction can be concluded that all even.I knew from induction. Is it wrong?
Comment: Yes. If i saw a a black bird a week ago and each day from then a black bird flies over my house I may conclude by induction the fact that tomorrow a black bird will fly over my house; that's how induction in a general sense works, but mathematical induction does not work that way.
It requires to proof that if is true for $n$ also is true for $n+1$, then if $n$ is even and you proved that $n+1$ is even, putting $n=99$ tells you that the next number is necessarily even.
If there's an exception, you could not have proved that $n$ even implies $n+1$ even.
Answer: It doesn't work since you don't have the following for any number $n$ of your subset of $\mathbb{N}$:
\begin{equation}
n \text{ is even} \Rightarrow n+1 \text{ is even}.
\end{equation}
You clarify this by taking the 99th number of your subset to see that the statement is false.
Answer: The "inductive" step is to say that if something is true for $n$ then it is true for $n+1$. It's implicit here that this inductive step can performed for ALL $n$. In your example, the inductive step is that if the $n$'th number is even, then so is the $n+1$'th number. The proof of this fact for your example comes from the fact that if $n<99$ then $n+1\leq 99$ which means that the $n+1$'th number must be even by the assumptions of the problem. This does not hold for $n=99$ so the inductive step fails there.
Answer: Induction proofs consist in having a case that is true (as you did), then proof through sound facts that if one generic case is true then the next case is true as well (here is where your example fails).
Let's use the following example: every natural number (counting number) is less than 100.
We start with 0. Run the test: $0<100?$ yes! OK we now know that there's at least one case for which this is true. Let's assume that it is true for $n$. Is this true for $n+1$?
Your argument was that I look at $1,2,3,\dots$ and they so seem to satisfy the test. But this is not a sound proof. What do we know about sums an inequalities? There isn't any rule that states
$$a<b \Rightarrow a+1<b$$
Nor anything of the sort that we can take advantage of. Therefore we can't complete our proof with induction. That doesn't mean the  statementstatement is false, just that we haven't been able to prove it.
To show it is false, it suffices to find a counter example, and we have plenty of those.


How to display all media that references this taxonomy term and its immediate children?

Question: I have a hierarchical taxonomy vocabulary, "Living Things". A simplified excerpt looks like this:
Plants
--Roses
----Red Rose
----Pink Rose
--Orchids
----White Orchid
----Yellow Orchid

I have a library of media (images and videos) that have a field, "Primary Taxon", which references the appropriate term in that "Living Things" vocabulary. e.g. An image of various roses has its "Primary Taxon" field set to "Roses", and a video of a white orchid has its "Primary Taxon" field set to "White Orchid".
On my taxonomy term pages, how can I display all media that references that species, and that species' immediate children? i.e. The "Roses" page should show media that displays roses in general, as well as red roses and pink roses. The "Plants" page should show media that displays plants in general, as well as roses in general, and orchids in general, but not the individual species.
Ideally, it should also be possible to sort the view with either "this taxon first", or "children first", but I'm interested in any solution without this functionality too.
So far, I have made a view that shows all media on the taxonomy pages. However I can't find an appropriate contextual filter to limit the displayed media. Even a single contextual filter using "Media: Primary Taxon (field_primary_taxon)" stops any media from displaying.
Comment: Having kind of a déjà-vu. The matrix must have been changed. ;) -
 Please check with my answer to your question https://drupal.stackexchange.com/questions/251401/how-to-display-a-taxonomy-terms-immediate-children-on-its-page. First version. Should get you re-started...
Comment: @Mario I'm aware that I'm leaving a sad trail of very similar questions. Unfortunately, as I realise the limitations of each strategy, the question changes slightly as I try the next approach, and now I can't make the answers to those previous questions work for the exact issue described in this question. To clarify, my strategy is now to present my species info as taxonomy term pages themselves (not content nodes), and those taxonomy pages should automatically pull in the appropriate media to display. I'm using Media Entity (that is now in core as just "Media") to build my media library.
Answer: I finally worked this out, using Views (which is a way of querying the database and presenting lists of data). My design places the View as a block on my taxonomy term pages, so I refer to a block display in this method rather than a page display:
BASIC VIEW TO SHOW ALL MEDIA

Structure > Views > Add view

Enter View name and Description
Show Media of type All sorted by Unsorted
Select "Create a block"
Unformatted list of Fields
Adjust "Items per block" as appropriate (e.g. 25)
Save and edit

Scroll down and check all your Media names are listed in the Preview section, to ensure the basic View is working correctly.
FIELDS > Add > Rendered entity (Category: Media).

Here you could alternatively add fields such as Image, Video URL and File rather than the general Rendered entity.
Choose the appropriate View mode > Apply. In my case I had set up a "Preview" display mode in /admin/structure/media/manage/MyMediaType/display, with a thumbnail image format and most fields disabled.

Scroll down to check your media is listed below the names.
Click "Media: Name" > Remove, if you don't want it. It's often unnecessary for media.
Save

CONTEXTUAL FILTER TO SHOW ONLY THIS TERM'S MEDIA
Here we need to make sure that in this block we will only display media that refers to the term whose page the block will be seen on. In this case, that reference is made in a field on my media labelled "Primary Taxon".

ADVANCED > CONTEXTUAL FILTERS > Add
Select "Primary Taxon (field_primary_taxon)" (Category: Media)(or whatever your field is called) > Add and configure contextual filters
WHEN THE FILTER VALUE IS NOT AVAILABLE > Provide default value > Type: Taxonomy term ID from URL > Select (only) "Load default filter from term page" > Apply > Save. We have to supply the value this way because, unlike a page, a block does not have a URL to find the value in.
For testing, find the taxonomy term ID number ("TID") for some of the terms in your vocabulary. You can find these in the URL of the taxonomy term's page. For example my Roses page has URL .../taxonomy/term/86 so the TID is 86. If you have a module such as Pathauto providing URL aliases, then you can find the TIDs by visiting .../admin/structure/taxonomy/manage/MyVocabulary/overview, hovering over "Edit" and looking at the URL at the bottom left of your browser.
In the Preview section, test the View is filtering correctly by entering your different TIDs in the "Preview with contextual filters" box and click "Update preview". For example if I enter 86, I see only media for which I had entered "Roses" in the "Primary Taxon" field.

RELATIONSHIP & CONTEXTUAL FILTER TO SHOW CHILD MEDIA
To list media that refers to children of the term whose page that the block will be seen on, we need to find media whose parent refers to that term. This "reverse thinking" helps with understanding contextual filters; think of the relationship from the thing you're listing, not from the thing you're displaying the list on. My media has no "Parent Taxon" field; that would have been redundant because terms' parents are inherently defined in the hierarchical vocabulary they belong to. This means we can't just add "Parent Taxon" as another simple contextual filter. So we need to extend the range of database tables that Views can query by adding a relationship:

ADVANCED > RELATIONSHIP > Add > Select "Taxonomy term referenced from field_primary_taxon" (Category: Media) > Add and configure relationships > Do not select "Require this relationship" > Apply. This looks at the taxonomy term specified in the media's "Primary Taxon" field and "pulls in" that term's taxonomy information so that Views can query it with our next contextual filter:
ADVANCED > CONTEXTUAL FILTERS > Add. You will see that the list of available filters to choose from is now longer than when we chose the first contextual filter, because of the new relationship.
Select "Parent term" (Category: Taxonomy term) > Add and configure contextual filters
Same as before... WHEN THE FILTER VALUE IS NOT AVAILABLE > Provide default value > Type: Taxonomy term ID from URL > Select (only) "Load default filter from term page" > Apply.
OTHER > Query settings > Select "Contextual filters OR" > Apply > Save. This means results will be listed that pass either the 1st contextual filter OR this 2nd one. Without this, it will filter for media matching both one AND the other, and no results will be displayed.
Note that after this 2nd contextual filter has been added, the view can no longer be previewed below (I don't know why). So we need to place the block on a page...

PLACE THE BLOCK ON THE PAGE

Go to Structure > Block layout > Find appropriate theme(s) (in horizontal sub-menu at the top) and region > Place block > Find your new block > Place block > De-select "Display title" if you want...

We only want our block to show on taxonomy term pages, however in the "Visibility" section there is unfortunately no "Taxonomy term page" listed under "Content type" (I don't know why). So click "Pages" and type /taxonomy/term/* in the box > Save block > Save blocks (at the bottom). This restriction will be applied before URL aliasing, so don't worry if you have a Pathauto alias set for your taxonomy pages.
Visit an appropriate taxonomy term page to check the View works. You may need to refresh the page and/or clear all caches (at .../admin/config/development/performance), especially if you haven't disabled caching.

DISPLAY THIS TERM'S MEDIA BEFORE CHILDREN'S MEDIA
The default order of display of the media is by the "Authored on" time. To display this term's media before child term's media:

Install the Views Argument Order Sort module (there's currently only a development version).
SORT CRITERIA > Add > Select "Multi-item Argument Order" > Add and configure sort criteria > Apply > Save. This put this taxon's media before child taxa's media, whether I selected "Sort ascending" or "Sort descending".
Despite exposing this sort criterion to users to try and allow them to change the sort order, I was unable to get that working. If you know how, please comment.

FURTHER GROUP MEDIA BY TAXON
You can group the media by the term they refer to, with headings:

FIELDS > Add > Primary Taxon > Add and configure fields > Select "Exclude from display" (not necessary but you can still group by this field even if it is hidden like this) > De-select "Link label to the referenced entity" (also not essential) > Apply
FORMAT > Format > Settings > Grouping field Nr.1 > Media: Primary Taxon > Apply > Save > Test the view.

VALIDATION BUG?
In theory, validating the output of the 2 contextual filters as follows is a good idea:

Click the contextual filter > WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED > Select "Specify validation criteria" > Validator: "Media" > Select only the Media types you wish to show (or none for all of them) > Select "Validate user has access to the Media" > Apply > Save.
However, this validation prevents the view from displaying anything. Please comment if you know why, or if you think this is a bug.

IMPROVEMENT SUGGESTIONS

HEADER > Add > Result summary. This will give you a summary of results at the top of the block, as is standard on a page display.
Select ADVANCED > Other > "Use AJAX" to reduce page refreshes.
In some cases a Table view is useful, rather than unformatted list etc., because you can sort the media by field columns if you add extra fields.
You can add a "Media type" regular filter (not contextual) and expose it to visitors to allow them to show only certain type(s) of media (e.g. Images or videos or both). The Better Exposed Filters module allows the choices to be shown as checkboxes rather than as a drop-down menu, although I have a bug with it (link to follow) at the moment (version 8.x-3.0-alpha3 in Views 8.4.4).
The Views Infinite Scroll module can make for a nice improvement over standard paging if you have a lot of media.

Here is what my View looks like (with the optional Infinite Scroll and AJAX selected):

I have little Drupal experience, so feel free to suggest refinements to this method.
Comment: Thank you for the detailed answer here. I believe the "Contextual OR" setting is not available without that contributed module, as I was unable to make this work as that option is not available. https://www.drupal.org/project/views_contextual_filters_or
Comment: Could you show a screenshot please of what your content type looks like and how it's taking advantage of that field?
Comment: @blue928 I don't have a content type. I have various media types. Is that what you mean? And which "field" are you referring to?
Comment: I wonder if we're trying to accomplish similar things? I think I kinda want to do the same thing you're doing, but I want the media type field to be part of the Content Type add form as a field. Does that make sense? You may have some insight to this: https://drupal.stackexchange.com/questions/274971/when-adding-media-to-content-how-can-i-search-for-the-media-by-tag-or-term?noredirect=1#comment340736_274971
Answer: Just noting this page on drupal.org that mentions this issue, along with two links. One to a core patch and one to a contributed module.
https://www.drupal.org/forum/support/post-installation/2018-02-21/how-to-display-all-media-that-references-a-taxonomy-term


Compute variance of a power Poisson process

Question:
Let $N_t$ be a Poisson process with parameter $\lambda$. Let $X_t = (1+a)^{N_t}$. Compute
  $Var((1+a)^{N_t})$.

My attempt:
First I tried to compute the MGF, but I could not simplify it.
Then I try to compute it by definition:
$Var(X_t) = E[(1+a)^{2N_t}] - (E[(1+a)^{N_t}])^2$
I can easily compute:
$E[(1+a)^{N_t}] = e^{\lambda t a}$
But I cannot simplify the quantity:
$$E[(1+a)^{2N_t}] = \sum_{k=0}^{\infty} (1+a)^{2k} \dfrac{(\lambda t)^k e^{-\lambda t}}{k!} =e^{-\lambda t} \sum_{k=0}^{\infty} (1+a)^{2k} \dfrac{(\lambda t)^k }{k!}$$
How can I compute this sum? There must be some clever way!
Comment: $(1+a)^{2k} = ((1+a)^2)^k$. So you get $\frac{((1+a)^2(\lambda t))^k}{k!}$, which the infinite sum is just $e^{(1+a)^2(\lambda t))}$
Answer: $$\sum_{k=0}^{\infty}(1+a)^{2k}\frac{(λt)^k}{k!}=\sum_{k=0}^{\infty}\frac{\left((1+a)^2λt\right)^k}{k!}=e^{(1+a)^2λt}$$


JDK 21 - Why ThreadLocalRandom's nextInt implement with super.nextInt directly?

Question: ThreadLocalRandom in JDK 17 and above (up to JDK 21):
@Override
public int nextInt(int bound) {
  return super.nextInt(bound);
}

@Override
public int nextInt(int origin, int bound) {
  return super.nextInt(origin, bound);
}

The methods nextXXX in ThreadLocalRandom implement directly with the super's (Random's) methods. In this way, I guess the ThreadLocalRandom is not "ThreadLocal"ed any more with respect to these methods.
I also check the same methods of ThreadLocalRandom in JDK8 like:
public int nextInt(int bound) {
  if (bound <= 0)
    throw new IllegalArgumentException(BadBound);
  int r = mix32(nextSeed());
  int m = bound - 1;
  if ((bound & m) == 0) // power of two
    r &= m;
  else { // reject over-represented candidates
    for (int u = r >>> 1;
         u + m - (r = u % bound) < 0;
         u = mix32(nextSeed()) >>> 1)
      ;
  }
  return r;
}

My question is, what's the point that thosenextXXX implement with super.nextXXX() directly in JDK17 (even the first revision comes from older JDK version, which I did not justify) and above, which makes ThreadLocalRandom just a pure Random.
Comment: In JDK21 `Random.nextInt(int bound)` uses `this.next(int bits)` which is overridden by `ThreadLocalRandom`. In the version you're looking at, it uses `mix32`, which again is overridden in `ThreadLocalRandom`.
Comment: The *primary* reason I prefer `ThreadLocalRandom.current()` over some other `Random` instantiation has to do with avoiding *subtle **seeding*** issues.
Comment: @tgdavies OK, I miss the override of the method `next(int bits)`. It makes sense now that all the `nextXXX` eventually depend on the `nextSeed` firstly defined by ThreadLocalRandom!
Answer: JEP 356 proposes to unify the various random number generators. It notes that the algorithm in Random and ThreadLocalRandom are similar enough to unify them.
That the methods ThreadLocalRandom.nextInt(bound) and ThreadLocalRandom.nextInt(origin, bound) are still there is because the JavaDoc for these methods is different from the JavaDoc for Random.nextInt(bound) and Random.nextInt(origin, bound).
Internally, the methods in Random use next(int) and / or nextInt(), both of which are overriden by ThreadLocalRandom. That means even though the apparent implementation in ThreadLocalRandom disappeared a ThreadLocalRandom is still a true ThreadLocalRandom.
Comment: OK, I miss the override of the method `next(int bits)`. It makes sense now that all the `nextXXX` eventually depend on the `nextSeed` firstly defined by ThreadLocalRandom!


How to show that a given differential equation has no solution?

Question: Let $h(x)=1+x$ and $z(x)=e^x$ be two solutions of
$$y''(x)+P(x)y'+Q(x)y(x)=0$$
 Then the set of conditions for which the DE has no solution is

$y(0)=2$, $y'(0)=1$
$y(1) =0$ , $y'(1)= 1$

The answer is option 1
I have found the value of $P(x)$ and the Wronskian but I am not able to go any further. I don't know how to use these conditions to find the solution
Comment: Should your ODE be $y'' + P(x)y'(x) + Q(x)y(x) = 0$?
Comment: I'm confused by the notation.  If $h(x) = 1+x$ IS a solution, then how can $y(1)=0$ be a condition, when $h(1)=2$?  By 'solution', do you not mean functions which, when substituted for $y$, satisfy both the DE and the conditions?
Comment: @RobertLewis yes, I have edited it
Comment: @Joe I have no idea, I posted the ques as it was given in the book. The same thing confused me. I don't understand how to use these initial condition
Answer: The given solutions are largely independent, thus span the solution space. Any other solution is a linear combination of these two.
1) Note that $z(x)-h(x)=e^x-1-x=O(x^2)$, so that $x=0$ can not be a regular point of this ODE. Indeed, the vector $(y(0),y'(0))=(2,1)$ should be a linear combination of the corresponding vectors for $z$ and $h$, but both of them are $(1,1)$.
2) The phase space vectors are $(0,1)$ for $y$, which should be a linear combination of $(2,1)$ for $h$ and $(e,e)$ for $z$, which is solvable.


Generate unique non-overlapping ranges from list of ranges in PHP?

Question: Algorithm question which I seem to be having trouble wrapping my head around today if someone can point me in the right direction. It feels like something which should already be solved that I could lookup but I am having difficulty finding it.
I have some ranges and I want to get new unique non-overlapping ranges from these. For example:
My ranges
[
  [0] => [
           'Min' => 5,
           'Max' => 10
         ],
  [1] => [
           'Min' => 5,
           'Max' => 12
         ],
  [2] => [
           'Min' => 13,
           'Max' => 15
         ],
  [3] => [
           'Min' => 13,
           'Max' => 18
         ],
  [4] => [
           'Min' => 20,
           'Max' => 24
         ],
]

What I would like out is:
Note keys 2 and 4 have changed different fixing the overlapping issue.
[
  [0] => [
           'Min' => 5,
           'Max' => 10
         ],
  [1] => [
           'Min' => 11,
           'Max' => 12
         ],
  [2] => [
           'Min' => 13,
           'Max' => 15
         ],
  [3] => [
           'Min' => 16,
           'Max' => 18
         ],
  [4] => [
           'Min' => 20,
           'Max' => 24
         ],
]

Note how 19 is not there as its not a number within any of the original ranges.
I've tried searching but can't seem to think of what this kind of algorithm would be named so I am getting lots of irrelevant results.
Also notes how non of the ranges at the end overlap and contain the numbers unique (either in a min or max).
Thanks,
Comment: If you get already array of ranges then make new array with values `5,rand(5,10)` get last result and make `rand(last,new range)`, then they won't overlap, but I actually don't understand question and purposes for this)
Answer: This is how I would go about:

Order the array entries with usort. First by Min ascending, then by Max descending.
Initialize $upperLimit with 0.
Then, loop over the array and

Set Min to max($upperLimit + 1, ['Min'])
If Min is >= Max, throw away this entry
Set $upperLimit to max($upperLimit, ['Max'])
Comment: Thanks. Complete mind block on this one. Very helpful.


Scipy: Continuous Uniform Distribution's CDF

Question: Question
How can we solve the problem below with Scipy?
Background: I am preparing statictics notes in Jupyter Notebooks and trying to apply appropriate Scipy functions to some real cases.
Problem: I found a good case in lumenlerning.com and I can solve the problem with the formulas. Nevertheless, I cannot find a function in Scipy to solve this problem.
Case: A company finds out that the amount of time a repairman needs to fix a furnace is uniformly distributed between 1.5 and 4 hours. What is the probability that a randomly selected furnace repair requires more than 2 hours?
# PDF function, f(x)
1/(4-1.5) = 0.4

# probability of occurrence between 2 and 4:
(4-2) = 2

# answer
0.4 * 2 = 0.8

Snapshot of the solution:

Thank you in advance.
Comment: You don't need to find the pdf for this problem, because a simple answer comes directly from the definition of a uniform distribution: namely, the chance of an event is its length as a proportion of the total length of the domain.  Thus, all you need do is write a program to compute the length of the interval $[x, 4]$ as a fraction of the length of the interval $[1.5, 4].$ That requires only a few basic checks (to see whether $x\in[1.5,4]$), two subtractions, and a division.
Answer: Software questions are in general off-topic on this site, but there seems to be a probability problem behind your question, so let me answer it.
As about Scipy, it has nice documentation for the probability distributions and you are looking for the uniform distribution. It has rather unorthodox parameters, because instead of lower and upper bounds, it uses loc for lower bound and scale where the upper bound is loc + scale.
You geometric solution is correct, but would be hard to translate to other distributions. More generic solution would be noticing that $\Pr(l < X < u) = \Pr(X < u) - \Pr(X < l) = \int_l^u f(x) \,dx$, so you can use the cumulative distribution functions. This takes the area till $u$ and subtracts from it the left tail ending at $l$.
>>> from scipy.stats import uniform
>>> dist = uniform(loc=1.5, scale=2.5)
>>> dist.pdf(2)
0.4
>>> dist.cdf(4) - dist.cdf(2)
0.8

Comment: Extremely well described. Many thanks for your efforts! I have used sf: survival function to get the result. Still confused about scale especially.
Comment: OK. Got that;
scale = upper bound  - lower bound (loc)


Web API routing with DTO object - C#

Question: I have two projects, one is SPA and the other one is ASP.NET aspx project.
Normally those two projects communicate with each other via web API.
There is a running method like this (from SPA to ASP.NET)
<code>    [HttpPost]
    [Route("DenyInvoice/{approvalId:long}")]
    public IHttpActionResult DenyInvoice(long approvalId)
    {
        string exMsg = "";

        if (DenyInvoice(approvalId, this.UserId, this.Email, out exMsg))
            return Ok();

        return BadRequest(exMsg);
    }
</code>
This method works as I wanted, but I want to write a method that accepts a DTO variable like;
<code>    [HttpPost]
    [Route("InvoiceDetailUpdate/{invoices : invoiceDetailDtoModel}")]
    public IHttpActionResult InvoiceDetailUpdate(invoices : invoiceDetailDtoModel)
    {
        ....
    }
</code>
Is it possible? How should I do this?
Can you help?
Thank you..
Comment: What do you mean DTO object? Is that an object of a class that you have defined?
Comment: Yes, i mean a class that i defined
Answer: You want to retrieve parameter via post so there is no required for get parameter routing.
<code>[HttpPost]
[Route("InvoiceDetailUpdate")]
public IHttpActionResult InvoiceDetailUpdate(InvoiceDetailDtoModel invoices)
{
    ....
}
</code>
Also, be careful with the name convention of a class.
Answer: Use <code>[FromBody]</code> to pass in the POST parameter. See https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api#implement-the-other-crud-operations for more details.
<code>[HttpPost]
[Route("InvoiceDetailUpdate")]
public IHttpActionResult InvoiceDetailUpdate([FromBody]InvoiceDetailDtoModel invoices)
{
    ....
}
</code>
Answer: In the following code, you can use like this :
<code>  public class BooksController : ApiController
{
    [Route("api/books")]
    public IEnumerable<Book> GetBooks() { ... }

    [Route("api/books/{id:int}")]
    public Book GetBook(int id) { ... }

    [Route("api/books")]
    [HttpPost]
    public HttpResponseMessage CreateBook(Book book) { ... }
}
</code>
Now , you can see this link attribute-routing-in-web-api-2
and change your code to above figure
<code>  [Route("api/YourController/InvoiceDetails")]
 public IHttpActionResult InvoiceDetailUpdate(InvoiceDetails invoiceDetailsDto)
</code>

Web API routing with DTO object - C#


Geometric Progression related question.

Question: In a sequence, first term a1 = 100 and nth term, an = 100 + (an-1)/5 If for some integer k, a50 lies between k and (k + 1), then k =
Answer: Let's check the first 3 terms:
$a_1 = 100$
$a_2 = 100 + 100/5 = 120$
$a_3 = 100 + 100/5 + 100/25 = 124$
I don't see how this is an arithmetic progression. It's more like a geometric series:
$a_n = \sum_{i=0}^{n-1} 100*(1/5)^i$
This allows a simple geometric series formula. Can you solve it from here?

Geometric Progression related question.


multisite: only changing name of the website

Question: I have a multisite up and running, which has completely different domain names but absolutely the same content (I'm using filters to filter the content by domain).
Everything works splendid with almost no redundancy. However, the only thing keeping me from rejoicing, is that I cannot change the name of the website domain-wise.
So basically, my question is where I can set this up, or rather:
Is there a way to override the page's name on drupal load?
And if there's not, can anyone tell me which table the site's name is getting stored, so I can domain-prefix it?
Answer: Do you have a settings.php file per site ?
If yes, you can add inside $conf['site_title'] = 'My Site name' this variable his stocked in the table variablebut you can override it directly with settings.php.


HTML Navigation Bar, fixed at the top of webpage, horizontal boxes(buttons)

Question: I am trying to get a navbar to show at the top of a webpage, have horizontal buttons inside of a clean box.  Very similar look to the navbar found at http://www.apple.com/.  I feel as if I should know how to do this, but apparently I do not.  Any help is very appreciated, or even points and tips.  Thank you and below is the code I have so far.
Css is shown first, and then my HTML.

body{
  border: solid;
  background-color: white;
  color: black;
  text-align: center;
}

table.slideshow{

}
th.slideshowtitle{
  text-align: center;

}

footer{
  border-top: solid 10px;

}

/*nav bar*/
.navbar-inverse {
  background-color:black;
}
<!DOCTYPE html>

  <link href="C:\Users\Chester Szydlowski\Desktop\HOF\stylesheet.css" type="text/css" rel= "stylesheet" />
<title>
  Hall Of Framers
</title>

           <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">

           </button>

          <u1 class="nav navbar-nav">

Home

Email List

Custom Frames

News

Silent Auction

Upcoming and Past Events

i dont know

        </u1>

 Products

Comment: do you have 'position: fixed;' in your css, or is that the only css that I see above? and where is your javascript?
Answer: If you add a display css selector to the "li" elements, it will do the trick
Add the following to your css.
  li{
     display:inline-block;
   }

This will move the elements next to eachother, and you can style it further from there. Good luck
Comment: No Problem! Let me know if you need any further styling assistance.
Answer: It looks like your nav is using boostrap classes. If so, just download and include boostrap.css.
Comment: I will look into this as I am unfamiliar with bootstrap classes, thank you!


Using page's angular JS in chrome extension

Question: I've a HTML page which has some DOM configured with Angular. Now I'm building a chrome extension to modifying value in a text box. element.value= newValue will not work as the text box is designed with Angular. After reading some resources, I came to know that I need to do the changes to the scope of the element. I tried doing this in the extension.
var eleScope = window.angular.element(document.querySelector('.textbox')).scope();
eleScope.$apply(function() {
  eleScope.item.request.box = newValue;
});

This doesn't seem to work as intended. When I dug into the problem more deeply, I came to know that the angular in the scope of window was not getting the right scope.
I also tried to inject angular.js from my extension and using angular.element directly which also doesn't seem to solve the problem.
Am I missing something. Appreciate your replies.
Answer: Hmm.. Actually you should be just able to change the value using vanilla Javascript or JQuery and should not need to update the scope as it is two-way binding ie. Updating the view updates the model and vice-versa.
The only reason why the model does not update is because the watchers to update the model trigger only on particular events like "click" or "input".
So the solution here would be to manually trigger these events.
This can be do by:
// the selector used is based on your example.
var elementTOUpdate = $('.textbox');
input.val('new-value');
input.trigger('input');

The last statement will trigger all the handlers on the element for the "input" event ( which will fire the angular watchers ) and update the scope.
More info on the trigger function:
http://api.jquery.com/trigger/
Answer: Although your web page and your Chrome extension's content script share the same DOM, they have separate JS execution contexts. In other words, despite grabbing the element via angular.element().scope() in your Chrome extension, you're still not accessing the correct scope object. (See the Chrome dev docs for more on this.)
In order to get the modified data from your Chrome extension on to the page, you can either manipulate the DOM via your content script, or take some extra steps to get the modified data into the web page's execution context (and subsequently, into your controller's scope).
For the latter, the solution is to use the Chrome's Message Passing API; specifically, the API designed to communicate between the web page and the Chrome extension (see here).
Here's an example from the documentation:
First, enable the API for the appropriate website(s) in your manifest.json file:
"externally_connectable": {
  "matches": ["http://*.foo.com/*"]
}

From the web page, make a request to connect to the Chrome extension. In your callback, you'd update your model:
// Chrome extension's ID
var extensionId = "abcdefghijklmnoabcdefhijklmnoabc";

chrome.runtime.sendMessage(extensionId, {foo: 'bar'},
  function(response) {
    if (response.success) {
      $scope.myData.foo = response.data;
      $scope.$apply();
    }
  });

In your Chrome extension's background.js file, add a listener for the request:
chrome.runtime.onMessageExternal.addListener(
  function(request, sender, sendResponse) {
    if (request.foo) {
      sendResponse({ data: 'modified data goes here' });
    }
  });

This process will allow your Chrome extension to send data into the correct execution environment, allowing your AngularJS app to work with it.
Answer: The main problem is well explained in Jonathan Guerrera's answer: you can't just load Angular in your extension and expect it to work because it's a different instance of Angular; the real one is in another JS context.

Another possible (though hacky) solution is to inject code into the page's context. That way, you're actually manipulating the page's own Angular.
It can be combined with other methods of communicating between the page-level script and the content script.


Bounded linear operator maps norm-bounded, closed sets to closed sets. Implies closed range?

Question: Question
Suppose $T:X\rightarrow Y$ is a continuous, injective linear operator between Banach spaces. Suppose, in addition, that $T$ maps norm bounded closed sets in $X$ to closed sets in $Y$. Then the range of $T$ is closed in $Y$.
This is a problem related to one given An Invitation to Operator Theory by Abramovich and Aliprantis and I'd just like to verify my proof.
Attempt
We assume that $T$ is as above, and we shall prove that it has closed range. If $y_n = T x_n$ and $y_n\rightarrow y$, we want to show that $y=Tx$ for some $x\in X$. First, suppose $\{x_n\}_{n\geq 1}$ is unbounded. Then
$$\lim_n\, T(x_n/\|x_n\|) = \lim_n\, y_n/\|x_n\| = 0.$$
But the set $B=\{ x\in X: \| x\|=1\}$ is closed and norm-bounded, so its image under $T$ is closed. In particular, we must have $Tz=0$ for some $z\in B$. This contradicts the fact that $T$ is injective. So the sequence $\{x_n\}_{n\geq 1}$ is bounded in $X$. Since $\{x_n\}_{n\geq 1}$ is bounded, the set
$$ A=\mathrm{cl} \{ x_1, x_2, \ldots, x_n, \ldots \}$$
is closed and norm bounded. Hence $T(A)$ is closed in $Y$. In particular, $y=\lim_n\, Tx_n = Tx$ for some $x\in A \subset X$. So the range of $T$ is closed.
Thanks in advance!
Comment: Looks good to me.
Answer: Your proof looks good.
Here's another possible line you could follow.

Lemma. Suppose $X,Y$ are Banach spaces, $T : X \to Y$ is continuous and injective.  Then the range of $T$ is closed if and only if there is a constant $c > 0$ such that $\|Tx\| \ge c\|x\|$ for all $x\in X$ (we say such $T$ is bounded below).

Proof.  For the forward direction, use the open mapping theorem.  (But we don't actually need the forward direction for this problem).  For the reverse direction, if $T$ is bounded below then $T^{-1}$ is bounded.  So $TX = (T^{-1})^{-1} X$ is closed, being the preimage of a closed set under a continuous map.
Now for the problem: let $S$ be the unit sphere of $X$.  By assumption $TS$ is closed, and by the injectivity of $T$ it does not contain 0.  Hence its complement contains an open ball of some radius $c$ about 0.  This means that $\|Tx\| \ge c\|x\|$ for all $x \in S$, and by linearity the same holds for all $x \in X$.  So $T$ is bounded below, and by our lemma it has closed range.
Comment: Thanks Nate. I actually wanted to prove a certain injective operator was bounded below -- hence my interest in the closedness of its range. The lemma I posted was particularly straightforward to prove for my operator, so I just wanted to check my tracks!
Comment: Hi Nate. For the forward direction in your Lemma, how do you show that if the range of T is closed, then T is bounded below "without" using the open mapping theorem?
Comment: @Dejon: The forward direction essentially *is* the open mapping theorem; you can't avoid it unless you re-prove it.  But what I meant was that we don't need the forward direction of my lemma to prove the statement in the question, only the reverse direction.
Comment: @NateEldredge : I think there is some confusion for the reverse direction ; as $T$ is injective , $T^{-1}$ is defined ( i.e. its domain ) on range of $T$ i.e. $T(X)$ ; and then $T(X)=(T^{-1})^{-1}(X) $  would obviously be closed in $T(X)$ itself ... still I can prove that if $T$ is bounded from below and $X$ is Banach , then $T(X)$ is closed in $Y$ ( though the proof is considerably different than working with just inverse images )
Comment: Since T is continuous and if we view it as an operator from X to ranT it is surjective, then by the open mapping theorem it is open. And as a bijection it is thus closed. So it is naturally bounded below thus ranT is closed. Is my statement right or which step goes wrong? Thanks!
Comment: @Greywhite: The open mapping theorem only applies to maps between Banach spaces.  So in order to apply it, you would need for ran T to be a Banach space, which only happens if it is a closed subspace of Y.  Hence your argument is circular.  (Indeed, your argument would appear to prove that every injective continuous linear map between Banach spaces has closed range, which is certainly not true.)
Answer: You are assuming that $(x_{n})$ unbounded implies $\left(\frac{1}{\|x_{n}\|}\right)$ goes to $0$, so that you can then conclude $\lim_{n\to\infty}\frac{y_{n}}{\|x_{n}\|}=0$.
This is not necessarily true.
For example, the sequence $(x_{n})$ in $\mathbb{R}$ given by $x_{n}=\begin{cases}n & \mbox{if }n\mbox{ is even}\\1 & \mbox{if }n\mbox{ is odd}\end{cases}$ is unbounded.
However, $\frac{1}{\|x_{n}\|}=\begin{cases}\frac{1}{n} & \mbox{if }n\mbox{ is even}\\1 & \mbox{if }n\mbox{ is odd}\end{cases}$ does not converge.
Fortunately, $\left(\frac{1}{\|x_{n}\|}\right)$ does contain a subsequence converging to $0$. So you can get around the problem with a minor change to your proof:
Assume $(x_{n})$ is not bounded. Then there is a subsequence $(x_{n_{k}})$ of $(x_{n})$ such that $x_{n_{k}}\not=0$ for all $k$ and $\lim_{k\to\infty}\|x_{n_{k}}\|=\infty$.
Then $\lim_{k\to\infty}\frac{y_{n_{k}}}{\|x_{n_{k}}\|}=0$.


Any tips on how to get nord piano 3 to sound better?

Question: 1

2 http://www.mediafire.com/file/l7oqhcb2yl2hbsb/2018-07-28_13-01-14.mp3/file
using two ts cable, effects are turned off and it is raw non-edited recording.
first one was recorded using obs to record video plus audio while the second one was recorded in audition (I don't know why there is so much reverb in the audition recording
both audio are recorded in 320kbps and in stereo
I'm looking to get this kind of sound

Comment: I don't think this is a problem with your cables. You need to find a brighter sounding piano patch than the miserable thing you used in your two demos. Also, you need to teach your left hand to play more softly - and in fact your touch is pretty uneven for both hands, which results in random notes "sticking out as too loud" for no musical reason.
Comment: the thing is I don't know which sample is best for recording
Comment: Just keep trying  different ones till you find one that sounds like the guy you want to imitate! Real pianos don't all sound the same. Anybody familiar with them can easily recognize the sound of a Yamaha, Steinway, Bosendorfer, etc, etc by ear - they are as different as chalk and cheese. (And actually, no two concert grands made by the *same* company have ever sounded *exactly* alike - professionals might try 20 or 30 pianos of the same brand before  they decide which one they like "best".
Comment: Hey so I noticed something. so my speakers creative gigaworks t20 series II) and guitar amp (both under 100) sound pretty bad. worse than my headphone at least. I was doing some recording in obs and audacity so far audacity sounds best so I have to figure out how to edit. the headphone sounded way better in the recordings and when I switch to the speakers (creative) it clips so much even when I'm not playing loudly.
Comment: how does it sound on your end? you prolly have much better speakers and headphones than i have
Answer: There is no best sample for recording, you are just using a different sample from the one used in the video you want to emulate. Check here:
http://www.nordkeyboards.com/sound-libraries/nord-piano-library/grand-pianos/royal-grand-3d
Listen to the sound demos. When you find the one you want, make sure you download the version with "XL" in the file name - that will have the highest quality. Use the Nord sample management software and a USB cable to load the sample into your piano - unless you already have it. If you already have, just select it.
You might have to read the manuals that came with the Nord (also available on their web site) to learn to select and/or download the sample that sounds like the sound you want.


How to display an attribute of a related model when using collection_select in Rails

Question: I Have a MTI set up with a Client inheriting from Person. I also have a Project which is in one-to-one relationship with Client model . In my view project/new.html.erb  I would like to create a dropdown menu with client names available for selection.
<%= f.collection_select(:client_id, Client.all, :id, :XXX, {include_blank: true, :data => {:placeholder => "Select a client"}}, {:class => "chosen-select", :tabindex => "-1", :style => "width:350px;", }) %>

The XXX normally is a symbol that signifies the attribute of the direct model ( in this case Client).
How can I display a name attribute which is actually an attribute of a Person class?
UPDATE
I added a person_name method to my Client class
class Client < ActiveRecord::Base
  has_many :projects
  has_one :person, as: :profile, dependent: :destroy
  attr_accessible :person_attributes, :pref_hours_of_contact, :pref_method_of_contact
  accepts_nested_attributes_for :person

  def person_name
    person.name
  end
end

I have also amended the view:
<%= f.collection_select(:client_id, Client.all, :id, :person_name, {include_blank: true, :data => {:placeholder => "Select client"}}, {:class => "chosen-select", :tabindex => "-1", :style => "width:350px;", }) %>

Answer: I haven't tried, but I believe you can have a method in the Client class that will output the Person attribute. I will assume you want to get a Person name:
Notice what it is said in the documentation for collection_select:

The :value_method and :text_method parameters are methods to be called
  on each member of collection

So, if you can send a method to the Client object that will retrieve the Person attribute, you are good to go. This really depends on how you have defined the MTI, but at the end of the day you can always have this in your Client class:
def person_name
  # Access your super attribute
end

So you could do:
<%= f.collection_select(:client_id, Client.all, :id, :person_name, {include_blank: true, :data => {:placeholder => "Select a client"}}, {:class => "chosen-select", :tabindex => "-1", :style => "width:350px;", }) %>

If you were to use the act_as gem you could directly use your Person object in the Client collection_select.
<%= f.collection_select(:client_id, Client.all, :id, :name, {include_blank: true, :data => {:placeholder => "Select a client"}}, {:class => "chosen-select", :tabindex => "-1", :style => "width:350px;", }) %>


Is there a good graphical/pseudographical/web-based tool for managing Linux users and groups?

Question: Is there a good graphical/pseudographical/web-based tool for managing Linux users and groups?
To see them all at once, operate them (create, remove, associate (add/remove users to groups), modify) with couple of clicks?
Answer: Webmin is generally considered to be pretty good at that and is probably already part of whatever distro you use.
If you look at their screenshot page, you can actually see some screenshots of creating and managing users.


Protocol defining singleton with properties

Question: I have the following protocol that defines a singleton with property:
protocol SingletonProtocol {
    static var shared: SingletonProtocol { get }
    var variable : Int { get set }
}

And the following class that implements this protocol:
class Singleton : SingletonProtocol{
    static let shared : SingletonProtocol = Singleton()
    var variable = 4
}

If I call:
Singleton.shared.variable = 5

I get the following error:
 change 'let' to 'var' to make it mutable

If I implement this class without the protocol I don't get the error and the variable can be changed. I can solve this by adding setVariable: method but I want to access and modify the variable directly.
How can I write a protocol that defines a singleton with variables that can be modified?
Comment: You can't really ensure that a conforming type only has a singleton instance, since for that you'd need to declare a private initializer in your class, which you can do, but you can't declare it in `SingletonProtocol`, so a class can conform to your protocol without having only a singleton instance. With your current implementation, it is possible to instantiate any number of `Singleton` instances.
Comment: Thank you @DávidPásztor for this comment, is there a way for a protocol to "enforce" private init in its comforting protocols.
Comment: Sadly no, you can't mark protocol methods as private.
Comment: You can set it like `var shared = Singleton.shared
 shared.variable = 5`
Comment: I'm curious, why do you need a protocol here? What other types would conform to `SingletonProtocol`?
Comment: I want to unitest a singleton class using dependency injection and for that I need a variable in the protocol with the type of an other protocol to set as a mock in the testing.
Answer: Make the protocol available only for classes (struct won't be able to conform to this protocol):
protocol SingletonProtocol: AnyObject {
    static var shared: SingletonProtocol { get }
    var variable: Int { get set }
}

Now you can set the shared property as a let
class Singleton: SingletonProtocol {
    static let shared: SingletonProtocol = Singleton()
    var variable: Int = 0
}

Comment: I'm testing in Playground and it works good for me, swift 4.1
Comment: In your class, don't forget to make your init private
Comment: 1) with private set I get the error "cannot assign to property: 'shared' setter is inaccessible"

2) how does making it only for classes help me?
Comment: Sorry, my mistake; that problem is about struct, which are value-types; I changed answer. If a protocol is only for classes, it means that only reference-types can conform to it; a reference type can be immutable even if its members aren't. So now you can use let instead of var
Comment: If I do, the class will not be a singleton anymore, shared must be immutable.
Comment: If you do this, in the class you can declare shared as let, so it's immutable
Comment: And back to the original problem, if I try to do Singleton.shared.variable = 2 I get the error '"change 'let' to 'var' to make it mutable"
Answer: Change
static let shared : SingletonProtocol = Singleton()

to
static var shared : SingletonProtocol = Singleton()
private init() {}

Comment: If you add `private init() {}` there shouldn't be much potential left for more than a single instance.
Comment: If I do, the class will not be a singleton anymore, shared must be immutable.
Comment: How can a var remains immutable?
Comment: Good point. However, how would you change it in the case above once it has been initially set?
Answer: In your singleton class change the variable declaration from let to var. so that will be same as in protocol's declaration.
class Singleton : SingletonProtocol{
    static var shared : SingletonProtocol = Singleton()
    var variable = 4
}

EDIT:
also add only getter for sharedInstance in protocol declaration to serve purpose of singleton class as:
protocol SingletonProtocol: AnyObject {
    static var shared: SingletonProtocol { get }
    var variable: Int { get set }
}

Comment: If I do, the class will not be a singleton anymore, shared must be immutable.
Comment: @amir check the tom's comment above, same can be applicable here.
Comment: yes but I still want shared to be let because it is the correct way of writing singleton, so the correct solution is Rico Crescenzio's