Chrome extension options

Question: In the manifest.json of my extension, I added this:
  "options_ui": {
      "page": "options.html",
      "chrome_style": true
  },

My options page (options.html) has this right before the closing body tag:

Both options.html and options.js are in the same folder.
options.js starts with this:
console.log('options.js');

Problem: I am loading the unpacked extension (developer mode enabled). My options page is showing fine, but the script is not loaded. I have defined event handlers in that file, and they do nothing.
options.js is not executed.
I followed all the instructions here, but it just does not work.
Answer: It turns out that the new options_ui does log things to the console, just not the console you're looking at with "View" "Javascript Console".  Instead, right click on the option page that opens, and "Inspect Element".  That will bring up the correct "Developer Menu".
Answer: the new "chrome_style" options actually don't show anything logged to the console trough console.log, your script is probably fine, try adding something to the dom.
Add this at the beginning of your script to see any errors happening in your chrome options page:
var errorText = document.createElement("div");
document.body.appendChild(errorText)
window.onerror = function (msg, file, line, column) {
  errorText.innerHTML = msg + '
' + file + ' ' + line + ':' + column;
}

EDIT:
Right click inside the Options UI, select "Inspect element", it will open the appropriate debugger.
Comment: I don't think your first paragraph is correct.  It appears you can right click to bring up the appropriate console.
Comment: Hmm, okay. I did what you told me and see it is loaded. So now I need to find out why the event handlers are not working...
Comment: Yes options page development is tricky as you can't debug the code ether, see my updated answer for a script you can use.
Comment: Thank you. That was very helpful. I found out that there was a 'Uncaught TypeError: Cannot read property 'sync' of undefined' error. I had to set the storage permission for the extension.

Chrome extension options


How to import url of the nodes via feeds

Question: When I use url field in feeds import the url does not get imported for some reason
Answer: IIRC because the link field is multiple fields (title, link, description, etc.) you need to map it to the correct one, from quick google searching it seems the Link module dev version has a migrate file in it for this.


RavenDb: Why filtering while string == null filters too much?

Question: I want to filter the EquipmentEntity list by Type if it is specified (different from null). The type is a nullable string.
Request:
public class GetEquipmentsQuery : IQuery<List<EquipmentDto>> {
    public string? Name { get; set; }
    public double? Price { get; set; }
    public string? Type { get; set; }

}

Filtering:
var equipments = await session
.Query<EquipmentEntity>()
.Where(a => (request.Type == null || a.Type == request.Type))
.ToListAsync(cancellationToken);

If the Type property equals null, equipments is an empty list. If the Type property has a value and there is an EquipmentEntity whose Type property has that value, it is included in the list of returned elements.
I have a problem with that condition:
var equipments = await session
.Query<EquipmentEntity>()
.Where(a => request.Type == null)
.ToListAsync(cancellationToken);

I tested how the filtering works with a simplified condition. Although request.Type == null is true, them for some reason equipments is empty.
I do not have this problem with very similar filtering:
var equipments = await session
.Query<EquipmentEntity>()
.Where(a => (request.Price == null || a.Price <= request.Price))
.ToListAsync(cancellationToken);

In this case, if Price property equals null it does not affect the filtering and receives a proper list. The only difference I notice here is that Price property is a nullable double and Type property is a nullable string.
How can I make Where so that it filters correctly when the given Type property from the request is null?
Comment: What happens when you try `request.Type == ""` in your second query?
Comment: Will the following help ?
**Filter by non-existing field** : https://ravendb.net/docs/article-page/6.0/csharp/client-api/session/querying/how-to-filter-by-non-existing-field
**Filter by field presence**: https://ravendb.net/docs/article-page/6.0/csharp/client-api/session/querying/how-to-filter-by-field
Comment: @GoodNightNerdPride The same, if  `request.Type == ""`, equipments is an empty list.
Comment: @Danielle My field has already existed in database
Answer: For now, this is working for me:
        using var session = _context.Store.OpenAsyncSession();

        var query = session.Query<EquipmentEntity>();
        if (request.Name != null) {
            query = query.Search(a => a.Name, $"*{request.Name}*");
        }

        if (request.Price != null) {
            query = query.Where(a => a.Price <= request.Price);
        }

        if (request.Type != null) {
            query = query.Where(a => a.Type == request.Type);
        }

        var equipments= await query.ToListAsync(cancellationToken);

        return _mapper.Map<List<EquipmentDto>>(equipments);

I only add further filters when I know that a request field is different from null. This avoids the problem of filter Where(a => (request.Type == null || a.Type == request.Type)) because aligning to a specific value filters the list as expected.
However, this is a workaround and I would like to understand why previous approach return empty list.


Views: Use like operator in exposed search filter (Search: Search Terms)

Question: In a view, I am using an exposed filter of keyword search (Search: Search Terms). The default behavior of the filter is to select exact matches. I need to have similar words also selected. For instance when the visitor searches for "paint", she should see "painting" or "painter" too.
Similar to the "LIKE" operator in mysql.
Answer: When you set a new filter in views on a field (for example node title), you can set the Operator to contains which is the equivalent of SQL LIKE.
You can also expose the filter and the operator to the visitor.
If you want to see the SQL query in the preview, check the option Show the SQL query in view setting.
Instead of Search: Search Terms, use Global: Combine fields filter; it will allow you to search multiple fields using the operator you want.


how to add menu item from tags?

Question: I am new in Drupal,
and I am creating  a library the library has subject, each subject select from a list that referenced to a taxonomy.

I want each subject become an item in my menu and when click on it
  show that tag result.
Comment: Do you want taxonomy terms from a vocabulary to show in the main menu? In that case check out https://www.drupal.org/project/taxonomy_menu. Or do you mean that all nodes of the type library should be in the menu?
Comment: Alright, have a look at https://www.drupal.org/project/taxonomy_menu
Comment: just a vocablery
Answer: I'll post my comment here as an answer also so this question can be closed.
If you want a taxonomy vocabulary and it's terms to be represented in a menu you can use the module Taxonomy menu. It synchronizes changes in your taxonomy tree to a menu of your choice.

Transforms your taxonomy vocabularies into menus with ease!

how to add menu item from tags?


Why I can't reduce an integral divided by another integral?

Question: For example,
$$
\frac{\int_{0}^{1}f(x)dx}{\int_{0}^{1}dx} = \int_{0}^{1}f(x),  \space\space\space  (1)
$$
The dx disappears since
$$
\frac{\int_{0}^{1}f(x)dx}{\int_{0}^{1}dx} = \lim_{N\to\infty}\left(\sum_{k=0}^{k\to N}{\frac{f(\frac{k}{N})\frac{1}{N}}{1\times \frac{1}{N}}}\right) = \lim_{N\to\infty}\left(\sum_{k=0}^{k\to N}{\frac{f(\frac{k}{N})}{1}}\right), dx = \Delta x = \frac{1}{N}  \space\space\space  (2)
$$
Above (2) is from the definition of the integral,
Can I do this reduction? If NOT, why?
Comment: The identity $\int f/g= \int f / \int g$ is very untrue. All you did was rewrote $1$ as an integral so it's more like a trivial case where it holds.
Answer: You cannot, since you're basically assuming
$$\frac{ \sum_i f(i) }{ \sum_i g(i) } = \sum_i \frac{f(i)}{g(i)}$$
This is not true in general. You're assuming this because each integral is basically its own, individual (limit of a) sum. For instance, it is generally not true that
$$\frac{a+b}{c+d} = \frac a c + \frac b d$$
It is also generally untrue that $\int f / \int g = \int (f/g)$ as a result.
Answer: No, and for several reasons:

$\int_0^1 f(x)$ is not a thing. The operation is $\int_a^b(\bullet)\,dx$: it takes functions and it returns numbers.
$\frac{\int_0^1 f(x)\,dx}{\int_0^1 g(x)\,dx}=\frac{\lim_{n\to\infty}\sum_{k=0}^{n-1}f(k/n)\frac1n}{\lim_{n\to\infty}\sum_{k=0}^{n-1}g(k/n)\frac1n}$. If both terms converge and the denominator converges to a non-zero number, then this limit is equal to $\lim_{n\to\infty}\frac{\sum_{k=0}^{n-1}f(k/n)\frac1n}{\sum_{k=0}^{n-1}g(k/n)\frac1n}$. Claiming this limit to be equal to $\lim_{n\to\infty}\sum_{k=0}^{n-1}\frac{f(k/n)}{g(k/n)}$ is basically the same fallacy as claiming that $\frac{x+y}{z+w}=\frac xy+\frac zw$, which is of course false.


How to create .jl file in IJulia

Question: I am very new to julia. I have just installed ipython and Ijulia. But every time I saved my file from ipython notebook, the format of the saved file is always .ipynb. I don't know if I can saved my file as .jl file. Or could anyone tell me how to create .jl file through ipython notebook. I have googled but seems like no one talks about it.
Comment: I am not sure about IJulia but in IPython you can save a notebook in code format (.py) - the option should be somwhere in file drop-down menu. `nbconvert` may also help you.
Answer: .ipynb is the JSON-based Jupyter notebook format, with conventions for storing code cells and associated metadata and data (such as inline images). Jupyter is designed as a fully-integrated interactive environment, not "just" a text editor, and as such the file format requires extra information. To create a .jl file, use a text editor or an ide such as Juno.

How to create .jl file in IJulia


Docker mssql container exits immediately when Docker starts, but not when started manually

Question: I have a MSSQL 2017 Docker container created using Docker Compose with this file:
version: "3"
services:
  mssql-server:
    image: mcr.microsoft.com/mssql/server:2017-latest
    environment:
      ACCEPT_EULA: "Y"
      SA_PASSWORD: "*****"
    ports:
      - "2017:1433"
    container_name: test-mssql

Whenever Docker Desktop for Windows starts, the container starts and then immediately exits. The logs only contain 2 lines:

2019-01-18 16:56:43.02 spid6s      Always On: The availability replica manager is going offline because SQL Server is shutting down. This is an informational message only. No user action is required.
2019-01-18 16:56:43.05 spid6s      SQL Server is terminating in response to a 'stop' request from Service Control Manager. This is an informational message only. No user action is required.

But if I start the container manually by running docker start test-mssql the container starts and stays running like I expect it to.
Answer: This issue related mssql password policy not match, Now try with password like :

Must be at least 8 characters long
Must contain at least 1 numeric character,
1 lowercase character,
1 uppercase character, and 1 special (nonalphanumeric) character.

Then try to run docker-compose up -d mssql-server
Comment: Mayur is correct. I tried simplifying the pw compared to the usage guide I'd seen. That cost me some time debugging wth was going on


integration by parts

