PyBrain so slow

Question: When I train a simple neural net using all the defaults it takes very long (I have played around with changing some of the defaults to little success).
Are there any tricks I am missing with PyBrain, or implementation of neural networks in general?
My dataset has has 100,000 observations, with one feature (covariate) and a binomial response ([0,1]).
<code>example code:
    net = buildNetwork(1, 1, 1, bias = True)

    ds_train = SupervisedDataSet(1, 1)
    ds_train.addSample(x,y)

    trainer = BackpropTrainer(net, ds_train)

    trainer.train()
</code>
I was actually using this as a test case for the larger regression I am looking to do which will have 20 features. Right now it seems that pybrain is too slow and I'm currently looking into Theano, is this a good idea?
Comment: At first sight, this just looks like a Python-related issue. Give us more information on your dataset and the statistical question you are trying to answer, and this will be on-topic on CV.
Answer: Former developer of PyBrain here. I programmed arac a few years back and have moved away from using PyBrain about 3 years ago.
PyBrain does not make use of mini batches; if your data set is of size 100'000, there will be a python for loop doing 100'000 iterations--and that is quite slow.
I do recommend to use Theano instead. Arac will make it better, but Theano will probably always be faster.
Comment: Well, that pretty much answers that :-) Thanks for weighing in!
Answer: I started writing an answer suggesting that you might be having convergence problems. If your one feature is only weakly predictive of the outcome variable, then it might take many iterations for the network to converge (or it might not converge at all, and training would only stop due to some some other criterion).  However, if you're actually calling BackPropTrainer.train(), then that only performs a single epoch of training, so that is probably not the issue.
There are some things in Python that I find surprisingly slow (like the new Collections!), so you may want to profile your code (see Python docs), or ask for suggestions on StackOverflow.
PyBrain also has a "high-performance" module called arac that moves a lot of the computation into C++. I've never used it, but they claim to get considerable speed-ups and it might involve minimal changes to your existing code.

PyBrain so slow


linux kernel option to set sata disk to udma/133 1.5gbps

Question: i try to speed up boot time of my linux server box which uses
removable HDD rack's
the current boot time is around 2 min's but if i connect the hdd's directly to the mainboard
its about 2 sec's
the problem is that ahci's kernel implementation causes a timeout of around 30 seconds for each disk during boot which originates from the hdd-rack
after the timeout the kernel prints that the disk is limited with speed to 1.5gbps and udma/133 is used
so the question i have is:
how can i set this in grub as a boot option so the kernel doesnt have to wait for a timeout
and just hardcoded limits the speed of the disks? i read about a few options like pci=nomsi
or such, which dont work
thats why im asking for limiting precisely the disks during boot
thx
Comment: this question is fine for here, but may get better responses on Server Fault.  please don't crosspost it there; it will be migrated automatically if necessary.  if it is migrated, you need to register on Server Fault and associate your accounts to regain ownership of the post.
Comment: Is the ACHI timeout a BIOS or Linux kernel issue?
Answer: Add this
<code>libata.force=1.5
</code>
to your boot options and it will force libata to 1.5Gbit. You can also force DMA modes etc, check out kernel-parameters.txt in your kernel documentation directory (or online say here)


Variance-covariance matrix of the residuals of an object of class merMod (R package lme4)

Question: I am trying to extract the variance-covariance matrix of the residuals of a generalized linear mixed-effects model that was fitted using lmer (of the R package lme4), but this does not seem to be straightforward. Does anybody knows how this can be done?
Thanks,
Regards,
Willem
Comment: This question appears to be off-topic because it is about how to do something in R. It would be better to ask this on a list devoted to R or lme.
Answer: As stated here, we usually do not need to estimate the variance-covariance matrix of the error term (or residuals, in the sense of latent outcome) in generalized linear mixed models:

The variance-covariance matrix of the residuals, $ε$ or the condition
  covariance matrix of $y|X\beta+Z\gamma$. The most common residual
  covariance structure is
$$R=I\sigma^2_ε$$ where $I$ is the identity matrix (diagonal matrix of
  1s) and $\sigma^2_ε$ is the residual variance. This structure assumes
  a homogeneous residual variance for all (conditional) observations and
  that they are (conditionally) independent. Other structures can be
  assumed such as compound symmetry or autoregressive.

Take binary data for an example, for logit link function, $\sigma^2_ε=\pi^2/3$ as the error comes for standard logistic distribution; for probit link, $\sigma^2_ε=1$ as the error comes from standard normal distribution.


howto get the selectionChanged signal

Question: Hi I am developing a plugin for Qgis in python, I need to connect the sselectionChanged signal emitted when a feature of the layer is selected, I could not find any examples on internet, here is what I have done as far
QObject.connect(self.iface.mapCanvas(),SIGNAL("selectionChanged(QgsMapLayer)"), self.test)

on the log of qgis  I get this warning
Warning: Object::connect:  (receiver name: 'MainWindow')

Answer: What you have to do is to create a signal every time you select a layer:
def initGui(self):
    # ... your other code here
    self.handler = None
    self.selected_layer = None
    QObject.connect(self.iface,SIGNAL("currentLayerChanged(QgsMapLayer *)") ,self.layerChanged)

def layerChanged(self, layer):
    if self.handler:
        QObject.disconnect(self.selected_layer, SIGNAL("selectionChanged()"),self.select_changed)
        self.handler = False
        self.selected_layer = None
    if layer is not None:
        if layer.isValid():
            QObject.connect(layer,SIGNAL("selectionChanged()"),self.select_changed)
            self.selected_layer = layer

def select_changed(self):
   # whatever
   pass

edit: disconnect(wrong layer) fixed

howto get the selectionChanged signal


wkwebview evaluate javascript click on nav bar title

Question: https://enquiry.indianrail.gov.in/mntes/. I have tried various ways to click on the "Live Station Info" in the nav bar buttons. I am new to javascript. Is this the right way to click on the button?
enter image description here
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
   webView.evaluateJavaScript("document.getElementsByClassName('nav-link')[1].click();

Answer: It's OK. Only it's not robust enough, since the index of the item might change in the future. It would be better to add a unique ID or another custom attribute, so that you can identify the item safely. Or you can directly call the onMenuItem method, instead of clicking the item, as follows.
Also, you will need to prevent the code from executing again and again, since webView:didFinish: will be called again after you click the item, since the page will be reloaded.
var liveStationClicked = false

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

    if !liveStationClicked {
        liveStationClicked = true
        webView.evaluateJavaScript("if (onMainMenu) onMainMenu('liveStation','');");
    }
}


Replacement Preamp for Yamaha APX 8D

Question: My Yamaha APX 8D's preamplifier is broken.
Does anyone know a good replacement?
The guitar has a piezo pickup and a microphone.
There are potentiometers for volume, treble, bass and a 9V battery compartment.
I would like to keep the pickups in place and simply use a replacement preamplifier.It would be great if I could leave the potentiometers as they are.
I asked several workshops, but they always wanted to replace everything.
I don't have a soldering station at the moment, but I know how to do it.
Comment: "I asked several workshops, but they always wanted to replace everything." Of course they do. It's quicker, cheaper, more reliable, and easier to give you a guarantee that the complete package works and will stay working for years. If you really want to a "pick and mix" solution, either learn to do it yourself, or find a specialist - and if they are any good, you will be paying "specialist" prices. (If they are cheaper than a "workshop" quote, then run away before you discover you have thrown your money down the drain...)
Comment: I don't really care about the pickups. The guitar has this mini-invasive thing which can be seen here https://goo.gl/images/UwWbGy and another poti close to the neck. The battery comportmant is a bit further down on the body. So replacing the preamp with a fishman e.g. would create another hole to the body.
Maybe I should just find somone who can resolder the caps or just get a pickup wired to the plug and use an external preamp
Comment: I think there may be an issue here in that the existing pots etc. may not be perfectly compatible with the circuit designed for the new system.  They might be, they might not be. If you can determine the specs of all the components, and decide they are compatible, you might be able to e.g. cut some wires and splice the old parts in.
Answer: You will have to do some research.  You will need to find out the part number for the pre-amp in the assembly. It is possible the pick up system is in the service manual for the instrument, but likely not, as manufacturers will change what system they are using on a model and often don't include them in the manual.
I would start by calling Yamaha and seeing if you can get the part numbers directly from them: (888) 892-6242
You can order the service manual from Yamaha here: https://usa.yamaha.com/support/parts_manuals/index.html, and parts at https://www.yamaha24x7.com, although it requires web site registration (just an e-mail address really)
I checked the parts site for your guitar model since I have a log in, and didn't see the pick-up listed, just the regular guitar body parts (tuners etc.)
You may have to call Yamaha and find out what manufacturer made the pickup system and get the part numbers and possibly replacement part directly from the pick-up manufacturer.
In some cases when a guitar model hasn't been made for a few years it is impossible to find a direct replacement. I have been able to replace pre-amp boards with non-stock boards with some clever rebuilding, but that may not be a project you want to undertake.
Comment: Okay, I've also checked the customer's website and it looks like they're only supplying mechanical parts, but not replacements for preamplifiers and pickups. That is a really sad policy. I guess it will be cheaper to get a good replacement guitar instead of repairing the Yamaha. So I should get rid of these sentimental feelings about the first E-acoustics, which I bought at the age of 18, for about $600 USD - that was a lot of money for me when I was just starting at university. Maybe I'll try to fix it myself by re-soldering the capacitors - if I have time in my late sixties. :-)
Comment: I couldn't find the details on the pickup(s) that model has, but it would likely be worth your time to bypass the built in pre-amp system all together.  Assuming it has a piezo under-saddle pickup, you could connect that to something like an end pin pre-amp unit with minimal time and effort, giving you amplification again. It wouldn't have the same sound as the original pre-amp, but would bring the guitar back into use. The end pin pre-amps range in price and quality, starting at about 10USD, up to hundreds for Brand Name versions.
Comment: Finally I got it fixed by letting add a replacement preamp from fishman inside sound hole and reusing the battery box. The old control knobs are still there, out of order, but at least there is no new hole in the body now.
Answer: For the give price range I would typically suggest something like:

universal audio 710 twin-finity (costs around 700 dollars)

watch a demo of it here:
Comment: Neat tool - I shure will get that :-)

Replacement Preamp for Yamaha APX 8D


C++ fmtlib: "Undefined reference" error after building and #include <> this library

Question: I downloaded the library from https://github.com/fmtlib/fmt and then executed the following commands from official documentation https://fmt.dev/latest/usage.html:
mkdir build
cd build
cmake ..
sudo make install

The commands were executed without errors. The final output of the sudo make install command:
Install the project...
-- Install configuration: "Release"
-- Installing: /usr/local/lib/libfmt.a
-- Installing: /usr/local/include/fmt/args.h
-- Installing: /usr/local/include/fmt/chrono.h
-- Installing: /usr/local/include/fmt/color.h
-- Installing: /usr/local/include/fmt/compile.h
-- Installing: /usr/local/include/fmt/core.h
-- Installing: /usr/local/include/fmt/format.h
-- Installing: /usr/local/include/fmt/format-inl.h
-- Installing: /usr/local/include/fmt/locale.h
-- Installing: /usr/local/include/fmt/os.h
-- Installing: /usr/local/include/fmt/ostream.h
-- Installing: /usr/local/include/fmt/printf.h
-- Installing: /usr/local/include/fmt/ranges.h
-- Installing: /usr/local/include/fmt/xchar.h
-- Installing: /usr/local/lib/cmake/fmt/fmt-config.cmake
-- Installing: /usr/local/lib/cmake/fmt/fmt-config-version.cmake
-- Installing: /usr/local/lib/cmake/fmt/fmt-targets.cmake
-- Installing: /usr/local/lib/cmake/fmt/fmt-targets-release.cmake
-- Installing: /usr/local/lib/pkgconfig/fmt.pc