Question: !!!!  PD: I did a little change in the denominator  !!!!
I need to solve this integral using integration by parts.
$\displaystyle\int\frac{x\,dx}{\sqrt{(a^2+b^2)+(x-c)^2}}$
Thanks!
PS: I know that I can to do:
$\displaystyle\int\frac{x\,dx}{\sqrt{(a^2+b^2)+(x-c)^2}}=\int\frac{(x-c)\,dx}{\sqrt{(a^2+b^2)+(x-c)^2}}+c\int\frac{dx}{\sqrt{(a^2+b^2)+(x-c)^2}}$
but according to the book it is easier using integration by part.
Comment: What does "PD" mean?  The change in the denominator doesn't affect the problem.  Whether it's $a^2+b^2$ or $(a^2+b^2)^2$, it's just a positive number, which you could call $k^2$ if it makes your life easier. (I guess you want to handle $a=b=0$ separately.)
Comment: That looks like a trig substitution.
Comment: Using the idea in "PS" is easy using trig substitution, but I need use integration by parts. According to the book is the easier way.
Comment: Consider the possibility that the book is wrong. Not that it necessarily means much, but I don't see how integration by parts would make it easier.
Comment: sorry. I did a little change in the denominator.
Comment: PD = P.D.: post data (just to emphasize that the change was after sending the message).
Comment: Thats true Jonas :)
Comment: Simplify everything by letting $a^2+b^2 = k$
Answer: Let $x-c=\sqrt{a^2+b^2} \tan \theta,$ then $d x=\sqrt{a^2+b^2} \sec ^2 \theta d \theta$ and
$$
\begin{aligned}
\int \frac{x d x}{\sqrt{\left(a^2+b^2\right)+(x-c)^2}} &=\int \frac{c+\sqrt{a^2+b^2 \tan \theta}}{\sqrt{a^2+b^2 \sec \theta}} \sqrt{a^2+b^2 \sec ^2 \theta} d \theta\\
&=\int\left(c+\sqrt{a^2+b^2} \tan \theta\right) \sec \theta d \theta \\
&=c \ln |\sec \theta+\tan \theta|+\sqrt{a^2+b^2} \sec \theta+C\\
&=c \ln \left|\frac{x-c+\sqrt{a^2+b^2+(x-c)^2}}{\sqrt{a^2+b^2}}\right|+\sqrt{a^2+b^2+(x-c)^2}+C
\end{aligned}
$$
Answer: You don't actually need integration by parts. First, observe the following:
$$\left[\sqrt{a^2+b^2+(x-c)^2}\right]'=\frac {x-c}{\sqrt{a^2+b^2+(x-c)^2}}$$
Integrating both sides and isolating the integral under question gives
$$\int\frac x{\sqrt{a^2+b^2+(x-c)^2}}\,\mathrm dx=\sqrt{a^2+b^2+(x-c)^2}+c\int\frac {\mathrm dx}{\sqrt{a^2+b^2+(x-c)^2}}$$
The latter integral can be evaluated using an Euler Substitution. A more detailed explanation of how to perform an Euler Substitution can be found on the Wikipedia page, but the substitution to make here is
$$t=x-c+\sqrt{a^2+b^2+(x-c)^2}$$
Differentiating gives
\begin{align*}
\mathrm dt & =1+\frac {x-c}{\sqrt{a^2+b^2+(x-c)^2}}\,\mathrm dx\\ & =\frac {x-c+\sqrt{a^2+b^2+(x-c)^2}}{\sqrt{a^2+b^2+(x-c)^2}}\,\mathrm dx\\ & =\frac t{\sqrt{a^2+b^2+(x-c)^2}}\,\mathrm dx
\end{align*}
As in
$$\frac {\mathrm dt}t=\frac {\mathrm dx}{\sqrt{a^2+b^2+(x-c)^2}}$$
The integral is then
\begin{align*}
 & \int\frac x{\sqrt{a^2+b^2+(x-c)^2}}\,\mathrm dx\\ & =\sqrt{a^2+b^2+(x-c)^2}+c\int\frac {\mathrm dt}t\\ & =\sqrt{a^2+b^2+(x-c)^2}+c\log\left(x-c+\sqrt{a^2+b^2+(x-c)^2}\right)+K
\end{align*}

integration by parts


Construct a sentence in the empty language.

Question: Consider the following exercise, taken from my course book on model and proof theory:

Let L be the empty language, so an L-structure is "just" a nonempty
  set M. Express by means of an L-sentence that M has exactly 4 elements.

I'm not entirely sure how to approach this; somehow, I have to use only variables and the standard logical symbols to "force" the underlying set to be of size four. It seems like it shouldn't be too hard, but I still lack intuition on how to construct such sentences. Any help is appreciated!
Comment: Try to write "there are 4 elements and every $x$ is equal to one of those 4"
Comment: You have no constant, functions and predicate symbols, but you have the logical symbols and "$=$" is (usually) treated as a logical symbol.
Comment: @Manlio So, something like $\exists a\exists b\exists c\exists d\forall x(x=a\vee x=b\vee x=c\vee x=d)$? But that doesn't seem to include unicity. So then I suppose I could replace $x=a$ with $(x=a\wedge\neg(x=b)\wedge\neg(x=c)\wedge\neg(x=d))$, and similarily with the other equalities. However... this seems like such a long sentence to express something so simple. I suppose it's alright if what I said is correct, but, could there be a "simpler" way of writing it?
Answer: Perhaps the simplest way of expressing that $M$ has exactly four elements is
$$\exists a\exists b\exists c\exists d[\neg(a=b\lor a=c\lor a=d\lor b=c\lor b=d\lor c=d)\land\forall x[x=a\lor x=b\lor x=c\lor x=d]]$$
The first set of equalities, wrapped under the negation, means that $a,b,c,d$ are different, so $M$ has at least four elements. The second set of equalities, in the universal quantifier's scope, means that all elements are equal to one of these four, so $M$ has at most four elements. The two combine and force $M$ to have exactly four elements.
Comment: This is almost exactly what I thought of right after writing down my last comment on the question. Nonetheless, very helpfull indeed.


Proving the squeeze theorem

Question: I know there are posts out there asking about this, but I didn't want to look at other solutions before I feel like I've solved it on my own or at least gotten close. If I'm on the wrong track, any hints would be very welcome instead of a solution. Here's what I have:

Prove the suqeeze theorem: suppose $g(x) \leq f(x) \leq h(x)$ for all $x\in\mathbb{R}$ satisfying $0<|x-c|<\delta$ for some $\delta > 0$. If $\lim_{x\rightarrow c} g(x) = L = \lim_{x\rightarrow c} h(x)$, then $\lim_{x\to c} f(x) = L$.

Proof:
By definition, for $0 < |x-c| < \delta$, $\delta > 0 \implies |h(x)-L| < \epsilon$, $|g(x)-L| < \epsilon$ for any $\epsilon > 0$. Then,
$$ \begin{align}
|h(x) - g(x)| - |g(x) - L| &\leq |h(x) - g(x) + g(x) - L| && |h(x) - L| < \epsilon  \\
|h(x) - g(x)| - |g(x) - L| &< \epsilon && \text{limit definition}\\
|h(x) - g(x)| &\lt \epsilon + |g(x) - L| && \text{rearrange} \\
|h(x) - g(x)| &< 2\epsilon && \text{limit definition}
\end{align} $$
Now, since $g(x) \leq f(x) \leq h(x)$, then $|g(x) - f(x)| \leq |h(x) - g(x)| $. This means that $|g(x) - f(x)| < 2\epsilon$. Then,
$$ \begin{align}
|f(x) - L| - |g(x) - f(x)| &\leq |g(x) - f(x) + f(x) - L|  && \text{triangle rule} \\
|f(x) - L| - |g(x) - f(x)| &< \epsilon && |g(x) - L | < \epsilon\\
|f(x) - L| &\lt \epsilon + |g(x)-f(x)| && \text{rearrange} \\
|f(x) - L| &< 3\epsilon && |g(x) - f(x) < 2\epsilon|
\end{align} $$
I could start with $\epsilon/3$ to end with $|f(x)-L| < \epsilon$; regardless, is this proof correct? Thank you!
Answer: Your first sentence is not correct, though I understand what you mean. I think you should say something like: "Let $\varepsilon > 0$ be arbitrary. By making $\delta$ smaller if necessary, we may assume that for all $x \in \mathbb{R}$, $$0 < |x - c| < \delta \implies |h(x) - L| < \epsilon \text{ and } |g(x) - L| < \varepsilon."$$
The rest of your math is correct, but you should preface the computations with something like "let $x \in \mathbb{R}$ with $0 < |x - c| < \delta$ be arbitrary" because you never said what $x$ was.
The proofs of the inequalities seem a bit unnatural. In my opinion, it is more natural to do
\begin{align}
|h(x) - g(x)| &\leq |h(x) - L| + |L - g(x)| \\
&< 2\varepsilon.
\end{align}
and
\begin{align}
|f(x) - L| &\leq |f(x) - g(x)| + |g(x) - L| \\
&\leq |h(x) - g(x)| + |g(x) - L| \\
&< 3\varepsilon.
\end{align}
Comment: Thank you. I was definitely a bit sloppy, thanks for reminding me that I need to state things carefully. I also appreciate the comments on the inequalities, I guess I was thinking of them too rigidly in the form I knew, but of course moving them around the way you did makes them seem easier to recognize/parse
Answer: This proof looks just about fine. Here is one comment I have:

By definition, for $0 < |x-c| < \delta$, $\delta > 0 \implies |h(x)-L| < \epsilon$, $|g(x)-L| < \epsilon$ for any $\epsilon > 0$.

It is unclear whether or not you are taking $\delta$ to be the minimum of the $\delta$'s coming from $h$ and $g$ for any $\varepsilon>0$. Personally, I would make that more explicit if that is what you intended.
To shorten up the part where you show that $|h(x)-g(x)|<2\varepsilon$, I would make use of the fact that $\lim\limits_{x\to c}h(x)=L=\lim\limits_{x\to c}g(x)$. Then $$|h(x)-g(x)|\leq |h(x)-L|+|L-g(x)|<2\varepsilon $$ for $x\in\mathbb{R}$ with $0<|x-c|<\delta$ and $\varepsilon>0$.
Other than that the proof is correct.
Again, to cut down on some time, here is an alternate proof:

Let $\varepsilon>0$. Let $x\in\mathbb{R}$ with $0<|x-c|<\delta$, where $\delta$ is the minimum of the $\delta$'s coming from $g$ and $h$. Then we have
\begin{align}-\varepsilon<-|g(x)-L|\leq g(x)-L\leq f(x)-L\leq h(x)-L\leq |h(x)-L|<\varepsilon\end{align}
which implies $|f(x)-L|<\varepsilon$.
Comment: Thank you! Sometimes I get a fixed notion in my head but I wish I would've been more flexible and considered your approaches. Thanks for hiding the solution too btw, appreciate you letting me read it on my terms. Pretty nice proof, thank you for sharing!

Proving the squeeze theorem


How to find points of intersection of two rectangles?

Question: Hi i need to find coordinates of where does two rectangles intersect.
I have the coordinates of middle of each rectangle(square) and width/lenght of said rectangle.
So for example i have square A and square B
square A middle point is [2,2] and lenght is 2
square B middle point is [4,4] and lenght is 4
now i can calculate the coordinates of each square in left bottom, right bottom, left top and right top
so lbA [1,1] rbA[3,1] ltA[1,3] , rtA[3,3]
and lbB [2,2] rbB[6,2] ltB[2,6], rtB[6,6]
now when i draw this i see that they intersect in [3,2] and [2,3]
but i need to find some kind of formula for this because i need to code this for any given squares.
My attemp at this was for the program to get all coordinates of the square A and B and compare them and if there is a match i have coordinates of intersection but i feel like there has to be a easier way to do this.
Answer: HINT for a general method.
Let the vertical sides of the first rectangle have equations $x=a$ and $x=b$. Let the vertical sides of the second rectangle have equations $x=A$ and $x=B$.
For the horizontal sides let the equivalent equations be $y=c,y=d,y=C,y=D$.
There are a few possibilities. Perhaps the main one is where the rectangles intersect as in your example. This occurs when the rectangles intersect at a corner. For example, if $a<A<b<B$ and $c<C<d<D$ then the intersections occur at $(A,d)$ and $(b,C)$. In general, for possibilities like this, just use the pairs of 'inner' numbers.
The other main possibility is where both intersections occur on an edge of one rectangle. There is also the case where the rectangle intersect along a line of points. See if you can work out what is true about the numbers $a,b,A,B,c,d,C,D$ in such cases.


Is a space of constant sectional curvature an open subset of a space form?

Question: Let $(M,g)$ be a connected (not necessarily complete) Riemannian manifold with constant sectional curvature. Then is $(M,g)$ isometric to an open subset of a space form?
(By space form, I mean a complete connected Riemannian manifold of constant sectional curvature.)
Answer: Not necessarily. Here's an interesting counterexample. Let $N$ be $\mathbb S^2$ with the north and south poles removed, and let $M$ be the universal cover of $N$. (Since $N$ is diffeomorphic to $\mathbb R \times \mathbb S^1$, $M$ is diffeomorphic to $\mathbb R^2$.) Give $M$ the constant-curvature metric obtained by pulling back the round metric from $N$ via the covering map. (You can visualize the covering map as an infinitely long orange peel wrapping around the sphere countably many times.)
Suppose $S$ is a space form and $F\colon M\to S$ is an isometric embedding. There's a Riemannian covering $\pi\colon \mathbb S^2 \to S$. Since $M$ is simply connected, it follows from covering space theory (see [ITM, Thm. 11.18]) that $F$ has a lift to a continuous map $\widetilde F\colon M\to \mathbb S^2$, and since $F$ and $\pi$ are local isometries, so is $\widetilde F$. Moreover, the fact that $F$ is injective implies $\widetilde F$ is also injective.
Now let $\gamma\colon \mathbb R\to \mathbb S^2$ be a unit-speed periodic geodesic whose image is the equator in $\mathbb S^2$, and let $\widetilde \gamma \colon\mathbb R \to M$ be the geodesic that projects down to the equator under the covering map. Then $\widetilde F \circ \widetilde \gamma$ is an infinitely long injective geodesic in $\mathbb S^2$, which is impossible.
[ITM] John M. Lee, Introduction to Topological Manifolds, 2nd ed.


How add custom AcessResult reason?

Question: When i look at

AccessResult::forbidden()

We can set a reason as parametter.
So i try this :
<code> public function access(Request $request, AccountInterface $account)
    {

        $userRole=$account->getRoles();

        if(in_array("administrator", $userRole) || in_array("agence", $userRole))
        {
            return AccessResult::allowed();
        }

        return AccessResult::forbidden('TESTTT');
    }
</code>
If a user try to access my page who call this custom check access, he got :

So it's in french but it's the default forbidden access message.
I try to custom this message, and i was thinking about the reason in parameter.
Any idea why i can't get TESTTT as message ?
Comment: The reason is for example use for REST requests, the UI doesn't really use them (yet).
Answer: As per function definition:
<code>   /**
    * Creates an AccessResultInterface object with isForbidden() === TRUE.
    *
    * @param string|null $reason
    *   (optional) The reason why access is forbidden. Intended for developers,
    *   hence not translatable.
    *
    * @return \Drupal\Core\Access\AccessResultForbidden
    *   isForbidden() will be TRUE.
    */
   public static function forbidden($reason = NULL) {
     assert('is_string($reason) || is_null($reason)');
     return new AccessResultForbidden($reason);
   }
</code>
So the $reason is only intended for developers.

How add custom AcessResult reason?


Is a smooth function on a line locally quasi-convex almost everywhere?

Question:
Is a smooth function on $\mathbb{R}$ locally quasi-convex almost everywhere?
Is a smooth function on $\mathbb{R}$ locally convex at almost every local minimum?

True? I think the only counterexamples are at the local maxima.
Intuition tells me that it is true?
Comment: @6'whitemale Obviously for $\mathbb R^n$ the first statement is not true. I am considering the $\mathbb R$ case for now. But I will be very appreciate if you could extend the discussions to $\mathbb R^n$. Thanks again.
Answer: I'm pretty sure 2. fails. Consider the function
$$\tag 1 f(x) = \exp [-1/(x(1-x))]\cdot[2 + \sin (\,1/(x(1-x))^2\,)]$$
for $x\in (0,1),$ $f=0$ everywhere else. Then $f\in C^\infty(\mathbb R),$ $f>0$ on $(0,1),$ and the support of $f$ is $[0,1].$ Clearly $f$ has a local minimum at both $0$ and $1.$ A slightly messy, but not too awful, computation shows $f'$ is both positive and negative in any neighborhood $0,$ and in any neighborhood $1.$ Thus $f$ is not locally convex in any neighborhood of those points.
This example can of course be transferred to any bounded interval $(a,b).$
Now suppose $K$ is a Cantor set of positive measure. Then the complement of $K$ is a pairwise disjoint countable union of open intervals. All but two of these intervals is bounded; let $(a_n,b_n), n=1,2,\dots$ be these bounded intervals. Then every point of $K$ is either one of the endpoints $a_n,b_n,$ or is the limit of a subsequence of these endpoints.
On each $(a_n,b_n)$ we construct $f_n$ as in $(1).$ If we choose small enough positive constants $c_n,$ then the function $f=\sum c_nf_n$ will be smooth on $\mathbb R.$ This $f$ is positive on each $(a_n,b_n)$ and is $0$ everywhere else. Thus each point of $K$ is a local minimum of $f.$ But because of the oscillation of each $f_n'$ near $a_n,b_n,$ $f$ fails to be locally convex at each $x\in K.$


Plus or minus sign using Apache Solr

Question: When I enable Apache solr, everything works perfectly fine except for the following scenario.
When I do a keyword search using character - (minus symbol), or +, I get the error:

The Apache Solr search engine is not available. Please contact your site administrator.

Do you know why this happens?
Answer: You need to be using Apache Solr 3.1 and have the edismax plugin enabled to allow for these boolean operator queries. You should see this in your Solr logs as 'an unknown query type' error. This should be an option in the ApacheSolr Drupal module since this patch but if not (or if you're running Apache Solr 1.4.x) you can check out this ticket on the solr forum for instructions on how to patch your solr and solrconfig.xml to allow for edismax queries.
Comment: Thank you #schnippy, will try and let you know if that works

Plus or minus sign using Apache Solr


blueimp jquery file upload - "done", "complete" callbacks not working for IE 9

Question: I am using Blueimp Jquery File Upload plugin to upload files asynchronously. It works well in most other browsers (with a few minor issues) - on IE, I see this issue that the "done", "stop", "always", "complete" and some other event callbacks are not getting invoked.
While debugging, I added console.logs in the "done", "fail", "always", and added a "complete" method to the ajax request in the _onSend function (in jquery.fileupload.js) - but none of them seem to get invoked in IE.
<code>_onSend: function (e, data) {
        var that = this,
            jqXHR,
            slot,
            pipe,
            options = that._getAJAXSettings(data),
            send = function (resolve, args) {
                that._sending += 1;
                jqXHR = jqXHR || (
                    (resolve !== false &&
                    that._trigger('send', e, options) !== false &&
                    (that._chunkedUpload(options) || $.ajax(options))) ||
                    that._getXHRPromise(false, options.context, args)
                ).complete(function (result, textStatus, jqXHR) {
                    console.log("complete");
                }).done(function (result, textStatus, jqXHR) {
                    console.log("done", result);
                }).fail(function (jqXHR, textStatus, errorThrown) {
                    console.log("fail", result);
                }).always(function (a1, a2, a3) {
                    console.log("done", result);

                   }
                });
                return jqXHR;
            };
</code>
[plugin code trimmed for readability]
I understand that in IE 9, jquery.iframe-transport.js used for the file upload (as XHR file uploads are not supported in IE).
I'm not sure how I should go about fixing/ debugging this issue.
Thanks!
Answer: The done event gets fired if the content-type of the response is set to "text/html" or "text/plain" (instead of application/json) when json is being returned from the server. This applies only for browsers that do not support XHR file upload (such as IE9) and where the blueimp plugin is using IFrame transport instead.
Related info under "Content Negotiation" in the plugin documentation:
https://github.com/blueimp/jQuery-File-Upload/wiki/Setup
Comment: how can we do that for rails app ?
Comment: @CanCeylan: render :text => { ... }.to_json instead of render :json => { ... }
Comment: @tanushree thank you for taking the time to write down this response. It fixed an issue that I've been debugging for a while now.
Comment: @PhysX Glad that it was of help! I had spent quite a while trying to fix the issue as well.
Comment: I am rendering a 'js.haml' partial using "render partial: "partial_name" and return", still in IE 8 & 9, blueimp is not working. It works in IE 10. When images is submitted in IE 8/9, "formData" attributes are not in params, hence problem is occurring. Can any one help me in this.
Comment: @tanushree Note that according to the docs the `done` callback is also called when the JSON response contain an `error` property (for the case you described) https://github.com/blueimp/jQuery-File-Upload/wiki/Options#done
Answer: For the record, I ran into this problem when uploading direct to S3, now that their CORS feature allows for that.
The solution was to set success_action_status to '200', and then the Done event was triggered correctly.
Answer: In case anyone is still having this issue with direct upload to S3 the solution is to add a success_action_status field with the value of "201". Make sure that that you include it as part of the policy data as well since they have to match.
Apparently when receiving the upload from IE9 S3 will return an empty string. To get it to return XML, which the file uploader needs, you have to tell it return a status of 201.
Comment: Were you able to parse the XML result? I need to get the key name of the uploaded file, I can see it in the XML response, but `data.result` is undefined with the `done` method. It seems like it's due to this - https://github.com/blueimp/jQuery-File-Upload/wiki/Cross-domain-uploads#cross-site-iframe-transport-uploads. Know of any workarounds?
Comment: @chris it's been a while since I looked at this and I'm not 100% sure I understand the issue you're seeing . But I just checked my code and I'm accessing the upload like this in the **on('fileuploaddone', function(e, data) {...}** callback like so:  **file = data.files[0]**


Phpmyadmin sql import error, Joomla 2.5

Question: I'm receiving this error #1064 when i try to import the sql i recently exported. This is within phpmyadmin. Joomla site exists on host but the domain expired, I now need to apply a new domain different to the first. No access to Joomla right now. Using cpanel. Help greatly appreciated, no expert here. Please see attached screengrab.
See Image
Thanks
Answer: There is a minus - before CREATE TABLE. Remove that and it'll work fine
Comment: Thanks for the quick response Sjon, I tried what you suggeted however received this result  http://i.imgur.com/jtNn3cy.png
Comment: Create a database first, and import the dump in there
Comment: Ok So I've added a new database and tried to import again, this is the error screen http://i.imgur.com/UIbUaMv.png Thanks
Comment: Your server not support Innodb motor. See on your machine ( cat /etc/my.cnf | grep skip-inndob. If exist comment and restart mysql. ) If you are not root of machine ask your hosting provider.
Comment: @DoeJolan Don't know where you got that dump from, but `TYPE=InnoDB` should be replaced with `ENGINE=InnoDB`
Comment: Thanks guys, I have changed TYPE to ENGINE. I then
Comment: new database created

re-imported sql export with new domain changes

error received after a few minutes:
Script timeout passed, if you want to finish import, please resubmit same file and import will resume.
Comment: After I resubmit the file I get #1062 - Duplicate entry '1' for key 'PRIMARY'

Phpmyadmin sql import error, Joomla 2.5


javac: invalid flag: getting error when compiling java servlet

Question: I run the command
javac -cp C:\Program Files\Apache Software Foundation\Tomcat 8.5\lib\servlet-api.jar Demo.java

for generating class file
But I am getting an error message:
javac: invalid flag: Files\Apache
Usage: javac <options> <source files>
use -help for a list of possible options

Answer: This isn't a java question, it's a basic "how do I Command Line" question. Spaces separate arguments, so, you have to enclose a path in quotes. That, or, don't put spaces in any of your directory names.


Problemas com menu dropdown com bootstrap

Question: Fiz um menu dropdown em minha página. Quando eu seleciono o menu acontecem os seguintes problemas:
1) Não fica nada selecionado, ou seja, escolho a opção, mas não seleciona nada.
2) Mesmo não sendo selecionado nada, o menu fica aberto, fechando quando seleciono e nem se eu clico em algum lugar da página, não volta mais ao normal.
Esse código peguei na net para alterá-lo para meu uso.
Meu cshtml(view):
<!DOCTYPE html>

    <title></title>

    <link href="~/Content/bootstrap.css" rel="stylesheet" />