I next created the file main.cpp with the following content:
#include <fmt/core.h>

int main()
{
    fmt::print("Hello");

    return 0;
}

And compiled it with the command g++ main.cpp -o main.
However, the compilation results in the following error:
/usr/bin/ld: /tmp/ccJ3FzHH.o: in the function «main»:
main.cpp:(.text+0x8a): undefined reference to «fmt::v8::vprint(fmt::v8::basic_string_view<char>, fmt::v8::basic_format_args<fmt::v8::basic_format_context<fmt::v8::appender, char> >)»
collect2: error: ld returned 1 exit status

I am using Ubuntu 20.04
Comment: Did you link it? add `-lfmt`
Comment: `g++ main.cpp -lfmt -o main`
Answer: Adding the argument -lfmt to the compilation command solves the issue.
-l<name> arguments generally stand for including the library <name> into the compilation (see GCC documentation)
The command thus looks as follows:
$ g++ main.cpp -lfmt -o main


Handling '#' in Request URI in Apache Rewrite Rules

Question: It looks like Apache Rewrite Rules are ignoring the '#' in the Request URI.
I want to rewrite the following Request
hptt://localhost/app_name/#Place=abc
to
http://localhost/app_name/#/#ID=abc
And here are the Rules i have tried so far and none of them worked.
RewriteEngine on

  # Rule 1
  RewriteCond %{HTTP_REFERER} %{HTTP_HOST}/app_name/#Place=(.*)$ [NC]
  RewriteRule ^app_name/#Place=(.*)$ /app_name/#/#ID=$1 [R,L]

  # Rule 2
  RewriteCond %{QUERY_STRING} ^#Place=(.*)$ [NC]
  RewriteRule ^app_name/#Place=(.*)$ /app_name/#/#ID=$1 [R,L]

When i tried Rule 1) at http://martinmelin.se/rewrite-rule-tester/ it is working as expected. How ever my local apache is not rewriting the rule
Thanks
Comment: You can't match `#` in a rule. It's not sent to the server. It's only seen by the client (your browser). You can't redirect based on that having that in your URL.
Answer: Fragments are not sent in the HTTP Request Messages by web browser. It's pointless to try work with them in an server side.
Answer: Maybe the apache not allowed overwrite rules with .htaccess.
in case you are on ubuntu edit the file /etc/apache2/apache2.conf
<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

and change it to
<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>

then restart apache
sudo service apache2 restart

Comment: No The Rules are being applied as i can see them in the log (As i set the logging level to 9). How ever none of them are matching and hence the request is getting passed through


The nature of variables within proofs

Question: I am confused about how best to view certain kinds of variables that show up in the course of an elementary proof. For example, to prove that the square of every odd integer is odd, I would write:
Let $m \in \mathbf{Z}$ be arbitrary. Suppose $m$ is odd. Choose $k \in \mathbf{Z}$ such that $m = 2k + 1$. Then $m^2 = (2k + 1)^2 = 2(2k^2 + 2k) + 1$, so since $2k^2 + 2k \in \mathbf{Z}$, it follows that $m^2$ is odd.
The symbol $m$ is introduced as part of the technique of universal generalization; Velleman [1] describes this step as "introducing a new variable [$m$] ... to stand for an arbitrary object." The symbol $k$ is introduced as part of the technique of existential instantiation; [1] describes this as "introducing a new variable [$k$] to stand for an object for which [the predicate $m = 2k + 1$] is true."
In what sense are $m$ and $k$ variables? They do not seem to be bound variables, as they are in the scope of no quantifier. They also can't be free variables, because if they were, then, for example, the sentence being proved true after the introduction of arbitrary integer $m$ -- namely that if $m$ is odd then $m^2$ is odd -- would be a predicate and not even have a truth value; I am also obviously not free to substitute values into $m$ and $k$, if for no other reason than $m$ and $k$ are dependent.
Stoll [2] says a variable is free if it is not bound, so there is no third option.
Is it more correct to think of the phrases "let $m \in \mathbf{Z}$ be arbitrary" and "choose $k \in \mathbf{Z}$ such that ..." as introducing new constants rather than variables, as their values are fixed despite being unspecified ($m$) or unknown ($k$)? More generally, the idea of a symbol that stands for a particular but arbitrary element of some set seems incompatible with the typical description of a variable as a placeholder as seen in, e.g., Epp [3].