Home

Technologies

Article

blog

                    News

Home

Technologies

Article

blog

Answer: Basta realizar a seguinte alteração:

Adicionando o atributo data-toggle="dropdown"


How to css Views Tree module theme

Question: I am using the module Views Tree. Apparently, it gets the hierarchical listing of taxonomy terms, and outputs a tree with indentation levels (two levels).
However, I am not able to style or css it, because the overriden tpl.php ( views-tree.tpl.php ) does not exist, and when I copy views-view-row.tpl.php in the theme folder, renaming the file to views-tree.tpl.php I almost get it, except that the rendering is: first the parent taxonomy terms, and next the children terms. Exactly as without the module.
So I am unable to use none of the available .tpl.php for Views, and cannot change the style, only with css, which is not adequate (there are ul tags which I want to have different classes, for example).
So, sadly, I must use template.php and views_get_view_result to recover the View and css it, which is exactly as not having the module installed at all! What am I doing wrong?
Answer: Finally, I discovered that the module uses the core listing resources, so the theming can be achieved via template.php and function NAMEOFTEMPLATE_item_list($variables). The only caveat is that, as the call to this function is recursive, you will need some tricks to know in which level you are. Those tricks could depend on the listing itself; another solution would be to modify the module itself to send the level.
Honestly, I think this in an example of a module whose existence is questionable. A direct treatment of the View_results is much faster and easier to theme.

How to css Views Tree module theme


Solving non-square linear matrix equations

Question: Let's say we have
$${\bf A} = {\bf B} {\bf X}$$
where $\bf A$ and $\bf B$ are known matrices, $\bf X$ is unknown. In case $\bf B$ was square, a solution can be found by ${\bf B}^{-1} {\bf A} = {\bf X}$. But how do you attempt to solve for $\bf X$ when $\bf B$ is not square, i.e., $n \neq m$?
Comment: What you mentioned works only if $B$ is invertible, by the way.
Answer: Let $\mathbf{a}_1,\ldots,\mathbf{a}_k$ be the columns of $\mathbf{A}$ (so $\mathbf{A}$ is $n\times k$ for some $k$). Notice that we will have $\mathbf{B}$ is $n\times m$ and $\mathbf{X}$ is $m\times k$ for some integer $m$ (for $\mathbf{BX}=\mathbf{A}$ to work out). Let $\mathbf{x}_1,\ldots,\mathbf{x}_k$ be the columns of $\mathbf{X}$.
Notice that $\mathbf{a}_i$ depends only on $\mathbf{B}$ and $\mathbf{x}_i$, since $\mathbf{Bx}_i = \mathbf{a}_i$. So to determine the $i$th column of $\mathbf{X}$, it suffices to solve the system of linear equations
$$\mathbf{B}\mathbf{x}_i = \mathbf{a}_i.$$
So finding $\mathbf{X}$ is equivalent to solving $k$ systems of linear equations.
In fact, you can just do them all at the same time. Simply take a matrix that is made up of $\mathbf{B}$ followed by $\mathbf{A}$:
$$\left(\mathbf{B}|\mathbf{A}\right)$$
and use Gauss-Jordan elimination on $\mathbf{B}$. The solutions you find for each column corresponding to $\mathbf{A}$ yield the columns of $\mathbf{X}$.
Comment: Can you elaborate on a procedure if you were attempting to solve for B, instead of X?
Answer: In addition to Arturo's answer, maybe you could take a look at mine to this question.
Answer: The answer is given by the Penrose pseudoinverse:
$z=B^{pseudo}A $.
While an exact solution exists only in the case $B^{pseudo}=B^{-1}$ the solution always guarantees that $||A-Bz||=minimum$


binomial coefficient aproximation

Question: I found this aproximation
$$
\binom{n}{k}\sim \frac{n^k}{k!}
$$
But there was a note that said this holds just when $n>>k$, why is this? I need to consider this binomial coefficient when $k$ is near of $n/2$ and I would like use this or any similar expression to avoid some factorials.
Comment: Use [Stirling's approximation](https://en.wikipedia.org/wiki/Stirling%27s_approximation).
Comment: yes, that's exactly what I want to use, but I just want to know if I can reduce the factorial expressions in order to have less Stirling's
Answer: You can write the coefficient as $\frac {n(n-1)(n-2)\ldots (n-k+1)}{k!}$ When $n \gg k$ the numbers you subtract from $n$ in the numerator may be too small to matter.  If you ignore them you get the approximation $\frac {n^k}{k!}$  When $k$ is near $\frac n2$ this is not a good approximation.  Stirling's approximation is quite accurate, leading to the approximation of the central binomial coefficient $${2n \choose n} \approx \frac {4^n}{\sqrt {\pi n}}$$
Answer: Because when $k$ is not a lot smaller than $n$, it doesn't work. We see this, for instance, with $k = n$ where $\binom nk = 1$ but $\frac{n^k}{n!}\gg 1$.

binomial coefficient aproximation


page.aspx and code behind (page.aspx.vb) relations problems

Question: I'm working in a web project and I decide to turn in MVC 4 from ASP.NET.
After many issues which I face it, I'm in a position to handle the events raised from the program.
In my previous environment ASPX.NET I was double clicked on a <asp:Button.../> control and automatically in the code behind I see the related procedure.
And of course every time I hit the button the program goes to this procedure, and the related event click.
Now in MVC 4 I following the same process, but when I'm trying to hit the button the program never goes to the procedure.
Another example is, when I have a Label control and I want to make it visible or Hidden then I use the
labelId.style.add("Visibility","Hidden") or "Visible".
And another one is:
ValidationSummary.ValidationGroup

Now in MVC happen the same but before I use the controller.
(The reason to use the controller is that I want to go to the asp:button on_click procedure since the program refuse to go through the event.)
After the controller process the Label control is evaluated but it is completely empty, and with an empty control we can't do anything.
The same happen in ValidationSummary is empty and then it threw an error
What I have done until now
When I use the inheritance web.UI.Page the program throws me this error:
The view at '~ / Views / Home / Index.aspx' must derive from ViewPage

So I change the inheritance to ViewPage
And I use the following Javescript to call the controller:

And from controller I use these instructions in the function:
   Public Function loginSubmit() As JsonResult
      Dim routes As New RouteCollection With {.RouteExistingFiles = True}
      Return Json(New With {Key Attributes.logSubmit.LoginButton_Click}, JsonRequestBehavior.AllowGet)
   End Function

When that happen not any control works from my page.aspx
Is there someone to assist me on this issue?
Comment: MVC and Webforms have different concepts regarding controls. In Webforms you're using `` control & handle form validation with ``, but in MVC you're using `BeginForm` with `FormMethod.Post` using `` & apply viewmodel for validation with `@Html.ValidationSummary()` helper. Of course you can't simply replace `System.Web.UI.Page` with `System.Web.Mvc.ViewPage` in existing ASPX webforms page.
Comment: I'm afraid you can't take the original WebForms based application and turn it into an MVC application with some small code adjustment (or, at least, this is something I would not try for any non-trivial application). Those two development paradigms are quite different from each other.
Comment: If I leave the `System.Web.UI.Page` of course I get an error and I know that I have to change it. What else I can do for this change. In `ValidationSummary` I use I do some additional issues as well that is the reason Ii use this manner `webforms`. Please be more specific about the `BeginForm` and the `FormMethodePost`
Comment: Yes you have right to that. I'm face it, with many problems. Now I'm trying to use `razorpage` with `LayoutPage`. Wish me luck
Answer: As said on the comments Asp.net web forms and Asp.Net MVC are a totally different concept. I know you know that. Asp.net Web forms work on code behind concept whereas Asp.Net MVC has route-based URLs means URLs are divided into controllers and actions and moreover it is based on controller not on physical file. In web forms, there are server controls but  Asp.Net MVC follow customizable syntax (Razor as default). And again as said on comments you cannot change System.Web.UI.Page with System.Web.Mvc.ViewPage in existing ASPX web forms page. So you need to have your views using a razor syntax. From your question what I can suggest is like below.
    // View.
@ModelType ViewModel   //Model you want to bind to the view.
     @Using Html.BeginForm("Login", "Account", New With {.ReturnUrl = ViewBag.ReturnUrl}, FormMethod.Post) // we pass action name as first parameter and controller name as third parameter.
                @Html.AntiForgeryToken()
                @<text>
                    @Html.ValidationSummary(True, "", New With {.class = "text-danger"})

                        @Html.LabelFor(Function(m) m.Email, New With {.class = "col-md-2 control-label"})

                            @Html.TextBoxFor(Function(m) m.Email, New With {.class = "form-control"})
                            @Html.ValidationMessageFor(Function(m) m.Email, "", New With {.class = "text-danger"})

                        @Html.LabelFor(Function(m) m.Password, New With {.class = "col-md-2 control-label"})

                            @Html.PasswordFor(Function(m) m.Password, New With {.class = "form-control"})
                            @Html.ValidationMessageFor(Function(m) m.Password, "", New With {.class = "text-danger"})

                            <input type="submit" value="Log in" class="btn btn-default" />

                </text>
            End Using

And in the controller.
    Public Class AccountController
        Inherits Controller
        <HttpPost>
        <AllowAnonymous>
        <ValidateAntiForgeryToken>
        Public Async Function Login(model As LoginViewModel, returnUrl As String) As Task(Of ActionResult)
            If Not ModelState.IsValid Then
                Return View(model)
            End If
// Your code logic
            Dim result = Await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout := False)
            Select Case result
                Case SignInStatus.Success
                    Return RedirectToLocal(returnUrl)
                Case SignInStatus.LockedOut
                    Return View("Lockout")
                Case SignInStatus.RequiresVerification
                    Return RedirectToAction("SendCode", New With {
                        returnUrl,
                        model.RememberMe
                    })
                Case Else
                    ModelState.AddModelError("", "Invalid login attempt.") // Because of this we can show the validation summary on view using  @Html.ValidationSummary
                    Return View(model)
            End Select
        End Function
    End Class

And the model is.
//In your case model class is different.
Public Class LoginViewModel
    <Required>
    <Display(Name:="Email")>
    <EmailAddress>
    Public Property Email As String

    <Required>
    <DataType(DataType.Password)>
    <Display(Name:="Password")>
    Public Property Password As String

End Class

I just described the way to handle your issue to my understanding from your question.
Comment: Yes you have understanding very well my question. The issue for me is not (so much) only to handle the login view page. But to handle the login data after the `loginButton_Click`. Really it is very difficult and now I need to start all over from scratch. With less knowledge about MVC. Thanks any way
Comment: @LefterisGkinis if my answer is helpful to you then could you please accept my answer? Or do you need any more explanation?
Comment: that instruction `ViewBag.ReturnUrl` threw me an error of `ReturnUrl not defined` why is that? And one more The Validation strings... where are they ?  don't we use them ?
Comment: Is it throwing the error on runtime or before compiling?
Comment: Before of runtime
Comment: @LefterisGkinisI cannot tell what exactly might have happened. I can tell that if you configure as I explained you will able to make it work. I think you might have already done it. Sorry for late response.


Issues Calling Execve In Forked Process

Question: I'm trying to create a very basic telnet server to practice memory corruption exploits. When I try to issue a command, in the first iteration, nothing happens. Second iteration I am getting multiple bad file descriptor errors printing on my server side. On the client side, everything seems ok. I get all the required prompts. Here's my relevant code:
int piper[2];
pipe(piper);

...
     while (1) {
        n = write(newsockfd,"Enter a command...\n",21);
                if (n < 0) error("ERROR writing to socket");
                bzero(buffer,4096);
                n = read(newsockfd,buffer,4095);
                strcpy(command, buffer);
                pid_t childpid;
                childpid = fork();
                if(childpid == -1) {
                    perror("Failed to fork");
                    return 1;
                }
                if(childpid == 0) { //child
                    printf("I am child %ld\n", (long)getpid());
                    if(dup2(piper[1], 1) < 0) {
                        perror("Failed to pipe in child process");
                    }
                    else {
                        close(piper[0]);
                        close(piper[1]);
                        char *args[] = {command, NULL};
                        execve(command, args, NULL);
                    }
                }
                else { // parent
                    if(dup2(piper[0], 0) < 0) {
                        perror("Failed to pipe in parent process");
                    }
                    else {
                        // read command output from child
                        while(fgets(command_out, sizeof(command_out), stdin)) {
                            printf("%s", command_out);
                        }
                    }
                }
            }

If I enter /bin/ls into my client, I get the following outputted onto my server:
I am child 26748

2nd time I do it, I get the following outputted to my server:
Failed to pipe in parent process: Bad file descriptor

0I am child 26749

Failed to pipe in child process: Bad file descriptor

Answer: There's a possibility that closing the pipe in the child process closes it in the parent process also. Consider moving your piper(pipe) in the beginning of the while loop. And to be safe, close the pipe at the end of the file loop not forgetting to test the return value of close.
Actually read puts a newline character at the end of input so your command could be for example testprog but in reality, when using read(), it is testprog\n so you have to get rid of the newline added or execve() will expect a program name with a newline in it.
#define STDIN 0
int n = read(STDIN, command, 4096);
command[n - 1] = '\0';   // get rid of newline

char *args = { command, NULL };
execve(buf, &args[0], NULL);

Comment: That did seem to get rid of my duplication errors. Execve is still not working as intended however
Comment: Is there an easy way to do that?
Comment: i've added code on how to get rid of the newline..i tested it on a small program and it works..

Issues Calling Execve In Forked Process


Matrix diagonalization takes infinitely many operations?

Question: I was reading chapter 7 (Tridiagonal Form) of the book The Symmetric Eigenvalue Problem by Parlett, and I came across a curious passage.
When explaining the advantages/usefulness of the tridiagonal form of symmetric matrices, he explains (with my comments in square brackets):

The eigenvalues and eigenvectors of $T$ [a tridiagonal matrix] can be found with significantly fewer arithmetic operations than are required for a full $A$ [full as in every entry could be nonzero].

Every $A$ [arbitrary matrix] can be reduced to a similar $T$ [tridiagonal] by a finite number of orthogonal similarity transformations. In principle, it requires an infinite number of transformations to diagonalize a matrix.

The problematic passage is in bold.
Not being very well versed in algorithms used to diagonalize matrices other than those used in early undergraduate linear algebra courses (i.e., find the roots of the characteristic polynomial and compute eigenvalues/eigenvectors by hand), I am puzzled by this statement.
Of course, I expect that diagonalizing a $n\times n$ matrix for large $n$ could take a very large amount of operations, but the claim that it can take infinitely many operations seems very counterintuitive to me.
Comment: sometimes people use infinite matrices, countable set of rows and columns. Not sure of the exact use myself.
Comment: Presumably they're talking about Householder transformations: constructing this matrix involves taking square roots but not solving any polynomials of higher degree than $2$.  With a finite number of such operations, it's impossible in general to solve a general polynomial of degree $3$ or higher, and thus to diagonalize a matrix whose characteristic polynomial is such.
Answer: The eigenvalues of a matrix are the roots of the characteristic polynomial, and there is no "quintic equation" and no nice closed-form expression for the roots of a general polynomial of degree more than five. So, we must use iterative algorithms to compute eigenvalues of matrices. While these iterative algorithms may achieve high accuracy in a small number of iterations, infinitely many iterations would be required to get the exact eigenvalues.
This is in contrast to direct methods for solving linear systems, which (neglecting roundoff error) compute the exact solution in a finite number of steps.


Is there a word in English to describe instances where a melody is sung by multiple singers/voices?

Question: I'm talking mostly in popular music / rock / etc. One prominent example of what I'm referring to is the start of Queen's Bohemian Rhapsody (pretty much up to the "I'm just a poor boy ... "; notice that at that point, even though there are multiple voices, that's a completely different thing: Freddie Mercury sings the melody, and several voices do a backing "oooooohhhh.... aaaaahhhh...." (well, or whatever they may be saying, if there's supposed to be lyrics in those back vocals)
In Spanish, we use (at least informally) the same word for "chorus", typically phrased as "in chorus" (as in, at the start of Bohemian Rhapsody, they sing in chorus). I guess being used to that usage, I'm eagerly trying to find an equivalent word in English. And yes, the chorus (now referring to the English meaning of the word chorus in the context of pop/rock music) typically (perhaps most of the time, although not always) is sung in that mode (that word that I'm looking for).
Notice that:

The term is very specific; polyphony or polyphonic is not specific enough (virtually 100% of popular music has at least a good fraction of the song that is polyphonic, if I understand correctly the term).
I would assume that "choral" is also not specific enough, although certainly, what I'm describing is an instance of a melody, not the chorus of a song, being sung by a vocal ensemble — in the context of pop/rock or other styles of popular music, where we are not talking about "choral music".
The term is not restricted to multiple voices in unison — in that starting bit in Bohemian Rhapsody, at least to my ear, the different voices are not always singing the same note (perhaps we could see it as a sequence of chords; each syllable in "is this the real life" is made by a chord where each note of the chord is sung by a different vocalist).
Comment: @Cal-linux I don't quite get what you want. A term will usually only be coined for something if it is either generic enough or iconic enough to justify it. If you are looking for a term that specifically refers to the vocal harmonies of in one specific section of one specific pop song – chances are quite high there is no such term.
Comment: You are most likely looking for a word like "harmony" or "background-chorus".
Comment: @Cal-linux Not really: https://en.wikipedia.org/wiki/Vocal_harmony
Comment: @Cal-linux they can be instrumental or vocal, and can also deviate from the rhythm of the main melody. In cases like Bohemian Rhapsody there's no real 'main melody', the vocals, singing in close-harmony, are the main feature (though arguably one of the voices is slightly more dominant). They ARE singing in chorus, but that phrasing is less often used in a pop/rock setting. This line/blurring between 'harmony' and 'the harmonies' has emerged out of rock/pop's quite piecemeal approach, using some elements of established western music theory and bypassing others.
Comment: @Cal-linux In the context you give I think your conclusion makes sense. Strictly in English language "chorus" means the group of singers are singing in unison (all the same note, no harmony). "In chorus" = a group singing/playing the same notes, "in harmony" a group singing/playing a selection of notes that have some harmonic relation to each other. But you would still be understood if you said 'the beginning of Bohemian Rhapsody is sung in chorus'. Chorus can ALSO refer to a song section, with historical links probably, and can also mean 'a group of supporting singers/dancers', in English.
Comment: The opening words of "Bohemian Rhapsody" are sung in a minor seventh chord, so definitely not in unison.
Comment: @Lazy ‒ definitely some characteristics in common with harmony, but harmony (as I understand it) refers to "background" accompanying sounds (usually simpler than the foreground melody and with a slower character .... meaning, that often enough, the melody goes in, say, a combination of 1/4 and 1/8 and 1/16 notes while the harmony goes in 1/2 notes or whole bars — just an example; not by any means a rule). The term I'm looking for refers to instances of the foreground/main melody.
Comment: I see.  This Wikipedia description of vocal harmony sounds quite like what I'm looking for. However, can it be used to describe specific bits of a particular song (e.g., a pop / rock song) ?? As I read it, it sounds more like a musical style in general (like "choral music".
Comment: Regarding "harmony" alone ‒ from https://en.wikipedia.org/wiki/Harmony, it sounds like the concept of harmony is far broader than I thought;  in my mind, harmony referred to the background, for example, in a simple piano piece, the right hand would do the melody (in simple pieces, one note at a time) and the left hand would do the harmony (usually chords, even in simple pieces). I see that harmony refers to a broader _concept_ (of which the above is sort of a particular case)
Comment: Again, it would sound like "harmony" cannot be the word I'm looking for (precisely because harmony is a broad concept — of course the term I'm looking for is a particular case of harmony, or in any case, it is a notion that involves harmony as one of its elements)
Comment: @Cal-linux indeed, but nevertheless colloquially within the areas of pop and rock they are referred to as 'the harmonies', 'vocal harmonies' or 'backing vocals' (for the last one it is generally implied that these backing vocals will need to be 'in harmony' for it to sound good). Harmony as you say is a large topic that concerns the interaction of pitched sounds but within pop and rock you don't tend to think of eg. the guitar chord as being 'in harmony with itself', though it is. Harmonious  layers of complimentary lines on top of main melodies are usually just called 'harmonies'.
Comment: Well, I just gave one example (something that a large fraction of the readers probably recognize); the need for the word actually came in a conversation the other day where I was trying to describe some of the unique features of Queen's music; of course, as soon as I used the term "chorus" (translating from the familiar term in Spanish), the other person (a native English speaker) immediately said "no, chorus relates to the structure of a song") .... but after a while, with me trying to explain what I was referring to, he could not think of a term that specifically describes it.
Comment: From the comments above, "vocal harmony" seems to be the closest to what I have in mind (among the "official" terms), and "in chorus" (which I see as a nearly-exact translation from the term in Spanish), according to OwenM's comment and Aaron's answer seems to be understandable, if uncommon  (mind you, it's not like in Spanish we use that term on a daily basis ... it is a notion that not necessarily often shows up in a casual conversation, at least in conversations among non-musicians)
Comment: "no, chorus relates to the structure of a song": chorus has multiple senses, most of which have nothing to do with musical structure and at least one of which has nothing to do with music.  It's like saying "no, _coro_ relates to a certain part of a church."
Answer: There's no formal term, but "in chorus" or "in concert" would be understood to mean what you have in mind.
Comment: @TannerSwett "consort" also refers to a group of instruments from the same family.
Comment: Do you mean "in concert"? I think "consort" usually means the spouse of a monarch.
Comment: @TannerSwett Yes, thanks.
Answer: I think you mean "homophonic".
From The Collaborative International Dictionary of English v.0.48 [gcide]:

Homophonic

(Mus.)

(a) Originally, sounding alike; of the same pitch; unisonous; monodic.
(b) Now used for plain harmony, note against note, as opposed to polyphonic harmony, in which the several parts move independently, each with its own melody.

[1913 Webster]

The corresponding noun would be "homophony".
Comment: Sounds like homophonic may be an adjective that applies to the instances I'm referring to.  But it does not sound (to me) like a term that specifically describes those.
Comment: In terms of modern music theory, homophony is used to mean multiple parts singing different notes on a shared rhythm (the second definition above).
Answer: I echo those who have said homophony is the word you're looking for. You could even be extra specific and say "homophonic harmony." As additional information, there are three main types of relationships between parts:

Monophony is when there is only one melody line present. It is typically interchangeable with Unison, and can be found in genres such as Gregorian Chant.
Homophony is when all voices have the same rhythm, but are in harmony on different notes. Most church hymns are written this way.
Polyphony is when different voices have different rhythms and, usually, different notes. Bach's chorales tend to be a good example, though they often have some homophony as well. You are right also that almost all popular music is polyphonic, though you usually won't see it described using that word.
Answer: In big band music and large-ensemble jazz, a shout chorus is a melodic line that is doubled throughout one or more sections, often including the vocal section. These are typically denoted with an Italian term such as tutti or soli, the latter of which has always struck me as kind of misleading, since the "doubling" is not usually in unison. Most commonly, it creates a closely-coupled harmonic line such as the one you mentioned from Bohemian Rhapsody.
Answer: I agree with user93865 that "homophony" is the single word that most closely describes what you are looking for. Unfortunately, it's probably true that it describes a wider range of situations, since there are many differing definitions. A related term is "homoryhthm", referring to a shared rhythm across all voices. Perhaps that, or even "homoryhtmic homophony" , is what you want.
You could also use "rhythmic unison", which is roughly synonymous with "homoryhthm" and is probably more accessible.
Answer: They are using a classic barbershop vocal harmony, as indicated by the solo line with the backing accompaniment in close harmony. This is a subset of a capella close harmony.
Answer: In modern music theory, Homophony has a very specific meaning, that being multiple parts singing different notes on the same rhythm (as opposed to Polyphony, singing different notes on different rhythms). So it's not quite what you are looking for.
Instead, a more accurate term is simply Unison. This can be used to mean part of the voices are singing the same note (i.e. the basses and tenors are in unison for the first 8 measures) or to mean all the voices are singing the same note (i.e. verse 3 is sung in unison).


Only homepage loads following migration (WordPress, nginx)

Question: following a migration from a shared platform to a private cloud server only the home page is loading.
After looking around the most common fix appears to be flushing the perma links and modifying the .htaccess with the following:
AllowOverride All
However the server uses nginx, after trying a .htaccess to nginx converter with the following code added to nginx.conf:
<code>location / {
  if (!-e $request_filename){
    rewrite ^(.*)$ /index.php break;
  }
}
</code>
However I had no luck with this.
Any assistance is appreciated - I hope this is sufficient information but let me know if not.
Thank you.
Comment: Nevermind I should have spent more time looking - eventually found https://nginxlibrary.com/wordpress-permalinks/
Answer: Rename .htaccess to some other name, lets say .htaccess1, then go to Settings -> Permalinks, Select Post Name and hit save. It will generate new .htaccess and see if it fix the issue.
Comment: Thanks for taking the time to read and comment. Unfortunately I cannot use a .htaccess as the server runs nginx however I should have spent more time looking as I eventually found https://nginxlibrary.com/wordpress-permalinks/


Is there a way to play vibrato on the piano?

Question: I know this is a silly question, but I couldn't help but wonder it. Is there a way to play vibrato on the piano? If not are there pianos out there with this feature?
Comment: Very easy on a synthesized piano... Not so much on a real one!
Comment: Indeed there are several electronic keyboards out there that have keys that are sensitive to finger motion and can be programmed to add vibrato. If you've ever watched Radiohead play on their Nord keyboards it'd be quite evident.
Comment: Fender Rhodes through a Leslie produces a sort of vibrato. Impossible using an acoustic piano - unless the strings are tuned honky tonk style.
Answer: Vibrato is impossible on the piano. The closest you could come is with the growling effect using the damper pedal, but this can be risky.
Vibrato is a standard technique on the clavichord, where it is called Bebung. This is possible due to the direct mechanical connection to the tangents which strike the strings. This possibility was a casualty of the development of the piano's escapement mechanism.
Answer: In the era of extended techniques, nothing is truly impossible anymore. At the expense of a nice sound and precise pitch, you can change the pitch of the note you are playing by pressing a finger or a suitable object on the strings. Obviously, if you wiggle it around you get a sort of vibrato.
There are quite some modern pieces that require altering the pitch of strings like this, however I haven't heard any that require vibrato.
Touching the strings with your fingers may cause them to rust.
Answer: Whilst you cannot do vibrato on a conventional grand or upright acoustic piano, recent developments do make vibrato possible on the Fluid Piano. Too many details to list here.
Answer: For electronic instruments you get what is modeled.  If it's available, it's available.  If not, you can try with some pedals/effects in the signal way.
For a real acoustic piano, there may be a very subtle effect by doing "vibrato" on the key strongly sideways.  It's not exactly a vibrato (namely a periodic pitch change) but a change in the character of resonance.  Whether they key is actually the best point for "warping the piano" may be questionable but it feels sort of natural to the player.
And maybe the mere act of the player being occupied with doing this "vibrato" already transfers its mood to the listener...
Answer: Flutter the sustainer pedal or rapidly repeat the vibrato note on the keyboard. Very fast.


Erro ao converter campo varchar em float

Question: Estou gerando uma Query e nessa Query estou fazendo um join entre um campo varchar e um campo float.
Sendo o campo SY.YE_MOEDA é varchar e o campo DA1_A1_MOEDA é float.
Segue minha Query:
SELECT
DA.DA1_CODTAB  AS TABELA,
DA.DA1_CODPRO  AS CODPRODUTO,
SB.B1_DESC     AS DESCRICAO,
SB.B1_PRV1     AS PRECOVENDA,
DA.DA1_MOEDA   AS MOEDA,
SY.YE_MOEDA    AS NOMEMOEDA
FROM DA1010 AS DA
INNER JOIN SB1010 AS SB WITH (NOLOCK) ON SB.B1_COD = DA.DA1_CODPRO
INNER JOIN SYE010 AS SY WITH (NOLOCK) ON CONVERT(FLOAT, ISNULL(SY.YE_MOEDA,0)) = DA.DA1_MOEDA
WHERE DA.D_E_L_E_T_ <> '*' AND DA.DA1_ATIVO = '1'

Segue o erro

Msg 8114, Level 16, State 5, Line 1 Error converting data type varchar
  to float.
Comment: Isto é o Protheus?
Comment: Sim protheus, mas consegui resolver o problema, na tabela onde esta o valor da moeda tinha um campo escondido com o código da moeda do tipo float, e este campo resolveu o problema do join.Mas muito obrigado pela atenção
Comment: Moeda `float` é muito errado. https://pt.stackoverflow.com/a/38140/101
Answer: No oracle existe um truque para fazer esta conversão:
select meuCampo + 0.0 as comoFloat from minhaTabela

Suponho que funcione no sql serve.
Outra solução é trocar o convert para decimal, ficando:
SELECT
DA.DA1_CODTAB  AS TABELA,
DA.DA1_CODPRO  AS CODPRODUTO,
SB.B1_DESC     AS DESCRICAO,
SB.B1_PRV1     AS PRECOVENDA,
DA.DA1_MOEDA   AS MOEDA,
SY.YE_MOEDA    AS NOMEMOEDA
FROM DA1010 AS DA
INNER JOIN SB1010 AS SB WITH (NOLOCK) ON SB.B1_COD = DA.DA1_CODPRO
INNER JOIN SYE010 AS SY WITH (NOLOCK) ON CONVERT(DECIMAL, ISNULL(SY.YE_MOEDA,0)) = DA.DA1_MOEDA
WHERE DA.D_E_L_E_T_ <> '*' AND DA.DA1_ATIVO = '1'

Comment: Sim protheus, mas consegui resolver o problema, na tabela onde esta o valor da moeda tinha um campo escondido com o código da moeda do tipo float, e este campo resolveu o problema do join.Mas muito obrigado pela atenção.
Comment: SHOW QUE BOM :)
Comment: Tabela customizada em Protheus com "chave" numérica , você se arrepende de ter nascido .... :)


Scientific references to singing?

Question: Is there a reference to scientific approaches to singing? For instance a classic book, or a journal? I'm mainly after the acoustics of the voice, and studies about the projection of the sound and the use of the resonance cavities in the head.

What I've found is the book "Dynamics of the singing voice" which is somehow good, but also disappointing (at the end, I remember it refers to quantum effects  and the author even sadly cites charlatan Deepak Chopra).
Hence I'm looking for a more serious reference.
Comment: Can you explain what you're after?  The science of controlling vocal cords w/o damage?  The science of harmony? The bioneurology of learning music and words?
Comment: Have you done any basic research - for example a quick web search on "vocal tract acoustics" produces some basic articles and a few names of researchers in the field.  This is of importance to speech synthesis, so I'm sure there will be lots of academic material around.
Comment: Definitely Complete Vocal Technique by Cathrine Sadolin.
Answer: The Musician's Guide to Acoustics by Campbell and Greated is a wonderful book that includes at least a chapter on the science and acoustics of singing - including standing waves and acoustic impedance in the vocal tract and how resonances create a formant that allows an opera singer to be heard over an entire orchestra despite putting out far fewer acoustic watts.
The downsides are it looks like it will set you back about USD 100 and it is not focused on singing exclusively and in-depth.
If you have a university library near you, that's where I would go and get a stack number for an acoustics book and look at the other titles in that section. There's a highly regarded acoustics book by Benade (the title escapes me) that you might look for also.
Comment: *Fundamentals of Musical Acoustics* A. H. Benade, 1976?
Answer: I would highly recommend Singing: The Mechanism and the Technic by William Vennard.  Also decent is Your Voice: an Inside View by Scott McCoy.
Any good pedagogy text will get you on the right track regarding resonance.  My personal favorites are the Richard Miller and the Barbara Doscher.
In terms of computerized synthesis and things of that nature, you might consult that vast body of literature, starting with the CSound community, the Curtis Roads Computer Music Tutorial, and a good search of Computer Music Journal on JSTOR, although you may have to work a little harder in that case.