[1] Velleman, D. (2006). How to Prove It: A Structured Approach (2nd ed.). Cambridge: Cambridge University Press.
[2] Stoll, Robert Roth (1963). Set Theory and Logic. W.H. Freeman.
[3] Epp, Susanna S. Variables in Mathematics Education. https://condor.depaul.edu/~sepp/VariablesInMathEd.pdf
Comment: See [this](https://math.stackexchange.com/questions/3822741/logic-justification-for-the-use-of-let-y-in-existential-proof) very similar post as well as [this one](https://math.stackexchange.com/questions/3799062/basic-question-about-proofs-with-the-goal-exists-x-px)
Answer:
In what sense are $m$ and $k$ variables? They do not seem to be bound variables, as they are in the scope of no quantifier.

Actually every time you say something like "let $m \in \mathbb{Z}$ be arbitrary" the word "arbitrary" is code for an implicit universal quantifier $\forall m \in \mathbb{Z}$, in this case part of the statement
$$\forall m \in \mathbb{Z} : \left( \exists k \in \mathbb{Z} : 2k+1 = m \right) \Rightarrow \left( \exists k' \in \mathbb{Z} : 2k'+1 = m^2 \right)$$
you are trying to prove. So it is a bound variable, bound to a quantifier which is being left implicit. This is a very common convention in mathematics which is usually not described explicitly. Then we appeal to a general principle about how to prove a result involving a universal quantifier, which I guess is called universal generalization: to prove $\forall m, P(m)$ you introduce $m$ as an arbitrary variable and write down a proof where you assume nothing about $m$ except whatever premises might be in the statement $P(m)$ and see if you can deduce the desired conclusion.
Comment: @Cole: unfortunately I've never seen this explained anywhere in writing (not that I've tried to look). Again, it's the sort of thing which is usually left implicit. One picks it up "by osmosis."
Comment: Is there a book you could recommend that expands on this? I've never seen proof methods described this way.
Comment: @ColeArora: It is easy once you learn a Fitch-style deductive system such as [this one](https://math.stackexchange.com/a/1684204/21820), where this proof method is simply creating a ∀subcontext ("Given m∈ℤ:") and proving the desired statement ("m is odd ⇒ m^2 is odd.") under that, and then coming back out and using ∀intro to get the desired theorem "∀m∈ℤ ( m is odd ⇒ m^2 is odd ).".
Comment: Also, note that if you want to stay within idiomatic English, you should not use the bare "let" for ∀subcontexts. The one you cited is still alright because of the word "arbitrary", but if you omit that then you would be simply using incorrect English. In contrast, the "let/choose k∈ℤ such that m = 2k+1" is an ∃elim step, for which "let" is correct. See [this](https://matheducators.stackexchange.com/a/18155/1550) for details.
Answer: During a proof, there are two things present at any point in time:

the thing(s) you want to proof right now (which I will call the goal(s) )
and the things you are assuming right now, the things you can use to continue in your proof (referred to as the context).

Let's go through the proof you want to do, keeping track of both the context on the left and the goal on the right.
At the start we have
$$
\boxed{\begin{array}{c|c}
\text{Context} & \text{Goal} \\
\hline
 & \hspace{1em} \forall m \, (m \text{ is odd } \Rightarrow m^2 \text{ is odd})  \hspace{1em}
\end{array}}
$$
So our goal is something of the form $\forall x \, \varphi(x)$. How do we show this in general?

We can conclude $\forall x \, \varphi(x)$ from the context $\Gamma$ if we can show $\varphi(y)$ for a variable $y$ which does not appear as a free variable in either the context $\Gamma$ or $\varphi(x)$.

In our case $y$ would actually satisfy this and thus we get a new goal
$$
\boxed{\begin{array}{c|c}
\text{Context} & \text{Goal} \\
\hline
 &  \hspace{1em} y \text{ is odd } \Rightarrow y^2 \text{ is odd}  \hspace{1em}
\end{array}}
$$
Why is it fine to simply get rid of the quantification and replace $m$ with $y$? Well, we did not simply get rid of the quantification. We had to make sure that $y$ is not free in the context and the right side! This condition assures that the context can not have any information about the variable $y$ for us. So we are not assuming anything about $y$, we know nothing about it and thus $y$ can truly be considered to be anything/general. And so if we show the right side for a variable we can consider general, the argument is that we have shown $\forall m [\dots]$.
Now let's continue with the proof. To show the implication you assume whats on the left and try to show whats on the right.
$$
\boxed{\begin{array}{c|c}
\text{Context} & \text{Goal} \\
\hline
\hspace{1em}  y \text{ is odd }  \hspace{1em} &
\hspace{1em}  y^2 \text{ is odd} \hspace{1em}
\end{array}}
$$
In order to continue we need to write out the definition of odd
$$
\boxed{\begin{array}{c|c}
\text{Context} & \text{Goal} \\
\hline
\hspace{1em} \exists k \, (y = 2k + 1) \hspace{1em} &
\hspace{1em} \exists k \, (y^2 = 2k + 1)  \hspace{1em}
\end{array}}
$$
Now at this point you can apply existential instantiation on the statement $\exists k \, (y = 2k + 1)$ in your context. What happens here is that you are allowed to replace $\exists k \, (y = 2k + 1)$ by $(y = 2z + 1)$ for any variable $z$ that does not appear free in your context and goal. Similarly to before, this now makes sure that the only thing you know about $z$ is that it satisfies $y = 2z + 1$. So we get
$$
\boxed{\begin{array}{c|c}
\text{Context} & \text{Goal} \\
\hline
\hspace{1em}  y = 2z + 1 \hspace{1em} &
\hspace{1em} \exists k \, (y^2 = 2k + 1) \hspace{1em}
\end{array}}
$$

This explanation is basically a verbalization of some of the rules for natural deduction, which is a formal way of describing proofs. So if you haven't yet and really want to learn more about proofs in detail, this would be a topic to get into; although it's a deep dive.
Comment: This is well-explained. I ended up putting a pause on Velleman's _How to Prove It_ to go through the more elementary _Introduction to Formal Logic_ (2e) by Peter Smith, which focuses on natural deduction, and it has been helpful in understanding Velleman in particular and informal mathematical proofs in general.
Comment: @ColeArora Ah, I'm a big fan of Smith's books! I don't think I could give you any better recommendation.
Answer: $m$ is a variable in that its value is not fixed, but due to the relation between $m$ and $k$ once you fix one of them you determine the value of the other (and $m$ must be odd). You are not proving the statement for particular constants but for arbitrary ones, which is to say, variables.
Answer: universal generalization: "for all odd $m \in \Bbb{Z}$".
existential instantiation: "there exists a $k \in \Bbb{Z}$ such that $m = 2k+1$".
These are both quantified and they are quantified in the way you recite.
It is more accurate to think of variables as variables.  A statement with a universally quantified variable may be specialized, removing the universal quantifier, by replacing the occurrences of the variable with a particular member of the set from which that variable is drawn.  For instance, in your proof, an equally valid set of statements is produced by replacing every instance of $m$ by "$3$" (an odd integer).  Existentially quantified variables can be specialized to the value that satisfies their constraints.
When $m$ is generic (free to range over the odd integers), $k$ must be generic, since the value of $k$ is dependent on the value of $m$.  (In a more pedantic setting, the dependence of $k$ on $m$ would be made more apparent by writing, for instance $k(m)$, $k_m$, or some other syntax to indicate dependency.  This dependency enforces an order on the quantifiers.  Equivalently, the order of the quantifiers, $\forall m \text{ odd}, \exists k \in \Bbb{Z} \dots$.)  Even though $k$ is generic, in this case, we can solve for $k$ in terms of $m$: $k = \frac{m-1}{2}$.  Consequently, throughout, we may specialize the variable $k$ to the value $\frac{m-1}{2}$.
When $m$ is specialized to a value, we may replace $k$ with the value that is half of one less than the value of $m$.  We still end up with a valid set of statements -- this valid set of statements is the explicit proof of the oddness of the square of whatever value $m$ has taken.  This last should make it clear: $m$ and $k$ are variables.  For each specialization of $m$ and $k$ to (valid) values, we obtain a concrete proof.  If we do not specialize, we obtain a proof that is universally quantified over $m$ and existentially quantified over $k$ (which is dependent on $m$).
Comment: @ColeArora : "it is more like multiple proofs are running in parallel -- one per specialization of the arbitrary object" -- this much is exactly right.  If it turns out that the proof works for all possible specializations, then the proof works when the variable that is specialized is universally quantified.  When one writes "Let $x$ be an arbitrary number", one is asserting $\forall x \in \text{numbers}$, so of course the subsequent assertion "$x < 3$", with $x$ a free variable, is interpreted as "$\forall x \in \text{numbers}, x < 3$", with $x$ universally quantified.
Comment: This is helpful, but I still have some confusion. Here's a simpler example: In the sentence "$x < 3$", $x$ is considered a free variable, and the sentence is a predicate and thus has no truth value; we are free to substitute a value for $x$ to produce a proposition. But if we precede this sentence by "Let $x$ be an arbitrary number", the meaning of $x$ in "$x < 3$" seems to change, and I don't get precisely what changes -- we now apparently have a proposition despite $x$ being generic. In the latter case, is the truth value of the proposition $x < 3$ the same as that of $\forall x(x < 3)$?
Comment: In other words, even though we manipulate an arbitrary element in the proof body as though it were a single object, it is more like multiple proofs are running in parallel -- one per specialization of the arbitrary object.
Answer: You say:  "They also can't be free variables, because if they were, then, for example, the sentence being proved true after the introduction of arbitrary integer $m$ -- namely that if $m$ is odd then $m^2$ is odd -- would be a predicate and not even have a truth value."  I would say this a little differently.  A predicate does not have a truth value until values are assigned to the free variables.  But if you assign values to the free variables, then a predicate has a truth value.
Now, let me suggest a slightly different version of Lereau's answer.  I like the idea of distinguishing between context and goal, but I would say that the context consists of two things: a specification of which variables are assumed to have values assigned to them, and a specification of which statements are assumed to be true (these are called "givens" in my book).  With this modified version of Lereau's idea of context, let me go through the proof.  We start with:

Context:  empty; that is, no variables are assumed to have values and no givens are assumed to be true
Goal:  $\forall m(m \text{ is odd} \Rightarrow m^2 \text{ is odd})$

When you write "Let $m \in \mathbb{Z}$ be arbitrary," you change the situation to:

Context: variables: $m$; givens: none
Goal:  $m \text{ is odd} \Rightarrow m^2 \text{ is odd}$

So now you are assuming that $m$ stands for something (so the goal, which contains $m$ as a free variable, has a truth value), but you are making no assumption about what $m$ stands for, so it could be anything.  Now you assume $m$ is odd:

Context: variables: $m$; givens: $m$ is odd
Goal:  $m^2$ is odd

Writing out the definition of "odd", this means:

Context: variables: $m$; givens: $\exists k \in \mathbb{Z}(m = 2k+1)$
Goal:  $\exists j \in \mathbb{Z}(m^2 = 2j+1)$

Now since the given is an existential statement, we can introduce the variable $k$  to stand for an integer such that $m = 2k+1$:

Context:  variables: $m$, $k$; givens:  $m = 2k+1$
Goal:  $\exists j \in \mathbb{Z}(m^2 = 2j+1)$

Now $m$ and $k$ are both assumed to have values assigned to them, and the statement $m = 2k+1$ is assumed to be true with those values assigned.  Now it is just simple algebra to come up with the value of $j$ that demonstrates that the goal is true.
Comment: I agree with this! Please see my comments on the other post starting from [here](https://math.stackexchange.com/posts/comments/9833042). In particular note how the Fitch-style subcontexts can precisely capture what you are referring to here. Also note that your mental version requires creating a new subcontext for every ∃elim, instead of how it is done in my linked system. These are two kinds of Fitch-style systems. From my experience, the kind I chose is better (despite the slight increase in complexity) as it is actually usable for actual mathematics way beyond toy logic problems.

The nature of variables within proofs


Problem Box-Cox Transformation on Multiple Linear Models

Question: When I use the command bcskew0 in Stata and I compare with the command boxcox of MASS library outputs in R, there's a massive difference.
Here are my data:
tempo <- c(61, 43, 35, 32, 60, 32, 69, 63, 62, 66, 49, 69, 50, 67, 67, 35, 62, 42, 38, 47, 65, 49, 30, 52, 55, 56, 58, 66, 33, 34, 66, 33, 60, 70, 55, 62, 34, 32, 53, 52, 61, 43, 35, 32, 60, 32, 69, 63, 62, 66)

dist <- c(34, 36, 18, 22, 40, 24, 40, 40, 40, 38, 36, 40, 40, 40, 38, 12, 40, 38, 40, 38, 38, 38, 18, 38, 38, 38, 38, 40, 18, 20, 38, 32, 38, 38, 38, 38, 28, 36, 40, 40, 34, 36, 18, 22, 40, 24, 40, 40, 40, 38)

sem <- c(11, 3, 3, 9, 16, 0, 13, 19, 11, 16, 5, 18, 15, 19, 12, 5, 11, 3, 16,  7, 12, 11, 3, 9, 10, 11, 11, 17, 8, 5, 14, 7, 12, 16, 15, 12, 1, 9, 15, 15, 11, 3, 3, 9, 16, 0, 13, 19, 11, 16)

On Stata, I've tried:
reg tempo dist sem

Then:
bcskew0 bctempo = tempo

And finally:
reg bctempo dist sem

On Stata, the Box-Cox transformation reports that the lambda value was 2.6486.
Now the R commands and outputs
model <- lm(tempo ~ dist + sem, database)
library(MASS)
bc <- boxcox(model, lambda = seq(-3,3))
opt.lambda <- bc$x[whitch(bc$y == max(bc$y))]

Then I'm using the value of opt.lambda object to transform my dependent variable. But, even so, the Stata lambda value is very different from the R lambda value.
Could anyone help me to understand the differences in outputs?
Comment: Is `whitch()` correct or a typo?
Answer: You are not comparing like with like.
In Stata the results of bcskew0 depend on what you give it, just the marginal distribution of tempo as a single variable. That is not presented in conjunction with any predictors.
tempo is slightly left-skewed. bcskew0 suggests a transformation with a power of 2.65, which out of context sounds quite a strong transformation.
----------------------------------------------------------------------------
                     n = 50 |       mean          SD    skewness    kurtosis
----------------------------+-----------------------------------------------
(tempo^2.648597-1)/2.648597 |  14923.004    8653.249      -0.000       1.563
                      tempo |     51.740      13.465      -0.327       1.590
----------------------------------------------------------------------------

So, positively, results show that bcskew0 does achieve what you ask of it, which is to produce a zero skewness transform.

But a plot (above) shows that given the limited range of tempo the transformation isn't a big deal.
On this evidence, I wouldn't transform tempo at all. I don't know what tempo means or measures, but I have no reason to believe that a power of 2.65 makes more sense than the original scale of tempo. The reduction in skewness does not seem even a compensating benefit for the loss of easy interpretation. In any case I don't much mind about marginal distributions out of context of the model I am seeking.
boxcox() in R by comparison is looking at the entire dataset, of a response and two predictors. Here the game is quite different,  whether a transformed scale would be a better story for the relationship between response and predictors. From plots of the response and the predictors separately, the relationship with dist seems particularly odd, which needs some kind of story, but regress results overall in Stata don't seem too bad.

In Stata it would be boxcox that you would use to try to go further. bcskew0 can't help directly with looking for a better model. Otherwise put, a transformation that "helps" with distribution shape isn't necessarily one that helps with a predictive relationship.
Comment: Thank you so much for your time!

I was trying to figure out the difference between the outputs (Stata anda R), and now I did.

The database is fictitious and has educational purposes only.

Could you tell me, please, if you know a R command that returns this outputs in a similar way to Stata?
Comment: Sorry, but I don't use R enough to advise. Stata I use more.
Comment: Thank you anyway (:


A case of import module from subdirectory - why does it work?

Question: I have a code from a friend (who works on Ubuntu) that is structured like this (no init.py files!):
BaseFolder
|-SubFolder1
  |- file1.py
  |- file2.py
|-SubFolder2

In file1.py there is an import:
from SubFolder1.file2 import func

She says it works when she runs the file1 from the BaseFolder. It doesn't works for me on Windows though; I read that the solution without any changes to either structure or files is to add path to the PYTHONPATH variable, but my question is if it is typical for Linux or she had modified the path?
Thanks in advance :)
Answer: Ok, I found the infomation concerning that - she probably stores the whole tree in a subdirectory of the working directory (the base Python dir) :)


Disabling space bar triggering click for JButton

Question: JButtons consider pressing the space bar to be the same as clicking on the JButton (assuming the JButton has the focus, which I am assuming here). Is there a way to turn off this behavior so they ignore pressing the space bar?
Also, more generally, is there a technique for doing this with AbstractButtons?
Comment: I thought your question was about buttons plural. It is not a very good UI to have some buttons work with the space bar and some not. So why would you want to change buttons one at a time?
Answer: You can disable it by doing
jbutton.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "none");

This seems to work for other AbstractButtons as well, such as JRadioButtons.
As @camickr points out below you can solve it for all JButtons in one go as follows:
InputMap im = (InputMap)UIManager.get("Button.focusInputMap");
im.put(KeyStroke.getKeyStroke("pressed SPACE"), "none");
im.put(KeyStroke.getKeyStroke("released SPACE"), "none");

Answer: The link given by aioobe shows how to do it for an individual button. If you want to do this for all JButton's you would do:
InputMap im = (InputMap)UIManager.get("Button.focusInputMap");
im.put(KeyStroke.getKeyStroke("pressed SPACE"), "none");
im.put(KeyStroke.getKeyStroke("released SPACE"), "none");

If you want to do it for check boxes and radio buttons you would need to repeat the above for each different input map.
You may want to read Enter Key and Button. It actually does the opposite of what you want since it explains how to invoke the button when the Enter key is used. But it may help explain why this solution works in reverse.
Answer: Spacebar on keyup may activate last focused element. To defocus the element try:
${element}.blur()

Answer: use:
button.setFocusable(false)
this way, the button can only be clicked using the mouse and not the space bar.


Span of union of subspaces

Question: I was reading a proof in my linear algebra notes, and it says:
Let $U, W$ be subspaces of $\mathbb{R}^3$, $U = \text{span}\{(1,0,1), (0,1,1)\}$, $W = \text{span}\{(1,1,0), (0,1,1)\}$
Then it goes on to say $\text{span}(U \cup W) = \text{span} \{ (1,0,1), (0,1,1), (1,1,0) \}$
Why does the span of the union of $U$ and $W$ equal the span of the union of the sets that span $U$ and $W$?
Answer: One direction is clear.  For the other direction, let $v\in$span$(U\cup W)$.  Then we may write $$v=a_1u_1+a_2u_2+\cdots+a_ku_k+b_1v_1+b_2v_2+\cdots+b_jv_j$$
where the $a_i, b_i\in\mathbb{R}$, $u_i\in U$, and $v_i\in W$.  But then we observe that
$$a_1u_1+a_2u_2+\cdots+a_ku_k\in U$$
and
$$b_1v_1+b_2v_2+\cdots+b_jv_j\in W$$
so indeed $v$ is the sum of a vector in $U$ and one in $W$.  But each vector in $U$ is the linear combination of  your three spanning vectors, as is each vector in $W$.  Hence $v$ is as well.

Span of union of subspaces


MySQL keeps restarting due to running out of memory

Question: how can we prevent this from happening? it generally causes down time of about 30 minutes, which is extremely disruptive for service...
Comment: Can you give a bit more data about the problem? Logs and system setup would be helpful?
Answer: MySQL tag, so I'm guessing MySQL.  I've had that FUBAR an InnoDB database before.
Sounds like you do not have your configuration optimized at all.  Tuning is going to be specific to your database engine.  I provided some general recommendations in the post linked below, which would apply to you as well.
How do I set my.cnf in Mysql so that there are no limits to connections?
Comment: +1 because you're wearing a bow tie in your gravatar (and because it's a good answer)


Não consigo informar que nenhum resultado foi encontrado dentro de uma pesquisa/filtro em javascript

Question: Estou usando o código abaixo para filtrar valores dentro de uma tabela. Usava um código parecido para filtrar itens em uma lista e exibir uma div caso nenhum resultado fosse encontrado. Entretanto, não consigo exibir essa div se eu usar o código abaixo. Já tentei usar document.getElementById('not-found').style.display = 'block'; usando uma variável com valores booleanos, mas, até o momento, não tive êxito.
Como proceder neste caso?

var $rows = $('#table tr:not(:first)');
$('#search').keyup(function() {
  var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase().split(' ');

  $rows.hide().filter(function() {
    var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
    var textN = text.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
    var matchesSearch = true;
    $(val).each(function(index, value) {
      matchesSearch = (!matchesSearch) ? false : ~textN.indexOf(value) || ~text.indexOf(value);
  });

        return matchesSearch;

  }).show();

});
td, th {
  border: 1px solid #000
}

#not-found {
  display:none;
}

<input autofocus type="text" id="search" placeholder="Pesquisar...">

    Name
    Country

Nenhum resultado foi encontrado.

    Alfreds Futterkiste
    Germany

    Berglunds snabbkop
    Sweden

    Island Trading
    UK

    Koniglich Essen
    Germany

Answer: Para mostrar a primeira linha (#not-found"), você precisa saber quantos elementos o filtro retornou.
Caso esse número seja 0, basta exibir a linha #not-found.
Segue o código.

var $rows = $('#table tr:not(:first)');
$('#search').keyup(function() {
  var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase().split(' ');
 //abaixo, salvo o conjunto resultante do filtro em $found;
 $found = $rows.hide().filter(function() {
    var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
    var textN = text.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
    var matchesSearch = true;
    $(val).each(function(index, value) {
      matchesSearch = (!matchesSearch) ? false : ~textN.indexOf(value) || ~text.indexOf(value);
  });
        return matchesSearch ; //?: $("#not-found");
  });
//aqui, vejo se houve algum encontrado, o que daria $found.length > 0 e portanto, true
  if($found.length){
      //se tem pelo menos 1, exibo as linhas
      $found.show();
 } else{
     // do contrário, exibo a linha #not-found
     $("#not-found").show();
 }
});
td, th {
  border: 1px solid #000
}

#not-found {
  display:none;
}

<input autofocus type="text" id="search" placeholder="Pesquisar...">

    Name
    Country

Nenhum resultado foi encontrado.

    Alfreds Futterkiste
    Germany

    Berglunds snabbkop
    Sweden

    Island Trading
    UK

    Koniglich Essen
    Germany

Comment: @winiercape Está *quase* funcionando: digite "ad" na caixa de busca pra ver o que acontece...
Comment: @winiercape Eu acho que é só colocar `$("#not-found").hide()` dentro do `if($found.length)` (pois se encontrou alguma coisa, basta esconder esta linha)
Comment: Boa, Marcos! Realmente, não tinha pensado nessa lógica tua de colocar os valores encontrados dentro da variável `found`. Muito obrigado, cara!
Comment: Obrigado pelo aviso, @hkotsubo! Eu notei isso também. Ainda estou fazendo alguns ajustes no código, mas acredito que esse erro pode ser solucionado alterando esta linha: `var $rows = $('#table tr:not(:first)');` É isso?
Comment: Verdade! Muito melhor mesmo, @hkotsubo! Muito obrigado pelo toque!


Qual a funcionalidade do mainloop no frame do tkinter?

Question: Eu estava tentando fazer um frame aparecer na tela no tkinter, e depois de muito, tentei checar a documentação e vi o nome "mainloop", ao testar ele aparecia na tela, o que eu não entendi, já que quando chamei por meio do pack ele não funcionou, só quando coloquei esse mainloop.
(PS: Chequei se era uma instância diferente do frame, mas era a do frame)
Por favor, alguém poderia me explicar o que esse mainloop do frame faz, porque nas docs do próprio tkinter é muito incompleto.
Answer: O método mainloop é usado para "travar" a execução da janela atual usando um event loop do tkinter. Isso permite com que o tkinter possa disparar respostas a eventos na instância atual da janela que chamou o mainloop, como um keypress ou click e não permite a execução de códigos posteriores até que a janela seja fechada. Pode testar isso ao chamar o método mainloop com um código logo em seguida e verá que ele só será executado depois:
window = Tk()
window.mainloop()
# esse print não será chamado até que feche a janela que chamou o método mainloop
print('chamou')

O print chamado só é executado quando a janela atual deixar o processo de mainloop, ou seja, tiver sua instância finalizada.


NodeJS double negate ternary operator

Question: I am using ternary operator in NodeJS below shown
let err = {a: 10, message: 0}
const error = !!err.message ? err.message : err;

But above code is showing eslint error for double negation how to solve this ? below alternative is same as above
const error = err.message ? err.message : err;

Comment: `0` is falsy already, there is no need to `!!`.
Comment: Your below code looks like what you should be doing, there's no need to cast to boolean with the conditional operator, is there an error when using it?
Answer: There's no actual need to use the !! - this code is what you want:
const error = err.message ? err.message : err;

If you really wanted to check against a Boolean rather than the pure value:
const error = Boolean(err.message) ? err.message : err;

Also note that what you're doing - if err.message is truthy, use it, or use err - is the exact use case of the logical OR operator ||:
const err = err.message || err;

Answer: You can avoid the conditional operator entirely if you want - if err.message is falsey, just alternate with err:
const error = err.message || err;

NodeJS double negate ternary operator


How to access plot data of GAM (tensor product smooth) in R?

Question: I have such a GAM model with a tensor product smooth of location and time:
dat <- gratia::bird_move
dat$longitude <- dat$latitude

mod <- mgcv::gam(count ~ species + te(longitude, latitude, week, d = c(2,1), k = c(8,8)), data = dat)

I know it's possible to get the data from plot(mod) but how can I extract (and plot) data for e. g. week 48 only?
plotdata <- plot(mod)
> str(plotdata)
List of 1
 $ :List of 12
  ..$ scale  : logi FALSE
  ..$ se     : logi FALSE
  ..$ m      : num 40
  ..$ nc     : num 3
  ..$ nr     : num 3
  ..$ lo     : num [1:3] 5 5 0
  ..$ hi     : num [1:3] 60 60 52
  ..$ vname  : chr [1:3] "longitude" "latitude" "week"
  ..$ main   : chr "te(longitude,latitude,week,37.46)"
  ..$ exclude: logi [1:14400] FALSE FALSE FALSE FALSE TRUE TRUE ...
  ..$ fit    : num [1:14400, 1] 4.98 4.9 4.83 4.74 NA ...
  ..$ plot.me: logi TRUE

Comment: Lol, sorry; I just realized you were using the made-up data from the HGAM paper. The issue with TPRS is that 1 unit of Longitude isn't the same as 1 unit Latitude for a big chunk of the planet. You could just use a 3 way tensor product (`d=c(1,1,1)`) or use the tools in the sf   to project the lat lon values to a local coordinate reference system
Comment: You probably shouldn't be using a TPRS (that 2d basis) for lat and long; it would be better if your cords were in a local coordinate reference system. If the response truly is a count, fitting a Gaussian GAM probably isn't great.
Comment: @GavinSimpson This was just an example, my actual model is quite different and doesn't have count data. Hmm, I have to use lat and lon for my coordinates (or wouldn't know how to transform them). What is the problem with the thin plate regression spline there?
Answer: Typically, one one create a data frame of the input variables then run predict using these data. For example, to get a complete grid of predictions for counts of species 1 at each latitude / longitude in week 48, we could do:
pred_df <- data.frame(species = 'sp1',
                      longitude = rep(0:60, 61),
                      latitude = rep(0:60, each = 61),
                      week = 48)

pred_df$count <- predict(mod, newdata = pred_df,
                         terms = "te(longitude,latitude,week)")

To print this we could use ggplot and geomtextpath:
library(geomtextpath)

ggplot(pred_df, aes(longitude, latitude)) +
  geom_raster(aes(fill = count), interpolate = TRUE) +
  geom_textcontour(aes(z = count,
                       label = ifelse(after_stat(level) < 0,
                                      paste0('\u2010', abs(after_stat(level))),
                                      after_stat(level))),
                   family = 'serif') +
  scale_fill_gradientn(colours = c('blue4', 'orange', 'yellow', 'white')) +
  coord_cartesian(expand = FALSE) +
  theme_minimal(base_size = 16) +
  ggtitle('Relative effect of latitude\nand longitude on counts at week 48')

Comment: @ecr right; but it's easy to fix. Add `terms = "te(longitude,latitude,week)"` to the `predict()` call (and be sure to be running the latest version of mgcv 1.8-41) and you'll get the "partial" effect on the link scale for the named smooth.
Comment: See my update, incorporating the suggestion by @GavinSimpson
Comment: Looks great but this seems to be the overall prediction (based on all predictors) and not the partial effect of the time/space smooth?


Is it correct to say that $0$ is not $100$% of $0$?

Question: $n = 100$% of n
if $n=0$ then $0 = 100$% of $0$, but
$0 = 1$% of $0$, $0 = 2$% of $0, 0 = 3$% of $0$, etc
Is it correct to say that $0$ is not $100$% of $0$?
Comment: 100% is $1.0$ and 1% is $0.01$. We have $0= a \times 0$ for every $a$ and thus x% of $0$ is always $0$, whatever is $x$ (1 slice of no cake is no slice; 2 slices of no cake are no slices, etc.).
Comment: 0 = x% of 0 does not have a unique answer since this would require dividing by zero.
Comment: If your statement was incorrect, then 0 would be 100% of 0 - I think your statement is correct.
Answer: By your reasoning, $4$ is not $1+3$ because $4$ is already $2+2$. Nope. $4$ is both $1+3$ and $2+2$, and of course many other things like $8 \div 2$.
Comment: The key is that we have many different expressions that refer to the same object. Given any decimal number $x$, the expression "100% of $x$" refers to the same number as $x$, and so we are always correct in writing "100% of $x$ = $x$".
Answer: I think if you go this way, you may say : $0$ is not only $100\%$ of $0$.
Answer: There is a subtlety here not captured in the other answers. If we say that $a$ as a percentage of $b$ is $$\frac ab \times 100\%$$ then $0$ as a percentage of $0$ becomes $$\frac 00 \times 100\%$$Now $\frac 00$ is undefined, and in general we cannot divide by zero, so the percentage is strictly undefined. The subtlety is the division by zero which is concealed by the language about percentages.
The language about percentages is, to be sure, often used less formally than the defined operations of arithmetic. The extent to which this matters therefore depends on the formality of the context.
Comment: The original phrasing means "100% $\times$ ..." so there is no division at all. Of course, one had better be aware of the subtlety that you point out when asking the question "How many percent of $b$ is $a$?" which is an ill-defined question if $b = 0$, regardless of $a$.
Answer: Every percent of $0$ is $0$. So, no, it is not correct to say that. $0$ is $100\%$ of $0$.