Scientific references to singing?


Erro no context-root javaEE usando Jboss

Question: Estou com um projeto com erro, tenho estás mensagens de erro nos arquivos de configuração: 404 - Not Found
jboos-web.xml

web.xml
Comment: Po favor, não coloque código como imagem. Fica bem ruim de ler.
Answer: O context-root não deve incluir a barra. Deve ser apenas:
<jboss-web>
    <context-root>matriz</context-root>
</jboss-web>

Para que isso tenha efeito, remova o projeto do servidor e faça o deploy novamente.


Keeping variables and methods private when using classes via protocols in swift

Question: Today I came to a question, what is the point of keeping class fields/variables and methods private, if you are using those class instances as protocol instances. For instance,
protocol SomeProtocol {
  func someProtocolMethod()
}

class SomeClass: SomeProtocol {
  private var someVariable = ""
  func someProtocolMethod() { }
}

class SuperClass {
  var someInstance: SomeProtocol?

  func superMethod() {
    someInstance.someProtocolMethod()
  }
}

let superInstance = SuperClass()
let someInstance = SomeClass()
superInstance.someInstance = someInstance

Here in SomeClass we have private variable called someVariable. Usually, I write it down as a private variable intuitively for the sake of SOLID encapsulation type-of-thing. As I was writing tests today, I came up to a question, isn't it already encapsulated and safe with only pointing to protocol? Does it have any disadvantages, if I don't use direct class instances and keep variables and methods public?
Comment: @Paulw11 I'm not facing any problem in accessing the variable from superclass. May be I haven't asked the question right, but this is just a question about is there any disadvantages of keeping variables/methods of concrete class public, if we are working with those classes only via protocol pointers.
Comment: But you can't be sure you are always working with protocol types so for that reason it might be needed to use private if no other class in the same module/library should be able to change it
Comment: @JoakimDanielson lets consider that we are always working with protocol types, so is there any other disadvantages? Maybe any performance issues?
Comment: My whole point is that you can not consider that nor should you rely on it, so if it is important that a property or function is private for any reason then make them private.
Comment: Ok, I misread your question. I agree with Joakim, whether a property should be private or not is nothing to do with what protocols an object conforms to. Even if you say you are only accessing via protocols, you can't guarantee that. There are no performance issues at runtime since access is checked at compile time.
Comment: Thank you for all your answers. I appreciate it.
Answer: The only thing known from the outside world about someInstance is that it complies with protocol SomeProtocol.  So there seem to be no risk of the outside world that accesses  someInstance could access someVariable if it were public.
However, this is not sufficient to justify making the variable public.  I can see at least 3 reasons not to do so:

SomeClass can be used on its own, and not only via the protocols it complies with. After all, reuse is one of the driver in OO design.  In this case, making public something that should be private for could later reveal to be short-sighted.
The context that initialises someInstance knows very well the real type of the object and could misuse public properties that are not meant to be changed directly. Here the risk is in the last 3 lines of your example.
Finally, some downcasting could be done to the real type, which would then expose public members that should be private:
  class SuperClass {
    var someInstance: SomeProtocol?   // optional or initializer

    func superMethod() {
        someInstance?.someProtocolMethod()
        if let oops = someInstance as? SomeClass {  // Downcast
            oops.someVariable = "hacked!"           // successful
            print (oops.someVariable)
        }
        else {
            print ("No access")                     // downcast failed
        }

    }
  }

Conclusion: Always keep private what doesn't have to be public. Of course, if all these classes are of limited use, i.e. only for testing purpose and if you're the only maintainer, the risk of misuse can be low.  But why taking bad habits; think of your legacy ;-)
Regarding performance, there is no difference here between the public and private access. Access is managed at compile/assembly time.
The performance here is slightly impacted by the protocol which implies dynamic dispatch. But unless you write an operating system or a a function called in the main loop of a video-game it is so small that it's not relevant.


How to call limited data items per page?

Question: I am using one custom module, which is getting data from the database, with the following code.
function rs_get_doors() {
  $doors = array();
  $doors_nids =  db_select('node', 'n')
  $doors_nids = $door_nids->extend('PagerDefault')->limit(10);
    ->condition('n.type', 'vivarium_door')
    ->fields('n', array('nid'))
    ->orderBy('n.title', 'ASC')
    ->execute()
    ->fetchCol();

  foreach ($doors_nids as $nid) {
    $wrapper = entity_metadata_wrapper('node', $nid);
    $doors[$nid] = array(
      'name' => $wrapper->title->value(),
      'fee_nid' => $wrapper->field_fee_category->value()->nid,
    );
  }

  uasort($doors, 'rs_doors_natural_sort');

  return $doors;
}

it is getting thousands of nodes at time in a single page and it takes too much time to load.
So I think I need to paginate the query. How can I achieve this?
Answer: $doors_nids = db_select('node', 'n')

->condition('n.type', 'vivarium_door')

->fields('n', array('nid'))

->orderBy('n.title', 'ASC')

->extend('PagerDefault')->limit(10)

->execute()

->fetchCol();

Hopes this will helps you.
Comment: @Smalution- thanks for your response i will check with this and come back to you
Comment: @Smalution- it is showing like this error Parse error: syntax error, unexpected '$doors_nids' (T_VARIABLE)
Comment: can you see my edits ...after modification of code..my full code has shown above..
Comment: updated answer you can check now.
Comment: @ Smalution - thanks..i will check and get back to you
Comment: @ Smalution - still it is showing error..actually i am calling the doors with the combination of fee...in one place calling the function of doors and another function as fee and i will combine the both as one one function ...according to person wise have to select month and year the fee will show automatically it is working properly but having due to lot of data it is showing proxy server error so thats why need to do pagination ..can i share my . module file for you...pls help me on this it will very helpful for me....
Comment: @Smalution Please don't just show code; explain it and the difference with the code shown by the OP.
Comment: @DINE That is a completely different question. Users are answering about the code you are showing in the question. If you have another question about other code, please ask as new question.
Comment: @ kiamlaluno - thanks for your response ..i will post as new que
Answer: You are using the wrong method: It's not limit(), but range() that you should use.
  $query = db_select('node', 'n')
    ->condition('n.type', 'vivarium_door')
    ->fields('n', array('nid'))
    ->orderBy('n.title', 'ASC')
    ->range(0, 10);

  $result = $query->execute(); // Add here the call to fetchCol().

Notice that dynamic queries are slower than static queries; you should use them when you want other modules to dynamically alter your query. In the other cases, you should use static queries (i.e. use db_query() or db_query_range()).
$query = db_query_range("SELECT n.nid FROM {node} n WHERE n.type = 'vivarium_door' ORDER BY n.title ASC", 0, 10);

Reference

Range and limit
Dynamic queries (It contains example code for using range().)


PHPUnit failing if run from different directory

Question: I have my namespaced webapp in a folder named 'library'. If I'm in the directory and run phpunit the tests run just fine. However, if I go out of the directory and run phpunit library/ PHPUnit complains that it can't find the class that I'm calling using the use statement.
Here is my phpunit.xml which lives in the 'library' directory:
<?xml version="1.0" encoding="UTF-8"?>

<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.1/phpunit.xsd"
         backupGlobals="false"
         colors="true"
         bootstrap="./tests/testsBootstrap.php"
        >
    <testsuites>
        <testsuite name="JTW Framework Test Suite">
            <directory>./</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./tests</directory>
            </exclude>
        </whitelist>
    </filter>

    <logging>
        <log type="coverage-html" target="./tests/report" charset="UTF-8" yui="true" />
    </logging>
</phpunit>

And here is the test that's using the class (shortened):
<?php
namespace Tests\Assets;

use Jtw\Assets\Reader;

class ReaderTest extends \PHPUnit_Framework_TestCase
{
    public function testYamlReader()
    {
        $yamlFile = __DIR__ . '/assets/reader.yml';
        $yamlArray = Reader::read($yamlFile);

        $this->assertTrue(is_array($yamlArray));
        $this->assertEquals(2, count($yamlArray));
        $this->assertTrue(in_array('baz', $yamlArray));
        $this->assertTrue(is_array($yamlArray['test']));
        $this->assertEquals('baz', $yamlArray['qux']);
    }
}

And my 'testsBootstrap.php' file is bootstrapping WordPress and calling composer's autoload file.
Any ideas as to why the tests would run fine from within the 'library' directory but not from outside it, but pointing to it?
If you want to see the full setup it's on my GitHub account.
Answer: The problem comes from here:
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.1/phpunit.xsd"
         backupGlobals="false"
         colors="true"
         bootstrap="./tests/testsBootstrap.php"
        >

Your tests need to have the bootstrap run in order to run.  When you are not in your library directory, PHPUnit is not running the bootstrap and so the tests are not set up properly and fail.
Running the tests from the directory results in PHPUnit running the bootstrap for you.
To get them to run properly you can use --bootstrap option.
phpunit --bootstrap <path to library>/tests/testBootstrap.php <tests you want to run>

Comment: instead of specifying bootstrap file only, You can specify PHPUnit configuration file to use `phpunit -c /path/to/phpunit.xml `
Comment: That was exactly it. But I'm curious as to why it won't read my phpunit.xml in the folder I tell it to run the tests in; or at least it won't load the bootstrap.
Comment: Because you can tell phpunit to run any particular files or any subdirectory, so it looks in the current location for a phpunit.xml file.
Comment: That makes perfect sense. Thank you!


can i have dynamic date pickers using jquery by class selector

Question: i have a dynamic html table and in one column i want a jquery ui date picker.  A few questions:

Can i have datepicker by class instead of id:
$(document).ready(function(){
         $(".datepicker").datepicker();
  });
Can i create them on the fly if i i am adding in textboxes with this class using jquery?
Answer:
You can have the datepicker based on any jQuery selector you'd like. The .datePicker() just gets applied to whatever your selector returns.
Yes, you can create them on the fly, you just need to run the .datePicker() on your selector once you're read, same as you would in the document.ready(). Simply adding a textbox with the same class used in your document.ready code won't automatically set them up though, you need to make sure you run the .datePicker code again (unless you do something with .live queries).