How to use more then one CLOB field on a page on ORACLE APEX 5

Question: I have a CRUD page, a form in APEX (version 5), and the corresponding table has two CLOB fields. I need to modify both fields on the same page. I´m aware of a know solution that apears to be very widespread, one that uses the collection APEX_COLLECTION and Processes that loads the CLOB field and update the modified values.
/** PL/SQL for loading the CLOB field */
declare
l_clob clob:= empty_clob();

begin
   if apex_collection.collection_exists(p_collection_name=>'CLOB_CONTENT') then apex_collection.delete_collection(p_collection_name=>'CLOB_CONTENT');
    end if;
 apex_collection.create_or_truncate_collection(p_collection_name=>'CLOB_CONTENT');
    dbms_lob.createtemporary( l_clob, false, dbms_lob.SESSION );

    select DS_CONCLUSAO
    into l_clob
    from CR_RELATORIO
    where ID_RELATORIO = :P15_ID_RELATORIO;

    apex_collection.add_member(p_collection_name => 'CLOB_CONTENT',p_clob001 => l_clob);
end;

/** Javascript Functions for loading and setting the field on the page */

I´m trying to use this solution, but the problem is: that collection has only one space for a CLOB field, and i need two (or more) spaces for the two CLOB field on the DB table.
I tried to create two different APEX_COLLECTIONS on the same page, with different names, but it´s not working.
Answer: APEX_COLLECTION is just a convenient wrapper for a table with automatic purging after the session is aged out.
In your case, I'd make my own table, with SESSION_ID as part of the key, and implement my own purge process for it.
Comment: but using your solution, how can i support two or more CLOB fiels on the same page?
Comment: What is stopping you right now? Your question was about the limitation of one clob in a collection; if you create your own table, you can have several CLOBs.
Comment: i have a table, which is populated and modified by this one page. I use the collection to load/insert the two CLOB fields from/into the table. And here's the problem, since the collection supports only one CLOB field. I don't see how the creation of another table with two CLOB fields may help.
Comment: The answer is *don't use collections*. Use your own table instead. Remember, there's nothing especially magical about collections, they're a convenient wrapper for an ordinary Oracle table.


Java Polymorphism - Selecting correct method based on subtype

Question: Given the following Class and Service layer signatures:
public class PersonActionRequest {
    PersonVO person
    // ... other fields
}
public class MyServiceLayerClass {

   public void requestAction(PersonActionRequest request)
   {
       PersonVO abstractPerson = request.getPerson();
       // call appropriate executeAction method based on subclass of PersonVO
   }
   private void executeAction(PersonVO person) {}
   private void executeAction(EmployeeVO employee) {}
   private void executeAction(ManagerVO manager) {}
   private void executeAction(UnicornWranglerVO unicornWrangler) {}
}

As discussed here, java will select the best method based on type info at compile time.  (Ie., it will always select executeAction(PersonVO person) ).
What's the most appropriate way to select the correct method?
The internet tells me that using instanceof gets me slapped.  However, I don't see the appropraite way to select the method without explictly casting abstractPerson to one of the other concrete types.
EDIT:  To Clarify - The VO passed in is a simple ValueObject exposed for web clients to instantiate and pass in.  By convention it doesn't have methods on it, it's simply a data structure with fields.
For this reason, calling personVO.executeAction() is not an option.
Thanks
Marty
Comment: If it's any help, *I* wouldn't slap you for using instanceof there.
Comment: Are you using inheritance? Where is your inheritance tree?
Comment: You've got a highly procedural 'Struct + Manager' architecture.  The answer to the question 'how can I take advantage of Object Oriented benefits like Polymorphism' is switch to an Object Oriented design domain.  Adapt your VOs up front into working business objects.  Is that the right answer for you?  Maybe not.  Zealotry aside, sometimes a procedural pattern is the right answer to a problem.  What's wrong with instanceof?  it's a procedural design pattern, not an OO one, so who cares about an OO principle like polymorphism?  (and "It's slow" hasn't been true for many JVM versions now.)
Answer: If executeAction was a method in a base class or interface that was common to PersonVO, EmployeeVO, ManagerVO and UnicornWranglerVO, you could just call abstractPerson.executeAction() instead of having multiple overridden methods.
Comment: Unfortunately, the VO is merely a Data Structure with fields only, no behaviours.  I've updated the question to make this clearer.
Answer: Your principle obstacle to polymorphism here seems to be a 'dumb-struct' data object + 'manager class' service non-pattern.  The "more polymorphic' approach would be for execute() to be a method that the various person implementations override.
Assuming that can't change, the way you do multiple dispatch in Java is with visitor-looking callbacks.
public interface PersonVisitor {
   void executeAction(EmployeeVO employee);
   void executeAction(ManagerVO manager);
   void executeAction(UnicornWranglerVO unicornWrangler);
}
public abstract class PersonVO {
public abstract void accept(PersonVisitor visitor);
}
public class EmployeeVO extends PersonVO {
@Override
public void accept(PersonVisitor visitor) {
  visitor.executeAction(this);
}
}

public class MyServiceLayerClass implements PersonVisitor {

   public void requestAction(PersonActionRequest request)
   {
       PersonVO abstractPerson = request.getPerson();
       abstractPerson.accept(this);
   }

   public void executeAction(EmployeeVO employee) {}
   public void executeAction(ManagerVO manager) {}
   public void executeAction(UnicornWranglerVO unicornWrangler) {}
}

Answer: You could change the way you are approaching the design and use a Visitor, passing the executor into the Person and have the person type determine which to call.
Answer: The Visitor pattern is often used to overcome Java lacking double-dispatch.
Answer: I would explicitly cast the abstractPerson. Not only does it ensure the JVM gets the right method, it makes it a hell of a lot easier to read and ensure you know what's going on.


Installation for maven in eclipse Mars

Question: As i am working in MNC company, we need to install maven in my eclipse.but Eclipse MarketPlace & Install New Software is blocked in my Firewall.
And also tried : windows-->Properties-->Advanced System Setting (this also blocked)
Can u please help any one to install maven.
Thanks
Comment: Try to use the offical site https://maven.apache.org/download.cgi and download maven via browser...
Answer: You cannot simply install maven in offline mode. It has a lot of dependencies and their dependencies. This will become a very tedious task to do manually.
Consider these options:

If you can connect to internet through other means, like using a
proxy, try configuring proxy to install maven. See Configuring a
proxy.
Better talk with your network IT team, they will sort it out for you by providing some exceptional access on 8080/80 ports
Answer: Well you can try it out and set the proxy from your company in eclipse and try again. Maybe you have no network configuration in eclipse so the Firewall blocks everything.
Comment: where we need to set proxy in my eclipse
Comment: Well vivek mano gave you an answer on how to configure a proxy. Otherwise you can look in eclipse for something like preferences -> Network Connections or something like that.

Installation for maven in eclipse Mars


Calculate the numbers of a geometric sequence

Question: The sum of $3$ numbers in a geometric sequence is $175.5$:
$$b_1 + b_2 + b_3 = 175.5$$
And the product of the same numbers is $91125$:
$$b_1 \cdot b_2 \cdot b_3 = 91125$$
I used the formula for the product and calculated $b_2$ which equals to $45$, but when I try to calculate the other terms I get stuck with this formula and I am not sure if the formula I get is correct:
$$45q^2 - 130.5q + 45 = 0$$
Thanks in advance
Comment: your quadratic looks fine.
Answer: Let the three numbers be $\frac ar, a, ar$.
Product:
$$\frac ar\cdot a\cdot ar=91125\\
a^3=91125\\
a=45$$
Sum:
$$45 (\frac 1r+1+r)=175.5\\
r^2-2.9r+1=0\\
(r-2.5)(r-0.4)=0\\
r=0.4, 2.5$$
Hence the numbers are either $$18,45,112.5$$ or $$112.5,45.18$$.
Comment: How did you convert this equation r^2−2.9r+1=0 to (r-2.5)(r-0.4)=0?
Comment: You might be more familiar with quadratics with integer coefficients. Multiply the equation by $10$, resulting in $10r^2-29r+10=0$ which then factorises to $(2r-5)(5r-2)=0$ giving the same answers as before.
Comment: Thank you for your answer.
Comment: You're welcome. Hope it was helpful.


Fourth roots of $-17$

Question: The question I'm stuck on is as follows:
Find all $4$th roots of $−17$ in Cartesian form. Simplify as much as possible.
Here's what I've done so far:
$$z^4 = -17\\
|z| = \sqrt{(-17)^2} = 17 = r\\$$Using De Moivre's Theorem:$$
-17 = 17e^{0i +2kπi}\\
-17^{\frac{1}{4}} =17^\frac{1}{4}[e^{2kπi}]^\frac{1}{4}\\
17^\frac{1}{4}[e^{2k}]^{\frac{π}{4}i}\\
z_0 = 17^\frac{1}{4}[\cos(0)+\sin(0)i] = 17^\frac{1}{4}\\
z_1 = 17^\frac{1}{4}[\cos\left(\frac{π}{2}\right) + \sin\left(\frac{π}{2}\right)i] = 17^\frac{1}{4}
$$
Comment: $e^{\pi i}=-1$ might help, although it might be easier to think of introducing the fourth roots of $i$.
Answer: The step you have done$|z|$=17 is wrong.As $z^4$ = -17,hence $z^2$ = $\pm$ $\sqrt17$$\times$i.
Case 1:-
For $z^2$ = +$\sqrt17$$\times$i.On square rooting i you will get $\sqrt i$ = $\frac{1}{\sqrt2}$$\times$(1 + i). hence as $z^2$ = +$\sqrt17$$\times$i so z=$\pm$ $\mathrm {17}^{1/4}$$\times$$\frac{1}{\sqrt2}$$\times$(1 + i).
Case 2:-
For $z^2$ = -$\sqrt17$$\times$i=$\sqrt17$$\times$(-i).On square rooting -i you will get $\sqrt -i$ = $\frac{1}{\sqrt2}$$\times$(1 - i).Hence z=$\pm$ $\mathrm {17}^{1/4}$$\times$$\frac{1}{\sqrt2}$$\times$(1 - i).Therefore z=$\pm$ $\mathrm {17}^{1/4}$$\times$$\frac{1}{\sqrt2}$$\times$(1 $\pm$ i)
Comment: $z^2=\pm i \sqrt{17}$.  $i$ has two square roots, the one you give and its negative.  You should find four fourth roots of $-17$
Comment: I corrected it but due to internet connection problem t didn't work out
Answer: As $\displaystyle -1=e^{i\pi }=e^{(2k+1)\pi i}$ where $k$ is any integer
So,  $\displaystyle -1^{\frac14}=e^{\frac{(2k+1)\pi i}4}$ where $k$ can assume any four in-congruent values $\pmod4$
Now use Euler Formula to get $\displaystyle -1^{\frac14}=\cos\dfrac{(2k+1)\pi}4+i\sin\dfrac{(2k+1)\pi}4$ where we can take $k$ to be $0,1,2,3$
de Moivre's formula should bring us in the destination