Clarification for comment:
You'd want to avoid running the datepicker on something that's already had it run (but I don't think it will hurt if you do). So you could so something like giving the new TR in your table a unique ID (say the ID of the record?) and then run <code>$('#newRowId input.datePicker').datePicker();</code>.
Comment: for #2, would i keep just repetitively call ".datepicker().datepicker().  wouldn't that reset the ones already created ?
Answer: Today, I faced your problem. Change JQuery like below :
<code>$(".myclass").live("click", function() {
    $(this).datepicker({
        changeMonth: true,
        changeYear: true,
        gotoCurrent: true,
        dateFormat: 'dd-mm-yy',
        yearRange: '2016:c',
        defaultDate: 'today'
    }).datepicker('show');
});
</code>


Showing Two Polynomials Have Isomorphic Splitting Fields over $\mathbb{F}_p$

Question: Consider the polynomials, $f_1, f_2 \in \mathbb{F}_p[x]$, given by
$$
\begin{align}
f_1 &= x^{2^n} + 1 \\
f_2 &= x^{2^{n+1}} - 1
\end{align}
$$
How can we show that $f_1$ and $f_2$ have isomorphic splitting fields over $\mathbb{F}_p$?

I think I have a bit of a messy way of showing this using the fact that we can write
$$
\begin{align}
f_2 &= x^{2^{n+1}} \\
&= (x^{2^n} + 1)(x^{2^{n-1}} + 1) + \cdots + (x^2 + 1)(x + 1)(x - 1)
\end{align}
$$
However, my idea seems quite inelegant and doesn't use the fact that we are working over a finite field, so I feel like I am missing something.
Any ideas would be greatly appreciated. Thanks in advance!
Comment: Thinking about roots of unity looks promising...
Answer: Indeed, this hasn't much to do with the fact that we're working over a finite field. If you want, consider the question over an arbitrary field $K$. We may suppose $2 \neq 0$, or else there is nothing to prove. Call the corresponding splitting fields $L_1$ and $L_2$. Because $f_1$ divides $f_2$, there is a homomorphism $\phi : L_1 \to L_2$. To show that it is surjective, take a root $\alpha$ of $f_1$ of order $2^{n+1}$. Take any root $\beta$ of $f_2$. Then $\beta$ has order dividing $2^{n+1}$, so it is a power of $\phi(\alpha)$. Hence $\phi$ is surjective.
Comment: Sorry if I'm being a bit dense here, but how do we know that $f_1$ has a root of order $2^{n+1}$? (And thanks for the answer btw!)
Comment: Never mind, I've got it! If $\omega$ is a primitive $2^{n+1}$-th root of unity, then (by definition) it has order $2^{n+1}$, and is also a root of $f_1$ (for example, this follows from the definition of a primitive root of unity and the factorization of $f_2$ given in the question).
Comment: Indeed. Alternatively, as $\omega^{2^{n+1}}=1$, we have that $(\omega^{2^n})^2=1$, so $\omega^{2^n} = \pm 1$. It can't be $1$, because $\omega$ has order $2^{n+1}$, so it must be $-1$.


How to calculate the likelihood function

Question: Lifetime of 3 electronic components are $X_{1} = 3, X_{2} = 1.5,$ and $X_{3} = 2.1$. THe random variables had been modeled as a random sample of size 3 from the exponential distribution with parameter $\theta$. The likelihood function is, for $\theta > 0$
$f_{3}(x|\theta) = \theta^{3} exp(-6.6\theta)$, where $x = (2, 1.5, 2.1)$.
And then the problem proceeds to determine the M.L.E by finding the value of $\theta$ that maximizes $log f_{3}(x|\theta)$. My question is, how do I determine the likelihood function? I looked up the pdf of the exponential distribution, but it's different. So is the likelihood function always given to me in a problem? Or do I have to determine it myself? If so, how?
Comment: Why do you want to do likelihood estimation with only 3 observations?  The estimate you get for $\theta$ will be biased and have huge amount of variance.  Is it HW?
Comment: Do you know what the definition of the likelihood is?
Answer: The likelihood function of a sample, is the joint density of the random variables involved but viewed as a function of the unknown parameters given a specific sample of realizations from these random variables.
In your case, it appears that the assumption here is that the lifetime of these electronic components each follows (i.e. its has a marginal distribution), an exponential distribution with identical rate parameter $\theta$, and so the marginal PDF is:
$$f_{X_i}(x_i\mid \theta) = \theta e^{-\theta x_i}, \;\; i=1,2,3$$
Also, it appears that the life of each component is fully independent of the life of the others. In such a case the joint density function is the product of the three densities,
$$f_{X1,X2,X3}(x_1,x_2,x_3\mid \theta) = \theta e^{-\theta x_1} \cdot \theta e^{-\theta x_2}\cdot \theta e^{-\theta x_3} = \theta^3\cdot \exp{\left\{-\theta \sum_{i=1}^3x_i\right\}}$$
To turn this into the likelihood function of the sample, we view it as a function of $\theta$ given a specific sample of $x_i$'s.
$$ L(\theta \mid \{x_1,x_2,x_3\}) = \theta^3\cdot \exp{\left\{-\theta \sum_{i=1}^3x_i\right\}}$$
where only the left-hand-side has changed, to indicate what is considered as the variable of the function.
In your case the available sample is the three observed lifetimes $\{x_1 = 3, x_2 =1.5, x_3 = 2.1\}$, and so $\sum_{i=1}^3x_i = 6.6$. Then the likelihood is
$$L(\theta \mid \{x_1 = 3, x_2 =1.5, x_3 = 2.1\}) = \theta^3\cdot \exp{\left\{-6.6\theta \right\}}$$
In other words, in the likelihood you were given, the specific sample available has been already inserted in it. This is not usually done, i.e. we usually "stop" at the theoretical representation of the likelihood for general $x_i$'s, we then derive the conditions for its maximization with respect to $\theta$, and then we plug into the maximization conditions the specific numerical sample of $x$-values,  in order to obtain a specific estimate for $\theta$.
Admittedly though, looking at the likelihood like this, may make more clear the fact that what matters here for inference (for the specific distributional assumption),  is the sum of the realizations, and not their individual values: the above likelihood is not "sample-specific" but rather "sum-of-realizations-specific": if we are given any other $n=3$ sample for which the sum of its elements is again $6.6$, we will obtain the same estimate for $\theta$ (this is essentially what it means to say that $\sum x$ is a "sufficient" statistic -it contains all information that the sample can provide for inference, under the specific distributional assumption).


Filter redux state based on specific url to display one product and it's variations

Question: I'm currently setting up a drupal based e-commerce react site. I already have it set up to make api calls and store data in my react app. When I console log I'm getting my current 3 products, and I'm getting another array of all the product variations. It's all there in the state.
Also, I have a page that displays product details. It shows description, color options, size options, etc. Right now I have it set up where when I click the link from the product selector in my app, it moves to the product page with a url containing the name of the product I clicked and displays the correct product description. However, I need to filter it so that the redux state only includes that product and it's relevant variations. Hopefully that makes sense...
Not sure what you guys need to see from the app in order to understand my issue so please let me know and I will add them to clarify. Thanks!
Answer: Since you have not provided any part of your code, I have assumed some of it.
I hope this helps:
<code>class ProductPage extends Component {
  constructor(props) {
    super(props);
    this.state = { productDetails: {}, relatedProducts: [] };
  }

  componentDidMount() {
    // considering your product URL looks like domain.com/product/product-name
    const productName = window.location.pathname.split('/')[2];
    const productDetails = this.props.productList.find(product => product.name === productName);
    const relatedProducts = this.props.productList.filter(product => // determine how a product can be considered as related to the current product);
    this.setState({ productDetails, relatedProducts });
  }

  render() {
    // render codes...
  }
}

export default connect(
  state => ({
    productList: state.products // or whatever the name of your reducer for your product list in redux store
  })
)(ProductPage);
</code>


Clicking on referenced dlls don't show path in properties window

Question: When I click on the referenced dll in my project "A" and I have my properties window open then I was expecting to see the full path of the dll and other details. For some reason I can't see those dll details in properties :(
I tried to clean/rebuild but still doesn't work. Although for my other project "B" it does work. That means there is definitely something wrong with the Any ideas?
Here is the screenshot of project "A". So I have clicked the Microsoft.CSharp dll but properties still show some other dll/project details.
Thanks

![enter image description here][2]
![enter image description here][3]
Comment: I used those DLLs for example to display that I can't see there referenced paths. Really important are those DLLs which are NOT part of .Net.
Comment: I am not sure exactly what I did - may be recompiled and closed VS and installed resharper. Now all paths are showing up.
Comment: The screenshot shows you looking at the Solution properties, not the properties of the reference.  So you either just clicked the wrong node or some kind of addin is messing with it.  Possible, "Enterprise Library 5 Assembly Set" isn't standard.
Answer: I am not exactly sure what but may be cleaning, recompiling and reopening the solution fixed the issue.


Uniform convergence of $\tan(x)^n$

Question: I am considering the uniform convergence of $(\tan(x))^n$ in the interval$[0,π/4)$. This function sequence is pointwise convergent everywhere in the given interval and converges to $0$.
 Is this function uniform convergent in the given interval? In my opinion, it is uniform convergent because the supremum of $|f_n(x)-f(x)|$ as $n$ tends to $\infty$ is $0$. Then by the $M_n$ test, we can say that the given function sequence is uniformly convergent.
Had the interval been $[0,π/4]$, the function sequence would have pointwise converged to a discontinuous function and hence been not uniform convergent.
Answer: It is not uniformly convergent. Let $x_n=\arctan (1-\frac 1 n)$. Then  $0<x_n <\frac {\pi} 4$ and $(\tan x_n)^{n}=(1-\frac 1 n )^{n} \to\frac  1 e$ so $\sup_x (tanx )^{n}$ does not tend to $0$.
Comment: Yes, it is not uniformly convergent. @HARVEERRAWAT
Comment: Does this mean that $x^n$ is not uniformly convergent in the interval $[0,1)$?

Uniform convergence of $\tan(x)^n$


enviar a variavel de javascript para php

Question: Eu tenho esta variavel sum1 em javascript e gostaria de a enviar para o php como posso fazer isto ?
JS
var sum1 = 0.0;
$('.class_nao_pago').each(function()
{
    sum1 += parseFloat($(this).text());

PHP
echo $sum1

Comment: submit ou ajax.
Answer: Você só vai conseguir fazer isso se chamar uma página via AJAX (por post ou get) ou então criar um form na sua html principal que envia esta variável para uma página PHP.
Essa integração que você esta tentando realizar não tem como acontecer.
Veja este exemplo:
var sum1 = 0.0
$('.class_nao_pago').each(function()
{
    sum1 += parseFloat($(this).text());
});

$.post('URL da página PHP', {'soma':sum1})
.done(function(data){
//callback
});

Ou por GET
var sum1 = 0.0
$('.class_nao_pago').each(function()
{
    sum1 += parseFloat($(this).text());
});

$.get('URL da página PHP', {'soma':sum1})
.done(function(data){
//callback
});


Função buscar texto

Question: Qual a forma correta para buscar texto na página?
Estou desenvolvendo uma "única" pagina em HTML e gostaria de um campo de busca ao digitar encontrar o texto, semelhante ao que acontece hoje com o CTRL+F, gostaria de manipular o campo encontrado com css.
Comment: Não entendi a parte do html puro, está buscando uma solução usando somente html?
Comment: É só para entender onde estou programando.
Answer: Apenas com HTML não dá. O HTML apenas renderiza componentes no navegador.
Se topar usar ao menos JavaScript, essa pergunta no S.O. ingles faz o que vc precisa.
JQuery search in static HTML page with highlighting of found word.
Comment: Sim irei implementar outras linguagens porem surgiu esse impasse no momento assim que eu chegar em casa irei analisar desde já obrigado pela resposta.

Função buscar texto