Fourth roots of $-17$


Does "y (2 + x) = 3" represents a straight line equation?

Question: I'm new to straight line equation and trying to find out whether $y (2 + x) = 3$ represents a straight line equation or not. Could anybody please help me to figure out how to reach a conclusion here.
Comment: Try picking some values of $x$ and see the corresponding vertical coordinate $y$ is. For example, $x=0$ means $2y=3$, so $y=3/2$. Do this a couple more times, and you will see that this equation does not describe a line.
Comment: Dividing both sides by $2+x$ yields $y=\frac{3}{2+x}$, which is nonlinear considering it is a reciprocal function.
Answer: No it does not, It represents a hyperbola.
General equation of a straight line is $ax+by+c=$ where $a,b,c \in\mathbb R$. But your equation when simplified looks like $2y+xy-3=0$ Notice that straight line equation has no $xy$(
or coefficient term $xy$ term is zero) hence it does not represent a straight line.
Answer: There's a simple way to distinguish between a linear equation (or any polynomial) and a non-polynomial equation. A polynomial is defines as $$y=a_1x^1 + a_2x^2 + ... + a_nx^n$$ Observe the variable $x$ is on one side and $y$ is on the other, this is the general form. So bring one of the variable to one side and see if the degree is a positive integer, only then the equation is a polynomial.
Try using this information for your question. (A linear equation is an equation of degree 1)


User Profile Picture Cached After Change

Question: When changing your profile picture (using core pictures support) the image is uploaded correctly but is saved with the same file path as the old image.
The result is even though the image is uploaded correctly, the browser has cached the old one and still displays it, making it seem as though the new picture wasn't uploaded.
Forcing a refresh Ctrl+F5 resolves the problem, but this is not normal user behavior and has already caused confusion.
Is there a way to force a reload for this, for example changing the image path or setting an expires header?
Answer: use a random tail after the filename like
http://www.domain.com/filename?122492834932
it will detect your file as a new file and browser cache will not read it as the same as the old one
Answer: Good point! It's easy to change the default behavior, however, with a module roughly along these lines:
<code>function YOUR_MODULE_form_user_profile_form_alter(&$form, &$form_state) {
  if (variable_get('user_pictures', 0))
     $form['#validate'][] = '_YOUR_MODULE_user_validate_picture';
}

function _YOUR_MODULE_user_validate_picture(&$form, &$form_state) {
  $source = $form_state['values']['picture'];
  if (! empty($source)) {
    $destination = /* TODO: generated random filename */;
    file_move($source, $destination, FILE_EXISTS_RENAME);
  }
}
</code>
Or, even better, use the Unique Avatar module. :-)
Comment: Unique Avatar did the trick


Fair three-way sandwich division

Question: This question discusses fair three-way sandwich division. Mentoined solutions include
the Selfridge–Conway discrete procedure and the moving-knife procedure. I posed the question to the guys at the office and we can't think why this method would not be a solution:

A makes the first cut.
B makes the second cut.
C chooses a piece.
A chooses a piece.
B gets the remaining piece.

Is this a solution? If not then why not?
Comment: If $A$ cuts the cake / sandwitch / whatever in more or less exactly half, then no matter what B cuts, he will end up with at most a quarter, and thus be unstatisfied.
Comment: But A would have no motivation to cut in half because he will then always be left with less than a third.
Comment: You might say that, but the _point_ of the Selfridge-conway procedure is that _no matter_ where you or anyone else actually cut, as long as you are under the impression that your _own_ cuts are made fairly, and you always _choose_ the biggest piece available, then it logically follows that your share is at least as big as anyone else's. That is not the case in the above procedure.
Comment: Can you state the question in mathematical language?
Answer: Suppose that A thinks that he has cut the sandwich into 1/3 and 2/3, but B then cuts the piece which A thought was 1/3. C can now take the piece which A thinks is 2/3, and A is going to be very unhappy.

Fair three-way sandwich division


Integration of $\frac{x^{1/3}}{1+x^2} dx$

Question: I have problem with integration $I = \int_0^\infty \frac{x^{1/3}}{1+x^2} dx$ using residue theory.
Define $\log z$ on the complex plane except the positive real line so that its imaginary part is in $(0, 2\pi)$.
Consider a counterclockwise path $C$ with a small circle around $0$, a real line from $0$ to $\infty$ on the upper half plane, a big circle around $0$, and a real line from $\infty$ to $0$ on the lower half plane.
The integral $\int_0^\infty \frac{z^{1/3}}{1+z^2} dz$ converges to $(1-e^{2\pi i /3})I$ as on the lower real line $z^{1/3} = e^{2\pi i /3}x^{1/3}$.
Using residues I have $\frac{1}{2\pi i} \int_0^\infty \frac{z^{1/3}}{1+z^2} dz = \frac{1}{2i} (e^{\pi i /6} - e^{\pi i /2})$.
But this leads to $I = \frac{\pi i}{\sqrt 3}$.
Where did this argument go wrong? Is it not OK to apply residue theorem in this situation?
Comment: Also see [here](https://math.stackexchange.com/q/1313993/977780) . Exactly same question.If this post doesn't answer you question, then mention in your post and add proper link.
Answer: Residue equals:
$$Res=\frac{e^{\pi i/6}}{2i}+\frac{e^{\pi i/2}}{-2i}$$
The integral goes to:
$$(1-e^{2\pi i/3})I=2\pi i\cdot Res=\pi\left( e^{\pi i/6}-i\right)\Rightarrow I=\frac{\pi}{\sqrt{3}}$$
Comment: Please strive not to post more (dupe) answers to dupes of FAQs, cf. recent site policy announcement [here](https://math.meta.stackexchange.com/questions/33508/enforcement-of-quality-standards).Instead of answering it, it would be better to look for a good duplicate target, or help the user by posting comments.You can use [this](https://approach0.xyz/search/?q=OR%20content%3A%24I%20%3D%20%5Cint_0%5E%5Cinfty%20%5Cfrac%7Bx%5E%7B1%2F3%7D%7D%7B1%2Bx%5E2%7D%20dx%24&p=1)


Limit existence for root x type problems.

Question: I know that $$\lim_{x\to 0} \sqrt{x}$$ does not exist when $x\to 0$. By looking at the graph of $\sqrt{x}$ it is obvious that yes it is not defined for any negative value of $x$. But as I have been taught that for any limit to exist it must satisfy:
$$\lim_{x\to 0^+} \sqrt{x}=\lim_{x\to 0^-} \sqrt{x}$$
So when I tried to prove it by subsituting $x=a+h$ for RHL & $x=a-h $ for LHL, where $a=0$ & $h\to 0$
RHL$$=\lim_{h\to 0^+} \sqrt{a+h}$$
$$=\lim_{h\to 0^+} \sqrt{0+h}$$
$$=\lim_{h\to 0^+} \sqrt{h}=0$$
AND
LHL$$=\lim_{h\to 0^-} \sqrt{a-h}$$
$$=\lim_{h\to 0^-} \sqrt{0-h}$$
$$=\lim_{h\to 0^-} \sqrt{-h}=0$$
So RHL $=$LHL.
 Says that limit exists but we all know that's not the answer. So what's the problem for this method?

My second question is that I have seen multiple times for questions like
$$\lim_{x\to6} \dfrac{(x+6)(x-6)}{\sqrt{(x-6)^2}}$$, which simplifies to $x+6$ if denominator's square root is open. But this opening of square root is not done but instead $\sqrt {(x-6)^2}$ is written as $|x-6|$ and then modulus is opened for $x<6$ and $x>6$. And is said that limit not exists at $x=6$.
So in that case $\sqrt{x}$ can also be written as $|x|$. And we know that $|x|$ limit exists at $x\to 0$ then it must also exist for $\sqrt{x}$. I know that graph of $\sqrt{x}$ is not same as $|x|$. But if this method can be applied to the previous problem then why can't for this. Please explain me I am getting much confused in such type of problems.
Comment: you must write $$\lim_{x \to 0^+}\sqrt{x}$$ since we have $$x\geq 0$$
Comment: The problem seems to be in both cases that you're concluding that $\lim_{h\rightarrow 0}\sqrt{-h} = 0$
Comment: For your second question it's not that $\sqrt x$ is treated as $|x|$, rather it's $\sqrt {x^2}$ that is treated as $|x|$.
Answer: The issue with your first one is that you have defined $h>0$, so $\sqrt{0-h}$ is in fact STILL the square root of a negative number, so the limit is undefined going from the negative side.
The reason on the second one: Consider going from the left side ($x<0$). We have $\sqrt{(x-6)^2}=6-x=|x-6|.$ This is simply because the final result of a square root must be positive if it's defined (it's obviously defined since the inside of the square root is always nonnegative). $x-6$ is not positive for $x<6$ so we must use $6-x$ in this case, or $|x-6|$ overall.
Comment: But I thought that subsituting 0 for value of h in square root will not take negative sign into account.
Comment: No, you are approaching from the negative side, so you must assume that $h<0$ as it stands. The limit is defined as not reaching the value it's approaching, it's only defined as getting infinitesimally close to it. Note that the function $f(h)=\sqrt{-h}$ is only defined for $h\ge 0.$
Comment: Hey! I have concluded in my question that $\sqrt {x}=|x|$. Is it correct, because now I am realising that it must have been $\sqrt {x^2}=|x|$.
Comment: Yes, you have $\sqrt{x^2}=|x|$ but not $\sqrt{x}=|x|.$
Comment: I think you've noticed exactly what is wrong with your last para.
Comment: Oh! Sorry for that. I have understood my mistake. Thanks for your quick response.


trying to identify which form submitted in php

Question: I'm trying to make several forms in the same page and I have faced a problem that the php code is not responding for the submission action
    <form id="DeleteEmployeeModal" name="DeleteEmployeeModal" method="post">>

Delete Employee

                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

                        Name
                        <select  class="form-group" required>

            </select>

                    <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">

                <input type="submit"  name="formAddEmplyee" class="btn btn-danger" value="Delete">
            </form>
<?php if(isset($_POST["DeleteEmployeeModal"])){

`echo "What is happpopoihsdafopishdfpoishdfpoaishdfpoiasdhfpoiashdfpoih";`}`?>`

Comment: I have filled my  tag with php and it's all working
Comment: You need to check for the name of the button clicked: `isset($_POST["formAddEmplyee"])`
Comment: the formname DeleteEmployeeModal is not transmitted.  Only Inputs are , so check the Submit name of formAddEmplyee instead
Answer: One way around this is to add a hidden form name input to each form:
<input type="hidden" name="formname" value="DeleteEmployeeModal" />

Then in your PHP you can just check the value of $_POST['formname'] to see which form was submitted.
Comment: @Dice that is also *one* way of doing it. Why is this a "very bad practice"?
Comment: That is a very bad practice. You can just give different names to your submit buttons and check if they're set...


How to send a content to specific users in ASP.NET Core 5

Question: I have an ASP.NET Core 5 MVC project that I want the admin to be able to send a file to a specific person and the information in this file is formed through a form.
Suppose an academic advisor has to send a separate syllabus to each of their students, which is a photo file. I have problems for every student in all areas such as database, downloading, uploading and displaying that image. I hope I could have explained it well
Please anyone who can help me
Answer: you can use a table in your database and save address of each file for each user you want. also use GUID file name for files and if It Has secure thing you can use Webapi interface Download (disable directly download) that check permission every time api called
Comment: Yes that's right
I know this but I do not know how to send a photo to the first student and display it in the user panel of the first student and do the same for the other students. exactly the main problem in database design and database relations between admin and student
Comment: can you explian you senario? only first student can see it? amd second one not?
Comment: No The counselor sends the program to several students. My problem is that I do not know how to put these photos in the database. The relationship between the program and the student is one to one. So any program is for the student. Later, the student should be able to view and download this program in his user panel
I hope I can explain well


Existence of Malthusian Parameter (general branching process)

Question: Consider a continuous time point process $\eta(t)$ representing the number of children in the interval $[0,t]$. Then $\eta(\infty)$ gives the total number of children of an individual. We define $\mu(t):= \mathbb{E}[\eta(t)]$ as the expected number of children in the interval $[0,t]$. In particular, we define $\mathcal{L}\mu(z):= \int_0^{\infty}e^{-zx} \mu(dx)$ for $z\in\mathbb{C}$.
The Malthusian parameter is defined as the solution $\alpha$ of $\mathcal{L}\mu(\alpha)=1$.
If we assume that the Malthusian Parameter exists, then it follows $\mu(\infty)>1$. I ask myself if the converse is true. So if we have $\mu(\infty)>1$, thus their a Malthusian Parameter exsists. Therefore should be $\mathcal{L}\mu(z)$ continuous, but i am not sure if this is true.
Answer: You have to use  the fact that $k=\log \mathcal {L}$ is a strictly convex function on $(0,\infty)$ (unless than $\mu$ is proportional to a Dirac measure.) We have $k(0)=\log \mu(\infty)$ and $k(\alpha)=0.$ If $k(0)<0$ then $\alpha$ exists and is unique. If $k(0)\geq 0$ there are $0,1,2$ solutions to the equation $k(\alpha)=0.$
Comment: Did i understand it correctly that just in a subcritical regime the malthusian parameter exist (and is unique) and in a supercritical regime their could be more (or zero) solutions?
Comment: What confuses me is that $\mathcal{L}\mu(\theta)$ is continuous for $\theta\in\mathbb{R}$, $\mathcal{L}\mu(0)=\mu(\infty)>1$ and $\mathcal{L}\mu(\infty)=0$. So their should be an $\alpha$?
Comment: Oh you are right, using the fact that $\mu$ is concentrated on $[0,\infty)$ we have $k(\infty)=-\infty.$ So your conjecture is correct!
Comment: Nb: $\mathcal{L}$ is finite on $(0,\infty)$ but not necessarily on the whole $R.$ Examples $\mu_1(dx)=1_{(0,\infty)}(x)dx$ or $\mu_2(dx)=e^{-x}\mu_1(dx).$
Comment: But in the most papers an assumption is that a Malthusian parameter exists. This implies then the supercriticality of the branching process. If my conjecture would be true than it would be enough just to assume supercriticality? And $\mathcal{L}\mu(z)$ could also be infinite on $(0,\infty)$?
Comment: With what I understand of your model $\mathcal{L}(z)<\infty$ by hypothesis. If  you consider monsters like $\mu(dx)=e^{x^2}1_{(0.\infty)}(x)dx$ the Laplace transform does not exist. To conclude, you must deal only with measures such that $\mathcal{L}(z)<\infty$  (which can be filled even for some unbounded mesures). The assumption of the existence of a Malthusian parameter seems to be equivalent to $\mathcal{L}(z)<\infty$ and the total mass $>1.$


Font Awesome into WinForms

Question: Someone tried to use Font-Awesome (fortawesome.github.io/Font-Awesome/) into a C# / WinForms app?
Is supposed to be a font like any other, or not?
Comment: Oops, sorry about the link... edited. Thx @user1189566 .
Comment: I used once, just remember to set as a `Resource`
Comment: That link 404's. And also I have no idea what you're asking.
Comment: No idea what your question means.
Comment: Hi @Tico!, thx by answer. Do you have any link? Into the winform app, I see the icons like in the web?
Comment: Hi @tnw! Font-Awesome is an `TTF` font with icons.(generally used in web projects with `BootStrap` and `CSS`). I want use that icons into an `Winform` app.
Comment: @Chapeti O_O that doesn't clarify your question at all...
Comment: Let me explain @tnw :-)

Instead use image on your web projects, you can install Font-Awesome and use them vectors icons embedded the `HTML` code.

I want do the same, but, into an Winforms App.
Comment: Because the icons in Font-Awesome are pretty nice and scalable. (vectors)
Comment: Sorry, man. It was a long time ago, something like 3 months =/
Answer: I'm pretty sure those won't work in WinForms without using a webcontrol or something similar.  That appears to be a web/css font only.
[EDIT]
There appears to be some hope here:
https://superuser.com/questions/532556/how-can-i-use-font-awesome-in-photoshop-and-fireworks
Comment: Here is a much easier to use drop-in class to use in a winforms project >  https://github.com/microvb/FontAwesome-For-WinForms-CSharp
Comment: Font Awesome in Windows Form Application Here https://github.com/denwilliams/FontAwesome-WindowsForms
Comment: Hi @Zippit ! That was my first impression too... but wanted to ask here to see if anyone had tried the same... ( I worked with Font-Awesome in web projects and I love )
Comment: Thx Zippit! we are one step closer... :-)

Font Awesome into WinForms


Expand $\frac{1}{z^2}$ as a series on $|z - 2| < 2$

Question: I am asked to show that
$$\frac{1}{z^2} = \frac{1}{4} + \frac{1}{4}\sum_{n = 1}^{\infty}(-1)^{n+1}(n+1)\left(\frac{z-2}{2}\right)^n$$
on $|z - 2| < 2$.
My plan is to consider a series expansion of $\frac{-1}{z}$ in $|z - 2| < 2$ and differentiate this series term by term to yield the desired series (This is valid from theorems we have proved in class).
Indeed,
$$\frac{-1}{z} = \frac{-1}{2-2+z} = \frac{-1}{2}\cdot\frac{1}{1+\left(\frac{z-2}{2}\right)}$$
$$ = \frac{-1}{2}\sum_{n = 0}^{\infty}(-1)^n\left(\frac{z-2}{2}\right)^n $$
$$ = \frac{1}{2}\sum_{n = 0}^{\infty}(-1)^{n+1}\left(\frac{z-2}{2}\right)^n $$
Differentiating term by term gives:
$$ \frac{1}{z^2} = \frac{1}{2}\sum_{n = 1}^{\infty}(-1)^{n+1}n\left(\frac{z-2}{2}\right)^{n-1}\cdot\frac{1}{2} $$
$$ = \frac{1}{4}\sum_{n = 1}^{\infty}(-1)^{n+1}n\left(\frac{z-2}{2}\right)^{n-1}$$
Now, if we let $k = n - 1$, we can re-index the series as:
$$ = \frac{1}{4}\sum_{k = 0}^{\infty}(-1)^{k+2}(k+1)\left(\frac{z-2}{2}\right)^{k}$$
$$ = \frac{1}{4} + \frac{1}{4}\sum_{k = 1}^{\infty}(-1)^{k}(k+1)\left(\frac{z-2}{2}\right)^{k}$$
Unfortunately, the power of $(-1)$ present in my series does not match what the prompt reads. I am off by one. Did I make a mistake or is the prompt incorrect?
Comment: Your solution looks correct.
Answer: Perhaps a simpler approach would be to write
$$
{1 \over z^2} = {1 \over 1 - \left(1 - z^2\right)}.
$$
Letting $a = 1 - z^2$, we see that the above expression has (at least formally) the geometric series expansion:
$$
{1 \over 1 - \left(1 - z^2\right)} = {1 \over 1 - a} = \sum_{n \geq 0} a^{n}.
$$
Now expand each power
$$
a^{n} = \left(1 - z^2\right)^n
$$
using the Binomial Theorem.


Reset button for an AJAX form

Question: How do i programatically reset the values of an AJAX submitted form for Drupal 8? I Want to reset them with an AJAX callback. Here is my current callback. It works because i'm forcing the values to NULL.
      public function resetFormCallback(array &$form, FormStateInterface $form_state) {

          $form_state->clearErrors();
          $form_state->setRebuild(TRUE);

          $form['address']['#value']    = NULL;
          $form['customer']['#value']   = NULL;
          $form['name']['#value']       = NULL;
          $form['email']['#value']      = NULL;
          $form['location']['#value']   = NULL;
          $form['zip_code_1']['#value'] = NULL;
          $form['zip_code_2']['#value'] = NULL;
          $form['phone']['#value']      = NULL;
          $form['subject']['#value']    = NULL;
          $form['message']['#value']    = NULL;

          return $form;
        }

Comment: $form_state->setUserInput([]); $form_state->setRebuild();
Comment: That doesn't cleans my input values. Do notice i do return $form at the end of my callback.
Answer: I found a couple solutions that works in Drupal 9 that should also work in 8. Untested.
In my buildForm() I am setting some '#default_valueswith$form_state->getValue('name')`. Maybe you are too?
In my case I have a non ajax version of the form that does not have a clear button. In my ajax form's buildForm() function; I simply add "unset()" to the beginning of the form because there is never an instance in which the form needs to be pre-populated on page load in my case. The form will not reload in-between state changes either, so we never have to worry about `#default_value' being set.
Example:
public function buildForm(array $form, FormStateInterface $form_state) {
    //get parent's form
    $form = parent::buildForm($form, $form_state);
    //unset default values so the form clears properly
    unset($form['address']['#default_value']);
    unset($form['customer']['#default_value']);
    unset($form['name']['#default_value']);
    // the rest of your form modifications

    return $form
}

Alternatively or in addition to, if you need your form to be pre-populated on page load via arguments (might be overkill); In your ajax buildForm() you can detect the last callback made and preform your unsets within:
//within the buildForm() ajax function, example clear button with your callback name
$form['clear'] = [
      '#type' => 'button',
      '#value' => $this->t('Clear'),
      '#ajax' => [
        'callback' => '::resetFormCallback',
        'event' => 'click',
      ],

//Check the operating button that submitted a callback action that rebuilt the form
//assign boolean
$form_cleared = 'Clear' === (string) $form_state->getValue('op');
if($form_cleared) {
  //preform unsets here
}

Reset button for an AJAX form


Undefined variable $daten a kind of ErrorException

Question: this is my laravel project, the is a problem named undefined variable
it is funny I think the route is ok and Controller is also fine
route
Auth::routes();

Route::get('/', 'PagesController@home')->middleware('auth')->middleware('assign');
Route::get('/home', 'HomeController@index')->name('home')->middleware('auth');
Route::get('/groupchat', 'PagesController@getGroupchatPage')->name('groupchat')->middleware('auth');
Route::get('/groupsearch', 'PagesController@getGroupsearchPage')->name('groupsearch')->middleware('auth');
Route::get('/statistics', 'PagesController@getStatisticsPage')->name('statistics')->middleware('auth');
//Route::get('/author_views.statisticsA', 'PagesController@getStatisticsAdmin')->name('statisticsA')->middleware('auth');

// Routes for SQL Controller Querys
Route::get('/getQuestions/{id}', 'QuestionsController@getQuestions');
Route::get('/getChapterQuestions/{id}', 'QuestionsController@getChapterQuestions');
Route::get('/getAnswers/{id}', 'AnswersController@getAnswers');
Route::get('/getChapters/{id}', 'ChaptersController@getChapters');
Route::get('/countMembers/{id}', 'GroupsMembersController@countMembers');
Route::get('/getGroupMembers/{id}', 'GroupsMembersController@getGroupMembers');
Route::get('/getGroups/{id}', 'GroupsController@getGroups');
Route::get('/groupChapters/{id}', 'GroupsChaptersController@groupChapters');
Route::get('/getChaptersAndGroup/{id}', 'ChaptersController@getChaptersAndGroup');
Route::get('/getGroupsChaptersMembersKombined/{id}', 'ChaptersController@getGroupsChaptersMembersKombined');

// 28.06.2021
Route::get('/statistics', 'StatisticsController@statistic');
Route::get('/statisticsA', 'StatisticsController@statisticA');

Route::get('/admin', [
    'uses' => 'PagesController@getAdminPage',
    'as' => 'admin',
    'middleware' => 'roles',
    'roles' => ['Admin'],
])->middleware('auth');

Route::post('/admin_assign', [
    'uses' => 'PagesController@postAdminAssignRoles',
    'as' => 'admin_assign',
    'middleware' => 'roles',
    'roles' => ['Admin'],
])->middleware('auth');

Route::get('/statisticsA', [
    'uses' => 'PagesController@getStatisticsAdmin',
    'as' => 'statisticsA',
    'middleware' => 'roles',
    'roles' => ['Author','Admin']
])->middleware('auth');

Route::get('/eventA', [
    'uses' => 'PagesController@getEventAdmin',
    'as' => 'eventA',
    'middleware' => 'roles',
    'roles' => ['Author','Admin'],
])->middleware('auth');

and my blade
@extends('layouts.appAuthor')

@section('content')

{{ __('DozentAnsicht') }}

                    @if (session('status'))

                            {{ session('status') }}

                    @endif

                            Id
                            FrageBezeichnung
                            Kapitel
                            richtige Antwort
                            falsche Antwort
                            Richtige Rate

                        @foreach($daten as $value)

                                {{$value -> Id}}
                                {{$value -> FrageBezeichnung}}
                                {{$value -> Kapitel}}
                                {{$value -> richtigeAntwort}}
                                {{$value -> falscheAntwort}}
                                {{$value -> richtigeRate}}

                        @endforeach

@endsection

I want to show the table in the view, but it didn't work in statisticA but it works in statistic
I don't know what happen
my controller
<?php

namespace App\Http\Controllers;

use DB;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class StatisticsController extends Controller
{
    //
    public function statistic(){
        $data =DB::table('statisticforteacher') -> get();
        return view('/statistics',compact('data'));
    }

    public function statisticA(){
        $daten =DB::table('statisticforteacher') -> get();
        return view('/statisticsA',compact('daten'));
    }
}

has anyone a idea?
Comment: Have you tried `php artisan view:clear`? Also you have this route `Route::get('/statistics', 'PagesController@getStatisticsPage')->name('statistics')->middleware('auth');` taking over `Route::get('/statistics', 'StatisticsController@statistic');`
Comment: Also you can try `php artisan route:clear`
Comment: thanks to your code, now all route couldn't be loaded, it is a bad idea
Comment: What code are you referring about? `php artisan route:clear` only clear the cache of your routes
Comment: In fact that might be a good thing, if after clearing the cache you have other issues, it mean you're on the right path.
Comment: ok, but it still don't solve the undefined variable error, I don't know why
Comment: Can you try `dd($daten)` in your controller to see if you're hitting the right method?
Comment: I tried, but still the same errror
Comment: Can you add the stacktrace to your question? (In Laravel.log)
Comment: Also, I don't think `view('/statisticsA')` is valid. It's usually `view('statisticsA')` without the `/` and then you complete with `.` (dot) for the folder / views `folder.view`
Comment: ye, but the way u talk about which I have already tried, and I make a lot of works, tried so many solutions, include view('statisticsA') all didn't work, I don't know what's wrong with my code
Comment: Can you please, share the stacktrace or the Flare error report?
Answer: You have in route file two different routes with same url but different controllers. As in order when Laravel read the file, get the last matched route, for that reason you have the issue. So, fix your routes statements and must work
Route::get('/statisticsA', 'StatisticsController@statisticA');

Route::get('/statisticsA', [
    'uses' => 'PagesController@getStatisticsAdmin',
    'as' => 'statisticsA',
    'middleware' => 'roles',
    'roles' => ['Author','Admin']
])->middleware('auth');

Comment: _Laravel read the file, get the last matched route_ I'm almost certain, it takes the first matching route. Is that an assumption? I don't have an environment on hand to verify.
Comment: yes, it's an assumption of the logic of sintax parser, not about how Laravel resolve this. If this loose focus or make wrong the answer of the issue, feel free of give yours
Comment: but the view '/statistics' also have different controllers but same url , and it works only in view '/statisticsA' didn't work
Comment: @Prospero I don't think it makes loose the focus or it makes the whole answer wrong. And since I don't see anything wrong in the question, except the route duplications that seems smeely. It still good to explore all the possible solutions.
Comment: @ClémentBaconnier I agree, I prefer solutions. So in that way, I think duplicate urls can affect the requests, just depends if you make call by the route name or for http


Porque essa tag HTML não mostra o link, só quando eu tiro o style="display: none;"

Question: Estou fazendo um tour no minha área administrativa, mas ela não funciona quando eu mando para o servidor. No projeto do rapaz no GIT no site onde eu fiz o download funciona perfeitamente
A tag é essa:
Tutorial

Comment: Bem vindo ao SOPT. Este site não é um fórum. Faça o [tour] e leia [ask]. Depois clique em [edit] para melhorar a sua pergunta e deixar a sua dificuldade mais clara.
Answer: A função do display: none simplesmente esconde o elemento em questão. O próprio nome já fala "none" (nada, nenhum).
Pode colocar display: block, para resolver ou simplesmente tirar esse estilo.
Tutorial

ou
Tutorial

Answer: display: none; é o ocultador do css a propriedade style é só para adicionar o estilo direto no elemento
Comment: E como eu resolveria isso ?
Comment: Na verdade não entendi seu problema, mas para tornar o elemento visível basta substituir o "none" pelo "block" ou remover essa tag.
Comment: Queria fazer isso aqui man
http://www.jqueryscript.net/other/Easy-Interactive-Visual-Tour-Plugin-For-jQuery-mytour.html
Comment: Já tentou usar o código abaixo do exemplo, display none em um link não faz sentido, a não ser q ele esteja no elemento que vai aparecer, como eu vi no exemplo, ai é preciso o display none para o efeito inicial, porém no seu caso creio q o problema seja outro.
Comment: Natan Melo, mas lá na parte How to use, não tem esse display: none;


Proper way to deal with several sources of variability

Question: What is the proper way of combining various sources of variability? For example, if we know that under the normal conditions, a machine produces parts with normally distributed diameter with some $\mu$ and $\sigma$, and that measuring this diameter has its own normally distributed "noise" with $\sigma_{meas}$. We than sample $n$ parts and measure each exactly once.
What would be the mean and standard deviation of the measurements under the assumption that the machinery works fine?
I am solving a homework assignment. I have stripped down the assignment to what I think is its pivotal point, from which I will be able to work my way out.
Answer: Generally, when you look at the final measurements results you always look at the sums of the particular diameter and a measurement error. Both are random variables with given means and standard deviations.
Now, generally for two random variables
$$
Var(X+Y)=Var(X)+Var(Y)+2Cov(X,Y).
$$
If X and Y are independent, then the covariance is zero and it becomes easier. Does this help you?


Determine the sum $\sum_{n=0}^{\infty}{(-1)^n}\frac{2^{2n-1}}{(2n)!}$

Question: I need to calculate the sum $\sum_{n=0}^{\infty}{(-1)^n}\frac{2^{2n-1}}{(2n)!}$ .
It seems very "similar" to Taylor expansion of functions arcsin(x) and its derivative for x = -2.
It is known: $arcsin(x) = \sum_{n=0}^{\infty}\frac{{(2n-1)!!x^{2n+1}}}{2^{n}n!(2n+1)}$.
When derivative applied we get: $\frac{1}{\sqrt{1-x^{2}}} = \sum_{n=1}^{\infty}\frac{{(2n+1)(2n-1)!!x^{2n}}}{2^{n}n!(2n+1)} = \sum_{n=1}^{\infty}\frac{{(2n-1)!!x^{2n}}}{2^{n}n!}$.
What to do next? Am I on the wrong trace here?
Thank you all in advance!
Comment: $\frac{cos(2)}{2}$
Comment: It's even more "similar" to,

$$\cos(x)=\sum_{k=0}^\infty (-1)^k\frac{x^{2k}}{(2k)!}$$

Divide it by $2$ and substitute $x=2$ to get your result (as shown by d.k.o)
Answer: It surprises me to see that you are familiar with the rather obscure series of $\arcsin x$, and yet, at the same time, fail to recognize one of the most well-known series in math, namely that of $\cos x=\displaystyle\sum_{n=0}^\infty(-1)^n\frac{x^{2n}}{(2n)!}~.~$ Also, $\sin x=\displaystyle\sum_{n=0}^\infty(-1)^n\frac{x^{2n+1}}{(2n+1)!}~.$ Remember that $e^x=\displaystyle\sum_{n=0}^\infty\frac{x^n}{n!}~,~$ and then recall Euler's formula $e^{ix}=\cos x+i\sin x$.
Comment: @Zach466920 I'm interested in the definitions of "linear" knowledge and "thinking too linearly."  Perhaps the OP has seen the TS for the cosine function and just for a moment, didn't recognize it herein.
Comment: @Zach466920 I didn't ask for "definitions for the words," I stated that I'm interested in your definitions of phrases (e.g., "linear knowledge").  What is "linear knowledge?"  And a "moment" is not limited to an hour+, so my conjecture is viable.  My comment is not intended to provoke debate or create unhealthy tension.  Rather, I hope each of us can be more empathetic towards problems others have in appealing for help.  While your math skills are better than some, they are dwarfed by best-in-class mathematicians.  Would you enjoy having them publicly criticize you?  Humility is a key here.
Comment: @Zach466920 No worry.  And I do understand the sentient better now.  Best wishes and "happy mathing!"


mkmf generates a strange Makefile

Question: When I build a gem with native C bindings I get this warning:
ld: warning: directory not found for option '-L/Users/travis/.sm/pkg/active/lib'

I've found in generated Makefile these lines:
CFLAGS   = $(CCDLFLAGS) -O3 -I/Users/travis/.sm/pkg/active/include -fPIC -mmacosx-version-min=10.6 -pipe -std=c99 -Wall -ggdb -O2 $(ARCH_FLAG)
..
ldflags  = -L. -L/Users/travis/.sm/pkg/active/lib -fPIC -Bstatic -fstack-protector -lpthread

My system user's name isn't travis, neither did I specified that in extconf.rb.
Also found this issue: https://github.com/flori/json/issues/207
Comment: Is there a question here other than what that ticket seems to indicate is a "known" bug in one of the makefiles?
Comment: @EtanReisner Question is to determine why mkmf acts like that and to fix this behaviour. The ticket doesn't indicate source of the problem as I'm not using json there.
Comment: What does 'env' say in the shell where you run `mkmf` where it does this?
Comment: `env | grep travis` - nothing
Answer: /Users/travis actually comes from the pre-compiled ruby that rvm installs, as of around 2.1.0. If you grep for that string in .rvm/rubies/ or your ruby install dir, you'll find it there. I believe the warning is harmless.
If it turns out not to be harmless or you just want to get rid of it, building ruby locally rather than using a precompiled binary should fix it for you.
Comment: On osx it's not benign.  Rails installation fails
Comment: I'm on OSX too. Are you sure this is the cause, and there's not some other error too?
Comment: I got an error during native library compilation complaining about the /Users/travis library path.  I re-installed command line tools and updated and upgraded brew.  Next I got an error about libgmp. So I reinstalled that with brew and the problem disappeared. @nilbus

mkmf generates a strange Makefile