If $f:Y \to X$ is a mono in $\textsf{Set}^{\mathbb{C}^{op}}$, then $f$ factors uniquely through $Y \xrightarrow{g} A \stackrel{i}{\hookrightarrow} X$.

Question: I have taken an introductory course in category theory and would like to learn more about presheaves. Currently I am working through "Generic figures and their glueings" by Marie La Palme Reyes, Gonzalo E. Reyes and Houman Zolfaghari (subsequently called RRZ).
Let $\mathbb{C}$ be a small category.
I am stuck with the second part of exercise 126.96.36.199:

If $A \stackrel{i}{\hookrightarrow} X$ is a sub-$\mathbb{C}$-set of $X$, then $i$ is a monomorphism. Conversely, if $f : Y \to X$ is a monomorphism show the existence of a unique sub-$\mathbb{C}$-set $A$ of $X$ and a unique isomorphism $Y \xrightarrow{g} A$ such that $f = ig$.

Since I am not sure how standard this terminology and the notation is, recall the following:

A $\mathbb{C}$-set is a presheaf.
A $\mathbb{C}$-set $B$ is a sub-$\mathbb{C}$-set of a $\mathbb{C}$-set $A$, if there exists a morphism of $\mathbb{C}$-sets $i$ (i.e. a natural transformation) such that for each $F \in \textrm{Ob}(\mathbb{C})$, $i_F:B(F) \subset A(F)$ (i.e. $i_F:\textrm{hom}(F, B) \hookrightarrow \textrm{hom}(F, A)$) is the set inclusion.

I find it slightly confusing that RRZ seem to use the same notation for objects in $\mathbb{C}$ and in $\textsf{Set}^{\mathbb{C}^{op}}$. It seems to be sensible for the sake of brevity in the context of that book, but for clarity I reformulate the second part of the exercise using the hom-functor.

Conversely, if $\textrm{hom}(-, f) : \textrm{hom}(-, Y) \to \textrm{hom}(-, X)$ is a monomorphism show the existence of a unique sub-$\mathbb{C}$-set $\textrm{hom}(-, A)$ of $\textrm{hom}(-, X)$ and a unique isomorphism $\textrm{hom}(-, Y) \xrightarrow{\textrm{hom}(-, g)} \textrm{hom}(-, A)$ such that $\textrm{hom}(-, f) = \textrm{hom}(-, i) \circ \textrm{hom}(-, g)$.

We know that in the category of sets, every monomorphism $G \xrightarrow{m} H$ factors uniquely through a bijection $G \xrightarrow{n} G'$ and $j : G' \hookrightarrow H$ such that $m = jn$.
Hence, for every $C \in \textrm{Ob}(\mathbb{C})$, we know that $\textrm{hom}(C, f)$ factors through some bijection $\textrm{hom}(C, Y) \xrightarrow{u} S$ and an inclusion $v : S \hookrightarrow \textrm{hom}(C, X)$ such that $\textrm{hom}(-, f) = v \circ u$.
My problem is now: How can we know that there exists some $A \in \textrm{Ob}(\mathbb{C})$ auch that $S = \textrm{hom}(C, A)$? I don't see how I could use the Yoneda-Lemma at this point, because we don't know whether $S$ is in the codomain of the object function of the Yoneda-embedding. Probably I would have to use the fact that $\textrm{hom}(-, f)$ is a mono somehow - but how?
Comment: How do they define a category?  In general I see no reason why $\hom(C,A)$ could be a *literal* subset of $\hom(C,X)$ for any $A,C,X$. Of course there could be natural injections from one to the other but your authors don't seem to count that as being enough to be a sub C-set
Comment: `\stackrel{i}{\hookrightarrow}` displays $\stackrel{i}{\hookrightarrow}$.
Comment: They refer to Conceptual Mathematics (Lawvere and Schanuel) as preliminary literature. The first sentence of the first chapter is literally: _Let $\mathbb{C}$ be a category whose objects are thought of as generic figures and whose morphisms are thought of as changes of figures._ --- They want to emphasise a certain way of thinking about categories. The exact definition is assumed to be well known though.
Comment: And yes, I agree: I also don't see, why $\text{hom}(C, A)$ could be a subset of $\text{hom}(C, X)$ - probably one has to use a different approach. I was just misled by the authors mentioning that in the category of sets it is well known that monos factorise like this.
Comment: I think the problem comes in, when I rewrite their notation in terms of hom-functors. $Y$ and $X$ are functors from $\mathbb{C}$ into $\textsf{Set}^{\mathbb{C}^{op}}$, but they are not necessarily hom-functors.
Comment: Thank you @azif00 - I fixed it in the title and in the question!
Answer: I think, I managed to solve this exercise. The problem was that I thought of the elements of $\textsf{Set}^{\mathbb{C}^{op}}$ as hom-functors and not as arbitrary functors from $\mathbb{C}^{op}$ to $\textsf{Set}$.
Let $Y \xrightarrow{f} X$ be a mono in $\textsf{Set}^{\mathbb{C}^{op}}$. Then for all $C \in \textrm{Ob}(\mathbb{C})$, $f_C$ is injective and factors uniquely as $f_C = i_C \circ a_C$ where $i_C : A(C) \hookrightarrow X(C)$ is the inclusion of the uniquely determined subset $A(C)$ of $X(C)$ and $a_C : Y(C) \to A(C)$ is a bijection.
We can now define the functor $A : \mathbb{C}^{op} \to \textsf{Set}$ to map every $C$ to this uniquely determined set $A(C)$ and every morphism $C \xrightarrow{g} C'$ to the function $A(g) = a_{C'} \circ Y(g) \circ a_{C'}^{-1}$.

All that is left to do is to show that this is actually a functor, which is trivial.


Deriving the discretized equation of the Geometric Brownian Motion EDE

Question: I am trying to obtain the discretized equation for the Geometric Brownian Motion EDE,
$$
d S_{t}=\mu S_{t} d t+\sigma S_{t} \eta_tdt \tag{1}
$$
I am looking for the discretization for the case where $\mu$ and $\sigma$ are constants, $\eta_t$ is a white noise and the value of $S_t$ at the initial time, $S_0$, is known. The expected result for the discretized equation would be
$$
S_{t+d t}=S_{t}+\mu S_{t} dt+\sigma S_{t}X_t\sqrt{dt} \tag{2}
$$
where $X_t$ is a standard normal variable, $X_t \sim N(0,1)$.
My attempt at a solution
I've tried integrating the whole equation ($1$) between $t$ and $t+dt$, obtaining
$$
S_{t+dt}-S_t=\mu \int_{t}^{t+d t}  S_{t} d t+\sigma \int_{t}^{t+d t}  S_{t} \eta(t)dt
$$
The first integral of the RHS can be approximated by the area of a left-centered rectangle of height $S_t$ and width $dt$,
$$
\int_{t}^{t+d t}  S_{t} d t \approx S_tdt
$$
However, I am not sure how to reason the following approximation for the second integral in the RHS, in order to get the equation ($2$) from ($1$):
$$
\int_{t}^{t+d t}  S_{t} \eta(t)dt \approx S_tX_t\sqrt{dt}
$$
Would this approximation make any sense? Why would it be true?
Comment: It makes sense. The simplest thing you can do is to approximate the integrals by $S_t dt$ resp. by $S_t X_t\sqrt{dt}$. This is called Euler scheme. See the standard book by Kloeden and Platen for more advanced schemes which you may not even need for such a well-behaved equation. BTW why you solve this SDE numerically ? It has a closed form solution: GBM.
Comment: Not foolish at all. You can study the discretization by comparing it with the theoretical GBM. That's exactly how numerical methods get testet.
Comment: @Kurt G It is part of a class exercise. I didn't know there was a closed-form solution. In that case, it's true that it may be a bit foolish to do it this way
Answer: This is by no mean a full answer, in fact as Kurt G. stated in the comments this "discretization" is just the very famous Euler method.
Still I wanted to make a few remarks that were too long for the comment section.
First thing one should notice is the fact that the actual SDE for the GBM is
$$d S_{t}=\mu S_{t} d t+\sigma S_{t} dB_t \tag{1}$$
where $B$ is a Brownian motion.
Even though it seems reasonable to write this equation as
$$d S_{t}=\mu S_{t} d t+\sigma S_{t} \dot B_tdt \tag{2}$$
where $\dot B$ is a "white noise", this is not actually correct; this is a consequence of the Wong-Zakai theorem. If we want to write the SDE as a random ODE we must use the so called "Wick product" $\diamond$ and then we could rewrite $(1)$ as
$$d S_{t}=\mu S_{t} d t+\sigma S_{t} \diamond \dot B_tdt.$$
Having said that what we want to show is that
$$\int_{t}^{t+d t}  S_{s} dB_s \approx S_tX_t\sqrt{dt}$$
or which is the same
$$\int_{t}^{t+d t}  S_{s} dB_s \approx S_t(B_{t+dt}-B_t).$$
Now we compare the two
$$S_t\int_t^{t+dt}dB_s-\int_{t}^{t+dt}  S_{s} dB_s,$$
since $S$ is adapted we can write
$$\int_t^{t+dt}(S_t-S_s)dB_s,$$
taking the $L^2$ norm and using the Itô isometry we have
$$\|\int_t^{t+dt}S_t-S_sdB_s\|^2=\int_t^{t+dt}\|S_t-S_s\|^2ds$$
and this last term converges to $0$ as $dt$ vanishes.


Is my remote server behind NAT?

Question: I have a few remote servers in various locations. How can I detect if they're behind NAT? Of course, I can connect to them via ssh, but is that 100% sufficient to tell that they're not behind NAT?
Answer: NAT can be done for incoming requests and/or for outgoing requests depending on the setup requirements.
To verify whether your server is behind NAT or not, login via SSH and check the address assigned to the server and compare it with the address you used to connect to server. If they are the same, there is no NAT for incoming requests. Similarly, you can do for outgoing requests.
Comment: `Similarly, you can do for outgoing requests.` -- how?
Comment: @Korioma: Request some service from a remote server you have to and check logged IP address.
Comment: `ip addr show` called on a server shows several ip addresses and among them there's one I use to connect to that server via ssh. Therefore, there's no NAT, right?
Comment: @Korioma: That's right

Is my remote server behind NAT?


Showing tha $\mathbb{R}^{a \times b}_{\mathrm{O}}$ is a submanifold of $\mathbb{R}^{a \times b}_{\mathrm{LI}}$.

Question: Let $\mathbb{R}^{a \times b}_{\mathrm{LI}}$ denote the set of $a \times b$ matrices with linearly independent columns. Let $\mathbb{R}^{a \times b}_{\mathrm{O}}$ denote the set with orthonormal columns. Suppose we wish to show that $\mathbb{R}^{a \times b}_{\mathrm{O}}$ is a submanifold of $\mathbb{R}^{a \times b}_{\mathrm{LI}}$, one way would be to use the Gram-schmidt function $$\Gamma : \mathbb{R}^{a \times b}_{\mathrm{LI}} \rightarrow \mathbb{R}^{a \times b}_{\mathrm{O}}$$ and argue that it's image has to be a submanifold.

Question. Is there an easy way of doing this? If not, what would be a good way of showing that $\mathbb{R}^{a \times b}_{\mathrm{O}}$ is a submanifold?
Answer: Idea: consider the matrices as vector tuples $A = (A_i)$. Define a function with coordinates $f_{ij}$ by
$$f_{i,j}(A) = \langle A_i,A_j\rangle.$$
Your submanifold is defined by the equations
$$f_{i,j}(A) = \delta_{i,j}.$$
Now, use the regular value theorem.
Answer: It's better to mimic the argument that $O_n(\mathbb{R})$ is a submanifold of $\operatorname{GL}_n(\mathbb{R})$ which corresponds to the case $a = b$. Namely, let $S = \{ C \in M_{b}(\mathbb{R}) \, | \, C = C^T \}$ denote the vector space of $b \times b$ symmetric matrices and consider the map $T \colon M_{a \times b}(\mathbb{R}) \rightarrow S$ given by $T(A) = A^TA$. Then $\mathbb{R}_{O}^{a \times b} = T^{-1}(I_b)$ so it is enough to show that $I_b$ is a regular value of the map $T$. Let $A \in \mathbb{R}_{O}^{a \times b}$ and let $C \in S$. We need to show that the equation
$$ dT|_{A}(B) = \frac{d}{dt}(A + tB)^T(A + tB)|_{t = 0} = B^T A + A^T B = C $$
has a solution. By choosing $B = \frac{AC}{2}$ we have
$$ B^T A + A^T B = \frac{1}{2} (C^T A^T A + A^T A C) = \frac{1}{2} (C^T + C) = C$$
and so $dT|_{A} \colon M_{a \times b}(\mathbb{R}) \rightarrow S$ is onto and $\mathbb{R}^{a \times b}_{O}$ is an embedded submanifold of $M_{a \times b}(\mathbb{R})$ of dimension
$$ \dim M_{a \times b}(\mathbb{R}) - \dim S = ab - \frac{b(b+1)}{2} = \frac{b(2a - b - 1)}{2}.$$
Since $\mathbb{R}^{a \times b}_{\operatorname{LI}}$ is an open subset of $M_{a \times b}(\mathbb{R})$ and $\mathbb{R}^{a \times b}_{O} \subset \mathbb{R}^{a \times b}_{\operatorname{LI}}$ we see that $\mathbb{R}^{a \times b}_{O}$ is also an embedded submanifold of $\mathbb{R}^{a \times b}_{\operatorname{LI}}$ of the same dimension.


History of "strumming" the piano (Rhythmic repeated chords)

Question: In many songs, a particular chord gets played over and over on a piano, very similar to how you might strum a chord on a guitar.
Examples:

This feels like a long shot, but does anybody know when this technique emerged?  Researching "piano strumming" (if that is even the proper term at all) has proven difficult.
Comment: I think "strumming" is not a useful search term here, as this is not strumming in any way :-)
Comment: Love the word 'strum'. To play on a stringed or keyboard instrument, esp. carelessly or unskillfully. Oxford Concis Dictionary.
Comment: If there is a better term, I'd love to hear it :)
Comment: I've had the exact same though "piano strumming", treating piano accompaniment like guitar strumming or fingerpicking. The point being it's different that the usual piano accompaniment. More rhythmic, less moving up and down the keyboard.
Comment: Do you mean just playing chordal accompaniment on a keyboard instrument? That predates piano... Would basso continuo played on a harpsichord count as "strumming" to you?
Comment: I'm not familiar with basso continuo, but as far as I can tell, it doesn't involve playing a chord on each beat like you'd find in typical strumming patterns.  It's more than just playing the chords, as it involves the beat as well.  I guess the key question is:  "If the chord stays the same, does the chord get played again on the next beat?"
Comment: An early example of an ongoing chord (using broken chords, which can be easier on piano) is the Alberti bass. See https://en.wikipedia.org/wiki/Alberti_bass
Answer: "Strumming" -- or, put another way, playing chords rhythmically -- has been around as long as the piano (and probably longer, but I'll stick to the piano).
Working backwards...
Using this kind of piano accompaniment has long been a mainstay of pop music. For example, the opening of The Beatle's "A Day in the Life" (1967) and Jerry Lee Lewis's "Great Balls of Fire" (1957).
The latter owes a debt to an earlier style, Boogie Woogie, in which repeated, rhythmic piano chords are a hallmark. Pianist Magazine credits the first Boogie Woogie recording to Jimmy Blythe's "Chicago Stomps" (1924) and the first hit song to "Pinetop" Smith's "Pinetop's Boogie Woogie" (1928).
But rhythmically repeated chords have figured prominently long before that.
Taking a leap about 100 years earlier, Beethoven was using "strummed" chords, for example in his Sonata in C Major, nicknamed the "Waldstein" Sonata (1804).
Repeated chords feature prominently in the opening of Mozart's Sonata in A Minor, K310 (1778). Haydn uses an accompaniment of repeated chords throughout the second movement of his Partita in Bb Major (Hob. XVI:2), which IMSLP tentatively dates to 1760.
The piano itself was invented in 1700, but did not gain prominence until the middle 1700s. During those 50-ish years, music itself was changing from "polyphony" to "homophony", the latter of which featured chords to a much greater extent.
However, that is not to say "strummed" chords didn't occur earlier. Bach, in the second movement of his Italian Concerto (1735) uses chords to accompany throughout. This piece, however, would most likely have been performed on harpsichord at the time, rather than piano.
Obviously there are vast differences in the way rhythmically repeated chords have been used. But as a technique overall, it's (at least) as old as the piano.

"Strumming" is, in fact, a piano technique in a different sense. It is an "extended technique" in which the strings of the piano are literally strummed, like a guitar or harp.
For some additional information, see Notation for strumming piano strings. It mentions a couple of pieces that include piano strumming.
And here's a video of pianist Annea Lockwood using some of these techniques.
Comment: That last piece doesn't quite feel like "Rhythmic chords" to me.  Regardless, great answer, thanks!
Comment: I especially love the "Waldstein" Sonata: feels very similar, but classical.
Comment: @NathanMerrill The Bach's a stretch, admittedly, and certainly a long, long way from Sara Bareilles rhythmic. Glad the answer was helpful.
Comment: Here's another one that comes to mind: https://www.youtube.com/watch?v=IaYsgjn82GA (ELP "Take a Pebble")


Calculating residues of singularities

Question:
I'm trying to calculate the residues of
$\displaystyle\frac{z^{1/2}\log\left(z\right)}{\left(\,1 + z\,\right)^{2}}$ at its singularities.
I've so far got that there is a pole of order $2$ at $z = -1$ and the residue at this point is $\pi/2 -\mathrm{i}$ but my final answer for the question ( a contour integral ) is not correct and also Wolfram says that this function has no poles so I'm a bit confused as to where I went wrong.
Comment: The pole is at $-1$ rather than at $1$, provided one uses branches of the square root and the logarithm that are defined there. Note that the residue depends on the chosen branches then. Wolfram probably uses the principal branches, which are defined on $\mathbb{C}\setminus \{ t \in \mathbb{R} : t \leqslant 0\}$, and so omit the potential pole from the domain of definition.
Comment: Apologies  I meant $z=-1$,  and both branches I'm using take values $\theta \in (0,2\pi)$
Comment: Please, shows explicitly the integral you want to evaluate.
Comment: So $f$ is meromorphic on $\mathbb{C}\setminus \{ t \in \mathbb{R} : t \geqslant 0\}$, with its only pole at $-1$. One can probably tell Wolfram Alpha to use these branches, so that it can compute the residue. What contour integral are you trying to evaluate?
Comment: The integral of the above function from $0$ to $\infty$ using a keyhole contour with a cut on the positive real axis
Comment: Since $$\lim_{\varepsilon \downarrow 0} \log (x - i\varepsilon) = \log x + 2\pi i\,,$$ the integral over the keyhole contour comes out as $$2\int_0^{+\infty} \frac{\sqrt{x}\,\log x}{(1+x)^2}\,dx +2\pi i \int_0^{+\infty} \frac{\sqrt{x}}{(1+x)^2}\,dx\,.$$ Use the same contour to evaluate $\int_0^{+\infty} \frac{\sqrt{x}}{(1+x)^2}\,dx$.
Comment: Would I not need the residue to work the final answer out?
Comment: Yes (well, there are other ways than the residue theorem …), you need the residue of both functions at $-1$ to evaluate the integral(s).
Answer: Despite you may find $z=-1$ as second order pole of $\displaystyle\frac{1}{(z+1)^2}$, it's not an isolated singularity of whole function because of $\log(z)$. The singularities of $\log(z)$ are on $z\leq0$ and residue can't be defined as well.
Comment: so does that mean the residue for this function doesnt exist?
Comment: Yes. It doesn't exist in any point since the only points probable to be singularity/ies is z=1.
Comment: Why would z=1 even be a probable singularity?
Comment: Sorry for the mistake! I mean z=-1.....

Calculating residues of singularities


Paypal Rest API Payment or Braintree Payments

Question: I used the Paypal NVP API (Express checkout) for a long time and it worked fine. I'm now developing a new project and wanted to use the 'new' Rest API that Paypal recommends for new projects. I, however, find the documentation rather imprecise at some points and often contradictory.
I'm using their sandbox to test the payments and I noticed that the payments work fine, except that once I log in to the Paypal Buyer account, I can only select the PayPal balance to pay.
Is this a limitation of the Rest API? I want to clarify that I am based outside the US and I do not want to accept credit card payments on my own website (well, if there is no other solution, I would accept it). I'd rather have the user get redirected to the PayPal page and provide his credit card information over there. I do, however, want to give the option to the user to at least select from PayPal balance or credit card. (As I'm used to from the NVP API)
UPDATE
In the meantime, I've done a lot of additional research. On the PHP SDK page, they've added the following notice:

Important: The PayPal REST API no longer supports new direct credit card integrations. Please instead consider Braintree Direct; which is, PayPal's preferred integration solution for accepting direct credit card payments in your mobile app or website. Braintree, a PayPal service, is the easiest way to accept credit cards, PayPal, and many other payment methods.

How should I understand the direct credit card integration? Is that the credit card payment on the PayPal website after being redirected onto that page or do they mean credit card payments where the card number is provided on ones own website?
I've got the impression, PayPal is entirely shifting to Braintree Payments. Even on the official PayPal Developer website, they propose Express Checkout for quick (client side only) integrations and Braintree Direct for other payments.
This is what I need:

PHP integration of the API calls
Payment methods: PayPal balance, Different Credit Cards
eventually recurring payments

I do not need:

Third party invoicing
client management
shipping address management

So my concrete questions would be:

What's the difference between Braintree and PayPal payment methods (since they belong to the same organisation)?
Should I use PayPal Rest API or Braintree solutions in my case?
What are those PayPal limitations that they list on their website?

Has nobody got any experience in this domain? Even partial answers are welcome!
Comment: I'm super hung up on this also, I'm building a Rest API app to be used by Philippines Merchants.

In regards to this question did you manage to find the answer "How should I understand the direct credit card integration? Is that the credit card payment on the PayPal website after being redirected onto that page or do they mean credit card payments where the card number is provided on ones own website?" Much appreciated!
Comment: Unfortunately, I did not. I have not yet tested it in production, either. I did however find that the documentation is being updated and some explanations are way clearer now than they were before. But, still looking for the right answers to the questions. I'll keep you updated as soon as I know more.
Answer: I have partial answer, as I am also in the process of choosing between BrainTree, PayPal Rest API, and Express checkout.
I'm here to answer "How should I understand the direct credit card integration?"
I'm no expert on the subject, but during my recent work at the area of integration with checkout systems, I've learned this:
One of the types of credit-cards is called "direct credit card". It means that it is directly connected with a bank account - when it is billed, the money is instantly transfered from the connected bank-account to the merchant. This is different than how most credit-cards work - most will only charge the bank-acoount at the beginninng of the next month.
I've come accross situations where direct cards behave differently than regular credit-cards.
For instance - the checkout-system I integrate with doesn't allow to monthly-bill a direct card. direct card on a monthly payment plan have to be billed manually.
So for me, the PayPal announcement you qouted means a lot - I need to support direct credit cards, hence I'm choosing BrainTree. Thanks!
Note to moderators:
I originally wanted to post this as a comment to the question, becuase I thought it would help the OP. I don't have enough reputation to comment, so I posted an Answer.
Comment: A partial answer, with some insights and "observations from the wild" are an accepted participation in the answering process here at StackOverflow; especially while no better complete answer is available.
Comment: Thanks for your answer, @pinkasey. I'm however not sure if PayPal isn't using `direct credit card payment` as `direct credit card accepting on your own website without being redirected to PayPal`. You may be right, of course. These PayPal documentations are completely unclear.
Comment: I think you're right, @Lozik -
I've been browsing through PayPal documentation all day, and came accross this:

`Important: The use of the PayPal REST /payments APIs to accept credit card payments is restricted. Instead, you can accept credit card payments with Braintree Direct. `

here:
[https://developer.paypal.com/docs/api/payments](https://developer.paypal.com/docs/api/payments/)
Comment: Thank you @pinkasey, and again, the PayPal docs are unclear: They do not specify what they mean by `restricted`, neither if they mean payment by credit card in general or only the credit card payments that can be done without leaving the own website. I think the best we can do is test, test, test and test again. Until now, I've tested the REST API with their sandbox and I didn't come across any restriction. (see my use case in my initial question) (1/2)
Comment: The only thing I noticed was that if the user doesn't log in, he can pay by credit card but once he logged in, he can't anymore. Don't know if thats an issue with my precise API settings, sandbox user settings or a wanted behaviour. But unless someone from PayPal tells us exactly what they mean, it's quite hard to find out. If I remember correctly, their developper-support redirects to stackoverflow. (2/2)
Comment: I see this restriction on their v1 REST API's, but I don't see the message on their v2 REST API page. Anyone know if credit card processing is restricted on V2 REST API's?
https://developer.paypal.com/docs/api/payments/v2/
https://developer.paypal.com/docs/api/payments/v1/


Show custom entity bundle field

Question: I created an module polls and entity poll using Drupal Console
I want to add default entity_type on installation.
Currently I added only one field to it field_image.
I created following files
FILENAME : field.field.poll.article.field_image.yml
langcode: en
status: true
dependencies:
  config:
    - field.storage.poll.field_image
    - polls.poll_type.article
  module:
    - image
id: poll.article.field_image
field_name: field_image
entity_type: poll
bundle: article
label: Image
description: ''
required: false
translatable: true
default_value: {  }
default_value_callback: ''
settings:
  file_directory: '[date:custom:Y]-[date:custom:m]'
  file_extensions: 'png gif jpg jpeg'
  max_filesize: ''
  max_resolution: ''
  min_resolution: ''
  alt_field: true
  title_field: false
  alt_field_required: true
  title_field_required: false
  default_image:
    uuid: null
    alt: ''
    title: ''
    width: null
    height: null
  handler: 'default:file'
  handler_settings: {  }
field_type: image

FILENAME : field.storage.poll.field_image.yml
langcode: en
status: true
dependencies:
  module:
    - file
    - image
    - polls
id: poll.field_image
field_name: field_image
entity_type: poll
type: image
settings:
  uri_scheme: public
  default_image:
    uuid: null
    alt: ''
    title: ''
    width: null
    height: null
  target_type: file
  display_field: false
  display_default: false
module: image
locked: false
cardinality: 1
translatable: true
indexes:
  target_id:
    - target_id
persist_with_no_fields: false
custom_storage: false

Field is created but it is coming as hidden in Form. How can I show it when modules get installed.
Please suggest.
--
Thanks
Answer: Configure the field in the form display, export this file
core.entity_form_display.poll.article.default.yml

and put it in the folder /config/install. Remove the uuid line from the yaml file.
Comment: It worked like charm.

Show custom entity bundle field


Bootstrap 4 full height template

Question: I have been trying for ages to make this work but have not been able to
get it to where I need it. Due to using React the markup is slightly more complex than a standard bootstrap template:

            ...

                    sidebar

                    main content

I am trying to get the sidebar column and the main content column to fill the screen. The closest I have got is that they are 100% height but then that makes the page longer than it actually is.
Any ideas would be great. Thanks!
Update:
I have just done the same setup in a pure html file and it works, it looks to be something that is happening in webpack/react
Update:
A little more research and I have a further understanding of what is going on.
So, setting height: 100% on and element doesnt make any difference, #root is full height using min-height: 100vh which is greate but adding height:100% to anything beneath that does absolutely nothing
Comment: it might be caused by navbar you are adding(if it is not fixed). I suggest you to make it fixed. Then you can give your container fluid a top padding as high as navbar.
Answer: Since you're using React the problem might be that you use class instead of  className.

            ...

                    sidebar

                    main content

Comment: thanks but i just put a simplified version in here as not everybody would know className. But in my actual code I do use className

Bootstrap 4 full height template


How to get the true client IP when a reverse proxy sets the value in a custom header rather than in X-Forwarded-For (HTTP_X_FORWARDED_FOR)

Question: I was working with a Drupal site that sits behind a load balancer and a varnish cache - 2 proxies. The true client IP is not present in the X-Forwarded-For header ($_SERVER['HTTP_X_FORWARDED_FOR') but is present in $_SERVER['HTTP_X_REAL_IP']
The IP that Drupal detects is interestingly from some hostname lookup and not present in any of the $_SERVER variables.
I don't have control over the infrastructure team to fix the HTTP_X_FORWARDED_FOR at the network level. I will need to fix it in settings.php. Now that Symfony is handling the IP detection, was wondering what $_SERVER variable should be altered in settings.php to get Drupal to detect the actual client IP.
Comment: After setting up the DrupalKernel Drupal's index.php initializes `$request = Request::createFromGlobals()`, and createFromGlobals uses `$_SERVER` directly as `$request = self::createRequestFromFactory($_GET, $_POST, [], $_COOKIE, $_FILES, $_SERVER)`.
Comment: I deleted my answer as not really answering the question. If Apache, you can try copying one header value to another with a technique like this: https://stackoverflow.com/questions/30703952/how-to-convert-a-http-header-into-another A technique like that will provide HTTP_X_FORWARDED_FOR from the HTTP_X_REAL_IP value before the request reaches Drupal.
Comment: I believe you can set $_SERVER variables directly in settings.php and printing $_SERVER seems to be printing the revised variables. I tried setting HTTP_X_REAL_IP as the first item in the HTTP_X_FORWARDED_FOR variable (comma separated string) but did not seem to help. Might need to read through how symfony parses these header values to really figure this out. Was wondering if somebody already has this figured out.
Comment: If PHP does not get `$_SERVER['HTTP_X_REAL_IP']`, there is not much you can do. You can set it with another value from `$_SERVER`, assuming it contains an equivalent value.
Comment: This does not seem a question which requires Drupal expertise to be answered. Drupal does not have control over the values contained in `$_SERVER`.
Comment: Thanks for looking into this @apaderno. Maybe the question will need edits. The scenario is that Drupal is not getting the true client IP because of the way the headers come to the application. The question is to figure out what we should alter in $_SERVER to make the symfony request processing get the true client IP.
Comment: If Drupal does not remove `$_SERVER['HTTP_X_REAL_IP']` or change that value, there is nothing that can be done from Drupal side. That is why this question does not require Drupal expertise. If the answer does not change for Drupal, it is not on-topic for us.
Comment: The point is to not have my custom code get the IP from the custom header but about having Drupal detect the IP correctly in all places an IP is used. Eg: floods limits, dblog etc. So the question is what do we manipulate in settings.php to get the desired behavior.
Comment: The actual header to edit is X_FORWARDED_FOR. Is that your question?
Comment: Thanks again @cilefen. Am working on this issue now. Will fix this and post the solution to the problem with findings.
Comment: Thanks for your patience. Have added my answer below.
Answer: To make Drupal detect the IP of the client correctly you will have to update $_SERVER['HTTP_X_FORWARDED_FOR'] by prefixing the true client IP to it or setting it to the true client IP itself.
$_SERVER['HTTP_X_FORWARDED_FOR'] = $_SERVER['HTTP_X_REAL_IP'] . ', ' . $_SERVER['HTTP_X_FORWARDED_FOR'];

or
$_SERVER['HTTP_X_FORWARDED_FOR'] = $_SERVER['HTTP_X_REAL_IP'];

The challenge is that by the time settings.php is parsed, the Request class has already been instantiated and the server variables have already been processed and loaded into the request object. So doing this in settings.php will not help solve the problem.
In index.php
$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();

settings.php is processed in $kernel->handle.
By then $request has already been loaded with values from $_SERVER
So to make Drupal detect the correct IP you will have to patch index.php to add the below line before $request is initialized.
There is likely a PHP OOPs / Symfony approach by overriding some class / extending some class to fix this more appropriately but this will solve the problem.
Comment: The header is `X-Forwarded-For`. `HTTP_ X_FORWARDED_FOR` is a Symfony Framework constant. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
Comment: Oh hold on: this isn't headers. It's what that header becomes in PHP superglobals. Ignore that comment. But I think the Question needs some cleanup to clarify HTTP header vs header-as-transformed into a $_SERVER value.
Comment: Thanks for the feedback. Does that look better now?
Comment: Yes, thank you.


Asp Mvc one way model property, i.e. from client only

Question: Is there an attribute or something similar in Asp MVC to indicate that a property should only come from the client, i.e. it shouldn't be roundtripped.
So
@Html.HiddenFor(x => x.MyProp)

I set this somehow on the client together with some other properties, it goes the server, server has a model error so sends it all back. I don't want this one property to be roundtripped.
The best I can think of is to do this
<input type="hidden" name=MyPropOneWay />

Then I manually insert it at the controller end into the property
(Addition)
It's not to avoid model errors, it's because there are a few ways of submitting the form, this is a shortcut method. In no circumstance do I want this value to be roundtripped as otherwise it will look like it's been set when it hasn't, however I do want everything else to be roundtripped
Thanks
Comment: there will be model error only when you use some model validations on a field if you will not use any data annotations on a field then it will not create any model error.
Comment: Details added, it's not to avoid model errors
Comment: You can use `ModelState[your Property].Errors.Clear();` to clear the errors for a property
Comment: It might be that there aren't any model errors but I still don't want this value roundtripped
Comment: @MemetOlsen, Hadn't seen the edit :). But if the property is reset in the controller, then its still required anyway (otherwise the value will be taken from `ModelState`, not the property value).
Comment: I don't want it to be taken from the controller, or the ModelState. I don't want it to come from the server side at all, hence the term oneway
Comment: Then don't make it a property of your model.
Comment: I still need it to come back, which I can do by looking in Request.Params. It might be thats what you have to do
Comment: Could you change your POST controller method to accept  `FormCollection` instead of the model?
Answer: If you don't want the value rendered from the server (either initially or after a roundtrip), use:
<input type="hidden" name="@Html.NameFor(m => m.MyProp)" />

This will render an input hidden element without a value, but it will still have the correct name to automatically bind to your model on form submission. Which effectively makes it "one way".
(The NameFor helper was added in MVC4)
Comment: Sounds ideal, thanks for that :-) (sorry for the delay, was on a support call)


How $form_state->setRebuild(); works?

Question: I have created one form. In function buildForm() I'm firing query by getting parameters from url.
So suppose my url is [example.com/myform/myshort-title][1]
Now during form build, it gets the default argument as url parameter, and render results of query.Let's say my query result is an array of entity ids.
$entityids = array(1,2,3,4,5,6);
public function buildForm(array $form, FormStateInterface $form_state, $short_title = '') {

$query = \Drupal::entityQuery('mycustomentity');
$query->condition('colname', $short_title);
$entity_ids = $query->execute();

}

Now in  form submit handler, I'm rebuilding form state like shown below:
class MyForm extends FormBase {
  protected $myvar;
  protected $step;
  protected $correct_ans;

  public function buildForm(array $form, FormStateInterface $form_state, $short_title = '') {

    $query = \Drupal::entityQuery('mycustomentity');
    $query->condition('colname', $short_title);
    $entity_ids = $query->execute();
    $i = 0;
    foreach ($node_storage as $nodeID=>$nodeData) {
       if ($i == $this->step)  {
echo $this->correct_ans;

       $correctAns = CategoryController::getCorrectAnswer($op,$entityid);
       $form['answer'][$i] = array(
            '#type' => 'hidden',
            '#value' => $correctAns,
      );
     }
    }

    }
public function submitForm(array &$form, FormStateInterface $form_state) {
$aString = $form_state->getValue('answer');
foreach ($aString[0] as $key1 => $value1) {

                         $this->correct_ans= $value1;

}
   $form_state->setRebuild();
   $this->step++;

    }

}

Debugging results give:
At first, when form gets loaded, it takes default parameter as argument from url == short_title.
print_r($entity_ids); gives array(1,2,3,4,5)
print_r($correctans); echo "
";gives arary(0=>myanswer1)
Hit Submit

array(1,2,3,4,5) array(0=>myanswer1)
array(1,2,3,4,5) array(0=>myanswer1) array(0=>myanswer2)
  array(0=>myanswer1) array(0=>myanswer3)

and echo $this->correct_ans; always gives myanswer1.
On every form submit form gets rebuild and $this->correct_ans takes default array value which is array(0=>myanswer1)
But I want, On first submit, I get array(0=>myanswer1), On second submit I want array(0=>myanswer2), On third submit I want array(0=>myanswer3) and so on...
Where I'm doing mistake?Please help.
Comment: use $form_state to store the variables, not class properties, see http://drupal.stackexchange.com/questions/227091/should-i-save-temporary-data-in-form-state-or-in-my-form-class
Comment: please explain it more, what i store in form_state, how?
Answer: You are trying to store state values into a protected variable in the class. That will not work. You will have to store state values into the form.
So instead of using
$this->step

and other class properties to store values use
$form_state->set('step', $value);

to persist values between submissions.

How $form_state->setRebuild(); works?


Cisco router password change and now select VOIP phones not working

Question: I manage this school network and I went in today to reset the password on their Cisco 2800 series router.  I didn't have the original password on the system because it wasn't shared with me and the only person that knew it had left, so I had to do the password recovery steps from here.
The password recovery went fine and I was able to change the passwords on the router to something new.  I did change the password for the "web admin" under "telephony-service" section also in my password resetting routines.
So after I did all this all was seeming to work fine, until I was about to leave and found out that some office phones weren't working, and some were.  The model phones that weren't working were the Cisco 7960 IP Phones, but the models that were working were the Cisco 7906 IP Phones.  The 7960 phones were taking a long time to sync up with the VOIP server, which is the router.  After a while the phone would say "Configuring VLAN", then it would goto "Configuring IP", then after a short time on that it would say "no load specified" and repeat the same process over and over.  I've done some research and the "no load specified" refers to the phone not being able to load a configuration from the TFTP server, if I understand correctly.
So..
--Can my password reset operations cause something to happen with the TFTP server authentication?
--How can I check to see if the TFTP server is working fine?
--Why do some phones work fine?
This is the running-config.  I didn't change any other settings in the running-config, only reset the passwords, and the phones were working just fine before the password reset.
Also, I'm not a Cisco professional, I know enough to go into the console, and run commands.  So please be thorough with your instructions of things to try and what they mean.  I want to have an understanding of commands before applying them.
Any help is appreciated.
Comment: Do the phone shows up if you do 'show cdp neighbor' on the switch they connected to?
Comment: They are connected to a LinkSys POE switch, when I run that command on the router it just shows me the FastEthernet interface on the router and "Fas 0/1            129          S I      WS-C3560- Fas 0/1" as the information.
Comment: If you could post the config for the Cisco and the LinkSys if it has one, that would probably get us closer to the problem.
Comment: FYI, I posted a link in my question.
Comment: On the phones having problems, does the Network Configuration on the phones having the correct DHCP Server address?  Do the settings match the other phones?  If not, what are the differences?
Comment: Have you had a chance to look at the running config?  Thanks.
Comment: @Joseph, yes, the settings on the phone don't seem to have changed, the information entered into the config seem to match up with information in the running config.
Comment: @Joseph, also, I don't know how to get to the configuration information on the phones that are working, they are the 7906 and have different buttons than the 7960 phones.
Comment: Press the button with the globe on it to the right of the up and down arrow button and choose Settings > Network Configuration.
Answer: I'd agree with Joseph, above. Let's start from the bottom of the network and work up.

Are the 7960's getting a good IP address?  Press the Settings key, choose Network Configuration, and (I think) IPv4 Configuration (or IP address). Is the IP address sane?
Are the 7960's receiving the option 150 properly from the DHCP server? Using the above method, does the TFTP server show 172.16.10.1?
Are the 7960's asking for something weird from the TFTP server? Get into the 2800 and issue "debug ip tftp". From a console you'll see error messages. From a Telnet or SSH session, issue "terminal monitor" and you'll get the error messages. On a phone reboot, what do they ask for?
What about the 7940's (ephone 2-4)? Do they work?
Answer: I found out the router was hacked or sabotaged remotely by the old company or people that managed the network.  There was some political things happening at the time.  It required calling Cisco for support in getting the phones operational again.
Answer: My best guess as to what happened is that the phones were added to the running config on the router.  The running config was never copied to nvram.  When you reset the password, the nvram config is what was used to boot up the router.
Since some phones work, I bet that everything is working just fine.  You probably just need to reconfig the phones into the system.
Comment: The phones are still in the running config, for example, extension 101 is in the system:

!
ephone-dn  2  dual-line
 number 101
 label Extension 101
 description Extension 101
 name Extension 101
 call-forward busy 900
 call-forward noan 900 timeout 10
 huntstop channel
 hold-alert 30 originator
!
!
!
ephone  2
 mac-address 001C.58F9.2A0D
 username "user" password pass
 type 7940
 button  1:2
!

Also, what you speak of, if the running config was not copied to nvram, wouldn't rebooting the router lose the phones?  If so, I have rebooted this router before without losing phone functionality.
Comment: Well, that didn't work out too well.  Sorry for the lack of formatting for easy reading.
Comment: If you rebooted before and didn't loose the phones, then I missed it with my guess.
Answer: If you want to perform a CISCO router password change, learn how it is done easily in a few steps, here:
http://www.brighthub.com/computing/hardware/articles/92933.aspx
Comment: This isn't helpful at all.


Determine the oldest file in a directory

Question: I am currently working on a project where I need to find the oldest file from a base name within the directory.
For example the base name of the file may be mylog but it will need to look at all files like mylog_060620121421.txt. From all the files that are mylog_ I need to find out which file is the oldeest, i.e. created first but I can't find how to do this.
I've seen the scandir command to list the file names but I can't see how it can be used to find the oldest date of the file.
Comment: Do you need to do it programmatically?
Comment: It is to be done programatically within the c program. I haven't yet tried anything specific for the oldest file, only the part where using scandir to read all the files and check if the file contains log file and print the name of it, that's about it so far, but I can't find anything for the main part of finding out the oldest file.
Comment: Take a look at getting a substring from your file name for the relevant portion (looks like from 6 - 14) and working from there :) Is this homework?
Comment: I've said that I've got that bit working, the problem I'm having is finding which of the found files is the oldest.
Comment: What's your working platform? Windows or Linux? If Linux, we cannot get creation time of a file IIRC.
Comment: Its on linux, you should be able to get the last modified time as I have done this before. Once the file is created it will never be written to again so the last modified time is suitable for this
Comment: Ok so you have the "creation time" of each file based on its last modified time, now you need to find the oldest one?  Search through them all for the oldest one, I don't see any other way to do it in C.
Answer: On linux just type in the dir:
ls -trl

This gives a list, beginning with the oldest file. If you want the name directly you can get it with:
ls -tr | head - 1

Comment: Thanks this worked great, was just wondering though is there a way that this could also be done on Windows, i am primarily doing it for linux but ideally it should support both. I was thinking the method I am using could have a check to see if its windows or linux and run the correct method for achieving this task.
Comment: The question is tagged with C.  It seems that should be removed, or the other C answer should be accepted.
Answer: Use stat()
Run the command "man -S 2 stat" to read more about it.
#include <sys/stat.h>
struct stat structstat;
stat(filename, &structstat)
printf("last modified time: %s", ctime(&structstat.st_mtime));

where filename is a string/char * representing the file
structstat is a structure of stat which can be found in sys/stat.h
the oldest file will be one with the oldest modification time, structstat.st_mtime unless you have both, then you can use the structstat.st_ctime (status change) for the type breaker...


Turning rows to columns in postgres

Question: I have one table with rental contracts. (Postgres v10.18)
Like this:
Table Rental
Id          Start       Main_tenant_id  Obect_id
101011          1.1.2021    1000            200
100222          1.1.2021    2050            210

If the Object has more than one Tenant the other ones a saved in a separate Table like this:
Table Rental_extra
Id          rental_id   xtra_tenant
20001           100222      3000
20002           100222      2700
20003           100222      2800

And i have a Person table like this:
Table Person
Id          first_name      last_name
1000            Peter           Mcdonald
2050            Dan         Hunt
3000            Steve           Cole
2700            Ian         Wright
2800            William         Pears

Now i need to get this output:
Goal
Id      tenant 1        tenant 2        tenant 3        tenant 4
101011      Peter Mcdonald  null            null            null
100222      Dan Hunt        Steve Cole      Ian Wright      William Pears

What's the best way? I tried with some crosstab example but couldn't make it work.
Comment: We very much prefer data as *text*. One cannot copy/paste from an image.
Answer: SELECT *
FROM   crosstab(
$$
SELECT t.id, tenant_nr, concat_ws(' ', p.first_name, p.last_name)
FROM  (
   SELECT id, 0 AS tenant_nr, main_tenant_id AS tenant_id
   FROM   rental
   UNION ALL
   SELECT rental_id, row_number() OVER (PARTITION BY rental_id ORDER BY id), xtra_tenant
   FROM   extra_tenant
   ) t
JOIN   person p ON p.id = t.tenant_id
ORDER  BY 1 DESC, t.tenant_nr
$$
) AS goal(id int, tenant_1 text, tenant_2 text, tenant_3 text, tenant_4 text);

db<>fiddle here
Detailed explanation here:

PostgreSQL Crosstab Query
Postgres - Transpose Rows to Columns

Turning rows to columns in postgres


How to prove the fraction identity without using calculator

Question: How to prove without calculator that
$$ \frac{1}{1001} + \frac{1}{3001}  > \frac{1}{1000}$$
Comment: Think about what the sum of the fractions produces (_don't_ multiply out the denominator!).  How might you make a comparison of that sum to 1/1000?
Comment: Multiply everything by $1001 \cdot 3001$
Answer: $$\frac{1}{1001}+\frac{1}{3001}=\frac{3}{3003}+\frac{1}{3001}>\frac{3}{3003}+\frac{1}{3003}=\frac{4}{3003}>\frac{4}{4000}=\frac{1}{1000}$$
Answer: HINT:
$$\frac1{1000}-\frac1{1001}=\frac{1001-1000}{1000\cdot1001}=\frac1{1000\cdot1001}<\frac1{3001}$$


Generalizing $\int_{0}^{\infty }\frac{f(t)}{t}dt=\int_{0}^{\infty }\mathcal{L}\left \{ f(t) \right \}ds$.

Question: Here, I saw the following formula:
$$\int_{0}^{\infty }\frac{f(t)}{t}dt=\int_{0}^{\infty }\mathcal{L}\left \{ f(t) \right \}ds$$

Say we have the integrand only $f(t)$, not $\frac{f(t)}{t}$, then I think we can multiply and divide this integrand by $t$, then we apply the formula. For instance, if the integrand is $te^{-t}$, then we should rewrite it as
$$\frac{t^2e^{-t}}{t}$$
So $f(t)$ is actually $t^2e^{-t}$, not $te^{-t}$.
I know that if the integrand is $te^{-t}$, then it can be done by integrating by part. However, I think it is a good looking function to illustrate my question.
Am I right about multiplying and dividing by $t$ just to make a use of the formula?
In other words, is the following true?
$$\int_{0}^{\infty }f(t)dt=\int_{0}^{\infty }\mathcal{L}\left \{ tf(t) \right \}ds$$

Second Question:
Can we, somehow, generalize the formula to any interval $(a,b)$ instead of $(0,\infty)$?
I know that the Laplace will have the same limits of integration, $(0,\infty)$ but I am asking about the original integral, not the integral from the $\mathcal{L}$.

Sorry for my bad English, hope my questions are clear. Your help would be appreciated. THANKS!

Edit:
For the second question, what I mean is
Given $a,b,$ and $h(x)$, and that $\int_{a}^{b}h(x)dx = \int_{0}^{\infty}r(t)dt$. How to find $r(t)$?
This will make use of the first formula in this post.
For instance, $\int_{1}^{2}\sqrt{4x(2-x)}dx$ can be replaced by $\int_{0}^{\infty} \frac{dt}{1+t^2}$. And now we can use the above formula.
Comment: In [general](https://en.wikipedia.org/wiki/Laplace_transform#Evaluating_integrals_over_the_positive_real_axis), $$\int_{0}^{\infty} f(x) \cdot g(x) \, dx = \int_{0}^{\infty} \{\mathcal{L} f\}(s)\cdot\{\mathcal{L}^{-1} g\}(s) \, ds$$ Set $g(x) = \frac{1}{x}$ and this yields your first formula. There are no such symmetries for an arbitrary interval $(a,b)$.
Answer: For your new question , use the transformation $y=\frac{x-a}{b-x}$ and then $x=\frac{yb+a}{1+y}$ and $dx=\frac{(b-a)dy}{(1+y)^{2}}$. Thus the l.h.s integral can be written as $\int_{0}^{\infty }h(\frac{yb+a}{1+y})(1+y)^{-2}(b-a)dy$. therefore you have the $r(y)$ you wanted!!
Answer: Write the r.h.s integral as $\int_{0}^{\infty }\int_{0}^{\infty }tf(t)e^{-st}dtds$ and change the order of integration. Then
$\int_{0}^{\infty }$$tf(t)e^{-st}ds=tf(t)(1/t)=f(t)$ and hence your claim is true!
Comment: The second question is not clear as you have put it. Please give it a more concrete form.
Comment: What about the main question (the second question)?
Comment: Could you please check my edit? Hope it is clear now, and hope you can help. THANKS!


How do I incorporate personalization to a Bayesian ranking engine?

Question: I'm looking to quickly get smart on how to add personalization into a Bayesian-based recommendation system.
I'm using clickstream data and Bayesian statistics to estimate probabilities of purchase to rank a list of products on.  How do I incorporate user-specific history to modify my generic probabilities for a specific user?  For example, a user clicked a product in a previous site visit.  How do I estimate the purchase probability during a successive visit?  What is the standard approach here?
Looking for papers, blogs, people  that can help illuminate.
Answer: Look into using Collaborative Filtering (CF) via Matrix Factorization in machine learning to get personalization. You can use CF w/ the Bayesian Personalized Ranking (BPR) cost function if you want to keep the Bayesian connection. See this paper: https://arxiv.org/abs/1205.2618 and this intro into recommender system using machine learning: http://www.eggie5.com/99-recommender-systems


Change paragraph text when bullet slider (swiper.js) is clicked not working on Elementor

Question: So I have this website that uses Elementor Builder and a slider showing some images and I'd like to change a paragraph text above the slider depending on the image.
The thing is that the bullets do not have an id assigned so I tried to do it using javascript.
I'm trying to use vanilla javascript.
Code below:

       var bulletFloors = document.querySelectorAll('.swiper-pagination-bullet');

       for (var i = 0; i < bulletFloors.length; i++)
       bulletFloors[i].id = 'bulletFloors-' + i;

        function floort1() {
        document.getElementById('desc_apartamento').innerHTML = "Paragraph text 1.";
        }

        function floort2() {
        document.getElementById('desc_apartamento').innerHTML = "Paragraph text 2.";
        }

    function floort3() {
        document.getElementById('desc_apartamento').innerHTML = "Paragraph text 3";
    }

    function floort3village() {
        document.getElementById('desc_apartamento').innerHTML = "Paragraph text 4.";
    }

    function floort4() {
        document.getElementById('desc_apartamento').innerHTML = "Paragraph text 5.";
    }

    document.getElementById('bulletFloors-0').onclick = function() {
        floort1();
    };
    document.getElementById('bulletFloors-1').onclick = function() {
        floort2();
    };
    document.getElementById('bulletFloors-2').onclick = function() {
        floort3();
    };
    document.getElementById('bulletFloors-3').onclick = function() {
        floort3village();
    };
    document.getElementById('bulletFloors-4').onclick = function() {
        floort4();
    };

What am I doing wrong?
Comment: You can send visual example of your slider? Maybe link to your site? Are you doing something wrong initially, why are you assigning text from js, and not through the slider options? through the admin panel?
Comment: I can't send the link because the website is in private mode. I need to place the text outside the slider. That's why I have to control it with javascript.
Comment: It doesn't matter, everything related to content should come from the admin panel. Create all 5 paragraphs on the page one after another and hide them using css and add the "Show" class to the active paragraph, you must give the ability to change the content through the admin panel, your logic is not correct
Comment: And also you shouldn't hack by clicking on bullets, you should use the api of your slider, tell me which plugin/widget do you use? Can you send a link to it? swiperjs ? Indicate in your question which slider you are using!
Comment: Thanks for the tips. I'm using swiper.js
Comment: Please indicate this in your question, otherwise your question will be useless and get negative response, and try to rephrase your question in relation to slides and a specific slider
Answer: If you are using wordpress or other CMS you should always avoid unnecessary hacks, especially related to content! Do not add any content via js code!
If you are already in an environment where jQuery is supported, do not be afraid to use it.
What should you do?

Create all your pararaphs with your builder on the page, one by one!
Give each paragraph or rather your paragraph widget (text widget) an
arbitrary class, for example a "dynamic-paragraph" and assign a unique class by index to all paragraphs, example: .p0, .p1 etc
Hide all your paragraphs with css

.dynamic-paragraph {display:none}

Avoid hacks such as "click on bullets" this is not an option! Because the slider can be swapped, it can have arrows for move slides, etc. Thus, you cannot provide a 100% chance that your paragraph will have dynamic text depending on the slide change! Therefore, find out the name of the slider and use its api!
I think you are using swiper.js, then see this link
You can get access to the slider:
const instance = jQuery('#my-id .swiper-container' );

// or

(function($) {
const instance = $('#my-id .swiper-container' );
})(jQuery);

Tip: where #my-id .swiper-container - selector to your slider
And then use the api slider
(function($) {
const instance = $('#my-id .swiper-container' );
instance.on('slideChange', function () {
  let activeSlide = instance.activeIndex;
  $('.dynamic-paragraph.show').removeClass('show');
  $('.dynamic-paragraph.p'+activeSlide+').addClass('show');
  console.log('slide changed');
});
})(jQuery);

etc
Comment: it did't work. Console shows no error. I don't get it.
Comment: show me a part of html code that is rendered on the client that contains a selector


Do I really need to put unit on the graphic?

Question: I would like to add unit on this graphic:

As stated in many sources, I should place as much of the required information within the figure itself. Unit is a (very) important information so therefore I need to put it on the graphic. But where? I have a feeling that anywhere the unit is, it will make the graphic, erg, imperfect. And I think putting it in the caption won't harm the eye of readers. So do I really need to put it on the graphic?
Answer: Yes, put it on the figure.  It is useless without units.  There is plenty of space in the middle of the black bar between the -5.000 and 5.000 .
Comment: Very creative. However, if the size of the graphic is smaller, I'm afraid that people can't read it.


Transformar o eixo y em porcentagem

Question: Boa tarde,
Tenho o seguinte comando que gera o gráfico a seguir:
CANDIDATOS_2018_LEGISLATIVO %>%

  group_by(DS_ESTADO_CIVIL, DS_GENERO) %>%

  count() %>%

  ggplot(., aes(x = reorder(DS_ESTADO_CIVIL, -n), y = n,  fill =
DS_GENERO)) +

geom_bar(stat = "identity", position = "dodge") +

theme(axis.text.x = element_text(angle = 30, size = 7))

Meu objetivo é tranformar o eixo y em valores percentuais, alguém saberia qual comando necessário?
Answer: Para adicionar porcentagem ao eixo y, basta modificar a sintaxe como abaixo:
CANDIDATOS_2018_LEGISLATIVO %>%

  group_by(DS_ESTADO_CIVIL, DS_GENERO) %>%

  count() %>%

  ggplot(., aes(x = reorder(DS_ESTADO_CIVIL, -n), y = n/sum(n)*100, fill
= DS_GENERO)) +

geom_bar(stat = "identity", position = "dodge") +

theme(axis.text.x = element_text(angle = 30, size = 7))

Transformar o eixo y em porcentagem


What is the expected number of flips that are needed?

Question: Suppose we flip a fair coin repeatedly until we have flipped four consecutive heads. What is the expected number of flips that are needed?
The hint is given is as follows: Consider a Markov chain with state space {0,1,...4}.
Can anybody give an idea of where to start? Thanks! As I make progress I will add what my solution becomes. Otherwise any help would be appreciated.
Comment: I have given a [solution here](http://math.stackexchange.com/questions/364038/expected-number-of-coin-tosses-to-get-five-consecutive-heads) of the same problem with $5$ consecutive. In order to make the argument accessible to people not familiar with Markov chains, the solution did not mention them explicitly, though you will recognize transition probabilities.
Comment: I see! Thank you. I will still post my solution.
Comment: You are welcome. Other solutions there use other techniques. There is a Markov chain solution somewhere on MSE, but my search skills are limited.
Answer: Indeed let $X_n$ denote the number of consequtive heads that have flipped at time $n$. The possible states of $X_n$ are $\{0,1,2,3,4\}$ since if $4$ consecutive heads the process is considered to end. Given $X_n=j$ the next state can be either $0$ if we flip a tail or $j+1$ if we flip another consecutive head, thus $$X_{n+1}|X_n=j=\begin{cases} 0, &\text{ with probability } \frac{1}{2} \\ j+1, &\text{ with probability } \frac{1}{2} \end{cases}$$ since each event (head or tails) occurs with the same probability. Hence, the transition matrix of the markov chain is given below $$\begin{pmatrix}\frac{1}{2}&\frac{1}{2}&0&0&0\\\frac{1}{2}&0&\frac{1}{2}&0&0\\\frac{1}{2}&0&0&\frac{1}{2}&0\\\frac{1}{2}&0&0&0&\frac{1}{2}\\0&0&0&0&1\end{pmatrix}$$ where we have assumed that as long the game reaches state $4$ i.e. 4 consecutive heads the process seizes. The initial state is $X_0=0$. Let $h(j)$ denote the expected number of flips until you reach state $4$. Then you have the following system of equations $$\begin{align*}h(0)&=1+\dfrac{1}{2}h(0)+\dfrac{1}{2}h(1)\\h(1)&=1+\dfrac{1}{2}h(0)+\dfrac{1}{2}h(2)\\h(2)&=1+\dfrac{1}{2}h(0)+\dfrac{1}{2}h(3)\\h(3)&=1+\dfrac{1}{2}h(0)+\dfrac{1}{2}h(4)\\h(4)&=0\end{align*}$$ Now solve the above system recursively to obtain $h(0)$ which is the expected number of flips needed.

The solution is $h(0)=30$.
Answer: Here is my solution!
$P=\begin{bmatrix}
1/2 &1/2  &0  &0  &0 \\
 1/2&0  &1/2  &0  &0 \\
 1/2&0  &0  &1/2  &0 \\
 1/2&0  &0  &0  &1/2 \\
 0&0  &0 &0  &1
\end{bmatrix}$
We will then treat state 4 like a recurrent state and solve for the matrix of the form
$\begin{bmatrix}
I &  &  &0 \\
 &  &  & \\
 &  &  & \\
 S&  &  & Q
\end{bmatrix}$
Note: Sorry I don't know how to partition the matrix into four equal parts.
We then solve for the matrix $M=(I-Q)^{-1}$.
So we find that $M=\begin{bmatrix}
16 &8  &4  &2 \\
 14&8  &4  &2 \\
 12& 6 & 4 &2 \\
 8&4  &2  &2
\end{bmatrix}$
We then take the matrix M and add up the first row 16+8+4+2=30.


Missing required UserInfo Uri in UserInfoEndpoint for Client Registration

Question: I am facing with below error while accessing to api within OAuth2.0 credentials.
The examples on Internet containing user-info-uri credential, but I have only authorization-uri and token-uri. How can I successfully connect without user-info-uri ?
Authorization screen is successfully opened, but after that the error is shown:
[missing_user_info_uri] Missing required UserInfo Uri in UserInfoEndpoint for Client Registration: aa-client-1

My application.yml like this :

spring:
   security:

oauth2:

client:
   registration:
     aa-client-1:
      client-id: XXXX-XXXXX-XXXX-XXX
        client-secret: XXXX-XXXXX-XXXX-XXX
        provider: A
        scope: A:scope
        authorization-grant-type: authorization_code
        redirect-uri: http://localhost:8080/login
    provider:
      A:
        authorization-uri: https://someurls/authorize
        token-uri: https://someurl/token

I want to login the API without user-info-uri.
Comment: Could you add your @Configuration class?
Comment: I have no configuration class, just Application and Controller class.
Comment: Spring Security for OAuth 2 requires the user-info-uri. It uses it to get the username to build the Principal: https://github.com/spring-projects/spring-security/issues/4992
Answer: Unfortunately, you must provide an user-info-uri if your grant type is authorization_code.
See GitHub discussion and Spring Security Source Code.
Perhaps this workaround may also applicable to your context.


Is there any package in R/Python which can analyze Pos./Neg sentiment of whole review?

Question: I'm a newbie here in the forum and new to text analytics using Python and R. My question is somewhat similar to Is there a better approach than counting positive-negative words in sentiment analysis?
I'm working on a dataframe with 2000 rows of product reviews of SalesForce One app. and want to analyze sentiments. (Pos. or Neg.)
I would like to analyze each review as a whole sentence and not based on a single word per review. Reproduced the same code from the below link, but the results are highly deviated as this approach is analyzing only one word per review using AFFIN lexicon.
Link:  Does sentiment analysis work? A tidy analysis of Yelp reviews
The NLTK approach in python seems to fit my problem, but unable to understand the complex code to apply to my problem.
Sentiment Analysis
Please recommend a package/module in either R or Python which can help to analyze each review as a whole sentence. (will be glad if some rough code is provided).
Answer: I think you answered your own question.
NLTK is what you need. If you provide some example sentences it might help.
But from the link you provided to NLTK, I just reproduced their examples:

Install the VADER lexicon used:
>>> import nltk
>>> nltk.download()

A dialog pops up. Chose models and vader_lexicon and download that.
Import the analyzer and input your sentences
>>> from nltk.sentiment.vader import SentimentIntensityAnalyzer
>>> sentences = ["The book was good.",         # positive sentence
... "The book was kind of good.", # qualified positive sentence is handled correctly (intensity adjusted)
... "The plot was good, but the characters are uncompelling and the dialog is not great.", # mixed negation sentence
... "A really bad, horrible book."]       # negative sentence with booster words

Run the analysis
>>> sid = SentimentIntensityAnalyzer()
>>> for sentence in sentences:
...     print(sentence)
...     ss = sid.polarity_scores(sentence)
...     for k in sorted(ss):
...         print('{0}: {1}, '.format(k, ss[k]), end='')
...     print()

and you get the scores:
The book was good.
compound: 0.4404, neg: 0.0, neu: 0.508, pos: 0.492,
The book was kind of good.
compound: 0.3832, neg: 0.0, neu: 0.657, pos: 0.343,
The plot was good, but the characters are uncompelling and the dialog is not great.
compound: -0.7042, neg: 0.327, neu: 0.579, pos: 0.094,
A really bad, horrible book.
compound: -0.8211, neg: 0.791, neu: 0.209, pos: 0.0,

Answer: I suggest you to use more tools, like textWiller package, LDA and LSA (LATENT SEMANTIC ANALYSIS I R). There is a good software: raoidminer, it is really intuitive smart and agile. I suggest you to download it and try the trial within
Comment: Welcome to this site! Please, do not provide multiple answer when they are related. Instead, you should provide a valid URL, a short description of what the software does and ideally why you recommend them. See our [Help Center](http://stats.stackexchange.com/help/how-to-answer) to learn more.


PDF of $Y=g(X)$ when $X$ is absolutely continuous and $g$ is strictly increasing and continuously differentiable

Question:
Let $X$ be an absolutely continuous random variable with density function $f_{X}$. Suppose that $g$ is strictly increasing and continuously differentiable. Derive the PDF of the random variable $Y=g(X).$

It is given as hint to find the CDF of $Y$ first and then differentiate it to find the PDF. So I try that for a start
\begin{align*}
F_{Y}(y) = \mathsf{P}(Y\leq y) &=\mathsf{P}(g(X)\leq y) \\
& = \mathsf P(X \leq g^{-1}(y)) \\
& = F_{X}(g^{-1}(y)).
\end{align*}
And differentiating with respect to $y$ on both sides yields
\begin{align*}
f_{Y}(y)=\frac{d}{dy}F_{Y}(y) &=\frac{d}{dy}F_{X}(g^{-1}(y)) \\
&=f_{X}(g^{-1}(y))\cdot\frac{1}{g'(y)},
\end{align*}
where in the final step I used the inverse function theorem for $\mathbb{R}$.

Is this the right approach to the problem? If it is not, could you please provide a hint to put me in the right direction?
Any feedback is much appreciated. Thank you for your time.
Comment: Small issue: the derivative of $g^{-1}$ at $y$ is $1/g'(g^{-1}(y))$.
Answer:
Is this the right approach to the problem?

Yes, that is quite okay.   Your approach is appropriate, and the working correct.

When $g$ is strictly increasing and continuously differentiable, and $X$ an absolutely continuous random variable with density function $f_X$, then indeed we have the result you discovered.
$$f_{g(X)}(y) =\dfrac 1{g'(y)} f_X(g^{-1}(y))$$
Good work.


Webpack change properties to devServer

Question: i'm trying to use a plugin in my vuejs project that allows me to create projects in VUE within CMS October, however i updated my node and i believe i updated the webpack version too (from what i've researched) and now my plugin is not working for that error is occurring right on that line of code.
The properties of disableHostCheck and public no longer exist, I would like to know which one I could replace that would have the same effect?
I've been searching the webpack documentation and I couldn't understand which one would be equivalent.
<code>// configure the dev server and public path based on environment
    options.devServer = {
        disableHostCheck: true,
        public: 'http://localhost:8080',
    };
</code>
<code>ValidationError: Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
         - options has an unknown property 'public'. These properties are valid:
           object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, magicHtml?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, server?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? }
</code>
Answer: In webpack 5 is changed, please check:
<code> devServer: {
    allowedHosts: 'all',
 }
</code>

Webpack change properties to devServer


How to track an external JSON file for a change

Question: I am currently checking this file: https://api.steampowered.com/IEconService/GetTradeOffers/v1/?key=700D84417970EEAE593ACB8BE455B16E&format=json&get_sent_offers=1 for a change every 5 seconds but Is there any sort of way that I can get notified E.g. a post request when this website changes? I had a look at google push notifications but It seems that it only works for their own api's not external api's
Comment: no, that would be something the site itself has to offer/perform. you can fetch just the HEAD and examine the Last-Modified, ETag, or Content-Length headers to spot changes without refetching the data
Comment: Ok thanks! I'll ask the api providers if they offer such a service. So if they say no, is there no way at all that this could cause I really don't want to be polling every 5 seconds.
Answer: I don't know what do you mean by getting notified.
If you want to get an email when the page changes you can use something like this Google Chrome extension
If you mean it in an programmatically way, then you will have to GET the JSON object from the URL every 5 sec and compare it to the previous version, see this question regarding the compare part.
Comment: By getting notified, I want the service to send a POST request to a url that I specify. E.g. if I was tracking this JSON file: someoneswebsite.com/api/randomjson for a change then when it changes, it would automatically send a POST request to my website E.g. mywebsite.com/APIprotected/newnotification
EDIT: Is google push notifications what I am looking for?
Comment: @mre12345 What you're describing is typically called a `webhook`. If you they provide something like that it will probably be called that.
Comment: ok thanks!, I'll check if the providers of the api provide a webhook


Prove that every cycle graph $C_{n}$ contains ${n}$ spanning trees?

Question: I'm trying to come up with a proof for every cycle graph ($C_{n}$) contains (${n}$) spanning trees. I know how to explain it in plain language, and visually, but I'm having a hard time with the notation, or which is the best way to go about proving it?
Does anyone have a good proof of this or know where to start looking? Its not for an assignment, just for a study sheet to have.
Comment: There are $n$ edges, and removing an edge yields a spanning tree...
Comment: Yeah, that seemed more like the plain language explanation I already knew. I didnt know if there was something more sophisticated than that, yet less complex than the answer below.
Comment: @Math1000 I guess you also need a proof that there aren't any other spanning trees. (Something on the lines - if you remove no edges, it is not a tree; if you remove two adjacent edges, you don't cover the vertex between them; if you remove two non-adjacent edges, you don't have a connected subgraph anymore.)
Comment: Do you know that $G$ with $n$ vertices is a tree if and only if $G$ is connected and has $n-1$ edges?
Answer: I am no expert but had a quick Google search, and as soon as I found that there was such a thing as Kirchoff's theorem (https://en.wikipedia.org/wiki/Kirchhoff%27s_theorem), I thought it would be fun to use that theorem. (Seems like overkill, but there you go.)
The Laplacian matrix of this graph is:
$$L_n=\begin{bmatrix}2&-1&0&\cdots&-1\\-1&2&-1&\cdots&0\\0&-1&2&\cdots&0\\\vdots&\vdots&\vdots&&\vdots\\-1&0&0&\cdots&2\end{bmatrix}_{n\times n}$$
(All nodes of degree 2, each node adjacent to the previous and the next one.) By Kirchoff's theorem, the spanning tree number $t_n$ is given as any cofactor of this matrix, i.e. (by calculating the cofactor corresponding to the upper left corner, i.e. cross out first row and columin in $L_n$) as:
$$t_n =D_{n-1}=\begin{vmatrix}2&-1&0&\cdots&0\\-1&2&-1&\cdots&0\\0&-1&2&\cdots&0\\\vdots&\vdots&\vdots&&\vdots\\0&0&0&\cdots&2\end{vmatrix}_{(n-1)\times(n-1)}$$
Now, the above is a determinant of a tri-diagonal matrix, and it is easy to derive recurrence relation:
$$D_n=2D_{n-1}-D_{n-2}$$
(expand on the first row, and then one of the remaining smaller determinants on the first column). Having in mind that $D_1=2$ and $D_2=3$, one can use induction to prove that $D_n=n+1$, which then yields the result $t_n=D_{n-1}=n$.
Comment: +1 for applying the beautiful Kirchoff's theorem.  Although it's definitely overkill for this problem, as you say.  A good example of an [awfully sophisticated proof for a simple fact](https://mathoverflow.net/questions/42512/awfully-sophisticated-proof-for-simple-facts).
Comment: I think this is outside my knowledge range... but I appreciate it!


Query zerando coluna ao aplicar order by - Mysql

Question: Estou com uma query que ao ordenar ela em ASC ela zera uma coluna da minha tabela, porém se eu ordeno em DESC exibe os valores normalmente.
Essa é a query:
SELECT
`tab_medicamentos`.`id`, `tab_medicamentos`.`classe_terapeutica`, `tab_medicamentos`.`apresentacao`, `tab_medicamentos`.`produto` as `nome`, `tab_medicamentos`.`pmc_18_perc` as `preco`, `tab_medicamentos`.`img` as `imagens`, `tab_medicamentos`.`margem`, `tab_medicamentos`.`margem_desconto`, `tab_medicamentos`.`restrcao_hospitalar`
FROM
`tab_medicamentos`
WHERE
`classe_terapeutica` LIKE '%M01C0%' ESCAPE '!'
OR `classe_terapeutica` LIKE '%L01B0%' ESCAPE '!'
OR `classe_terapeutica` LIKE '%N02A0%' ESCAPE '!'
OR `classe_terapeutica` LIKE '%N02B0%' ESCAPE '!'
OR `classe_terapeutica` LIKE '%N01A2%' ESCAPE '!'
OR `classe_terapeutica` LIKE '%N01B1%' ESCAPE '!'
OR `classe_terapeutica` LIKE '%M01A1%' ESCAPE '!'
OR `classe_terapeutica` LIKE '%M02A0%' ESCAPE '!'
OR `classe_terapeutica` LIKE '%R05A0%' ESCAPE '!'
OR `classe_terapeutica` LIKE '%A11D4%' ESCAPE '!'
OR `classe_terapeutica` LIKE '%A03D0%' ESCAPE '!'
OR `classe_terapeutica` LIKE '%M01A3%' ESCAPE '!'
OR `classe_terapeutica` LIKE '%B01C1%' ESCAPE '!'
OR `classe_terapeutica` LIKE '%M03B0%' ESCAPE '!'
OR `classe_terapeutica` LIKE '%N02C9%' ESCAPE '!'
ORDER BY `pmc_18_perc` ASC

Quando coloco o ORDER BY ASC ele zera todos os valores dessa coluna 'pmc_18_perc', mas quando ordeno em DESC aparece os valores normalmente.
O que pode ser?
Comment: tem certeza que zerou todos ou só nos primeiros registros? porque `ORDER BY ASC` vai trazer os dados começando do "menor", zeros, espaços, etc primeiro... pode ser que os dados preenchidos estejam nos próximos registros, chegou a olhar todo o resultado do `select`?
Comment: não zerou todos os valores, apenas ordenou os que estão com valor "0"  a frente.
Comment: Tenta colocar no WHERE, pmc_18_perc IS NOT NULL
Comment: Esqueci de comentar isso, pois sabia que seria a primeira hipótese. Eu verifiquei no final do resultado, e desde da primeira linha à ultima o valor foi zerado! Nunca vi isso!
Coloquei o IS NOT NULL e não mudou nada.
Answer: Já tentou realizar a ordenação em um nível superior?
Ex:
select
* from
(SELECT
tab_medicamentos.id, tab_medicamentos.classe_terapeutica, tab_medicamentos.apresentacao, tab_medicamentos.produto as nome, tab_medicamentos.pmc_18_perc as preco, tab_medicamentos.img as imagens, tab_medicamentos.margem, tab_medicamentos.margem_desconto, tab_medicamentos.restrcao_hospitalar
FROM
tab_medicamentos
WHERE
classe_terapeutica LIKE '%M01C0%' ESCAPE '!'
OR classe_terapeutica LIKE '%L01B0%' ESCAPE '!'
OR classe_terapeutica LIKE '%N02A0%' ESCAPE '!'
OR classe_terapeutica LIKE '%N02B0%' ESCAPE '!'
OR classe_terapeutica LIKE '%N01A2%' ESCAPE '!'
OR classe_terapeutica LIKE '%N01B1%' ESCAPE '!'
OR classe_terapeutica LIKE '%M01A1%' ESCAPE '!'
OR classe_terapeutica LIKE '%M02A0%' ESCAPE '!'
OR classe_terapeutica LIKE '%R05A0%' ESCAPE '!'
OR classe_terapeutica LIKE '%A11D4%' ESCAPE '!'
OR classe_terapeutica LIKE '%A03D0%' ESCAPE '!'
OR classe_terapeutica LIKE '%M01A3%' ESCAPE '!'
OR classe_terapeutica LIKE '%B01C1%' ESCAPE '!'
OR classe_terapeutica LIKE '%M03B0%' ESCAPE '!'
OR classe_terapeutica LIKE '%N02C9%' ESCAPE '!' )  as tmp
order by tmp.pmc_18_perc desc
Comment: Tentei, porém está retornando o seguinte erro: #1054 - Coluna 'tmp.pmc_18_perc' desconhecida em 'order clause'.

Assim... Quando faço a consulta com apenas uma clausula ele faz tudo como esperado, agora quando coloca mais uma clausula ele zera todos os valores... não entendo isso.


Can a ratio of random variables be normal?

Question: For a pair of random variables $Y$ and $Z$, is it possible that their ratio $X:=\frac{Y}{Z}$ is (exactly, not asymptotically) normally distributed?
If so, could you offer an example of the distributions of $Y$ and $Z$ and the relationship between them (besides the obvious case where $Y$ is normal and $Z$ is a constant, as suggested by @gunes)?
P.S. A special case of my question has been answered here: What Ratio of Independent Distributions gives a Normal Distribution?. My question is more general than that.
Comment: @Gunes there are slightly less trivial cases.  One is the ratio of a half-normal and an independent Rademacher variable.  Apart from requiring the variables be continuous (and obviously one of them *must* be), https://stats.stackexchange.com/questions/121752/what-ratio-of-independent-distributions-gives-a-normal-distribution is exactly the same question.
Comment: You probably want to say independent RVs to exclude things like $Z^2/Z$.
Comment: Here is a related question: https://stats.stackexchange.com/questions/162483/is-the-ratio-distribution-of-two-normally-distributed-variables-ever-normal
with a useful comment just under it. It seems the trivial case is the only case for independent RVs.
Comment: It's a very good trick, i.e. Y half-normal and Z being 1,-1 with 0.5 prob.
Comment: @Hasse1987, thanks. I wanted the general case, including dependent $Y$ and $Z$. Once I got some good examples on that, the remaning interest is of course on independent cases. But that was not the sole focus of the question *before* I got the examples of the dependent cases.
Comment: @kjetilbhalvorsen, no, it does not. My question is more general as it allows for dependence between $Y$ and $Z$.
Comment: But that's no generalization, because the answer is trivial: multiply any normal variable $X$ by any variable $Z$ whatsoever (provided only it has zero chance of equalling zero) to produce $Y.$
Comment: @whuber, the applicability of the qualifier *trivial* depends on the user and more frequently holds ex post than ex ante... And to be precise, a trivial generalization is still a generalization.
Answer: A trivial case: Let $Y$ be a normal RV, and $Z$ be a constant RV, then $X$ is going to be normally distributed.
Another one: let $A,B$ normal RVs, and $C=A/B,D=1/B$ are two other RVs that belonging to Cauchy and Reciprocal Normal Distributions. Their ratio will be $C/D=A$ normally distributed.
Comment: It would be more interesting with some less obvious examples ...
Comment: Thank you! Techincally you are right. I did not exclude the constant RV case explicitly as I thought it was too obvious, but obviously it was not. I will edit my post. (P.S. I did not downvote your answer.)
Comment: couldn't understand why I'm downvoted. (thank you, I guessed that you didn't, it was a general question). It'd be interesting if we have two Rvs that are independent and their ratio is normally distributed. Otherwise, we can define any dependence relation we want just as in the example case.
Comment: The latter idea is a nice one. The case of independent $Y$ and $Z$ is even more interesting, but there is less hope there, I guess.
Comment: The answer would be improved if the contrived trivial case were removed, and the substance left.


Markov Chains on $\mathbb{C}^N$ are all the positive unital maps on $\mathbb{C}^N$

Question: Is there a biijection between all the markov chains represented by the stochastic matrices, and all the positive unital maps from $\Phi : \mathbb{C}^N \rightarrow \mathbb{C}^N$?
I mean, given any unital positive map of this kind, will this be a stochastic matrix and therefore, a representation of a certain markov chain? And why is this true?
Thanks
Answer: "Unital" in your setup is precisely "stochastic". Given one of your $\Phi$, you have $\Phi e=e$, where $e$ is the identity of $\mathbb C^N$. This equality, row by row, is
$$
1=(\Phi e)_k=\sum_j\Phi_{kj}e_j=\sum_j\Phi_{kj}.
$$
Similarly, in this context $\Phi\geq0$, means that $\Phi x\geq0$ whenever $x\geq0$. It follows that $\Phi\geq0$ if and only if $\Phi_{kj}\geq0$ for all $k,j$. Indeed, suppose that $\Phi\geq0$. Thus
$$
0\leq \sum_k \Phi_{kj}a_j, \ \ \text{ each $k$ and for all } a_1,\ldots,a_n\geq0.
$$
Taking a single $a_j$ to be nonzero, you get $\Phi_{kj}\geq0$ for all $k,j$. The converse is trivial.
Comment: Positivity in your setting is entrywise; I've added that into the answer.
Comment: Yes, they are precisely the $n$-tuples with all non-negative entries. One of several ways to notice it is that $$\mathbb C^n=\{f:\{1,\ldots,n\}\to\mathbb C\}=C(\{1,\ldots,n\}).$$ Positivity in $C(X)$ is pointwise positivity.
Comment: Thank you for your precious help Martin! So is it sufficient to assume that the map is unital to say that it is stochastic. I don't know much about markov chains yet.. and what about positivity? I guess that is because we're talking about transitions probabilities so each entry must be between 0 and 1 and hence positive.. but I still tend to confuse the positivity of the map and the positivity of the matrix(does this mean that the entries are all greater than 0 in this setup?)
Comment: I can't thank you enough.^^ The cone of positive elements of $\mathbb{C}^N$ are the elements that can be written as $|\lambda|^2$ for some $\lambda \in \mathbb{C}^N$ right?


Will the site load slower when using a sub-theme of a sub-theme?

Question: In Drupal, you have a base-theme, and maybe a sub-theme. That sub-theme can also have another sub-theme.
Will Drupal be slower when using 3 themes, where each of them is a sub-theme of the previous one, or doesn't this affect the performance?
Answer: TL;DR Have as many sub-themes as you want, it's not a problem.
Longer answer All types of inheritance, theming or otherwise, will have a performance penalty, and really all logic that you perform will have that effect; However

With proper caching enabled, only the very first request that uses the sub-sub-theme, is actually going to notice a difference. After that you will have aggregated css/js files from all three (or more) involved themes, and all of this becomes a non-issue until you clear the cache, after which you will again need to aggregate the files once.
With a pretty big generalization, the performance cost is roughly going to be linearly proportional to the number of changes you make. So if you don't make a lot of changes, you won't see a big effect.

Generally speaking, I suggest you approach the problem the other way around. Organize your theme/solve your problem in a way that is efficient for you as a human. Then worry about how to make it efficient for a machine only when necessary.
Since your site isn't written in assembly, your entire site is a huge performance problem, but in the vast majority of cases, a cpu performing literally trillions of calculations in a second makes that a non-issue.


Encoding problems signing a xml document due to special characters

Question: Signing an xml document using c# I continuously have signature verification issues because of the special characters, in concrete this one 'º' commonly used for addresses in Spain.
The encoding for this xml file is "ISO-8859-1", however if I use UTF-8 it works fine.
The method I use for signing is this one:
<code>    public static string SignXml(XmlDocument Document, X509Certificate2 cert)
    {
        SignedXml signedXml = new SignedXml(Document);
        signedXml.SigningKey = cert.PrivateKey;

        // Create a reference to be signed.
        Reference reference = new Reference();
        reference.Uri = "";

        // Add an enveloped transformation to the reference.
        XmlDsigEnvelopedSignatureTransform env =
           new XmlDsigEnvelopedSignatureTransform(true);
        reference.AddTransform(env);

        XmlDsigC14NTransform c14t = new XmlDsigC14NTransform();
        reference.AddTransform(c14t);

        KeyInfo keyInfo = new KeyInfo();
        KeyInfoX509Data keyInfoData = new KeyInfoX509Data(cert);
        keyInfo.AddClause(keyInfoData);
        signedXml.KeyInfo = keyInfo;

        // Add the reference to the SignedXml object.
        signedXml.AddReference(reference);

        // Compute the signature.
        signedXml.ComputeSignature();

        // Get the XML representation of the signature and save
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        Document.DocumentElement.AppendChild(
            Document.ImportNode(xmlDigitalSignature, true));

        return Document.OuterXml;
    }
</code>
Taken from: http://www.wiktorzychla.com/2012/12/interoperable-xml-digital-signatures-c_20.html
And this is how I call it:
<code>    static void Main(string[] args)
    {
        string path = ".\\DATOS\\Ejemplo.xml";
        string signedDocString = null;
        XmlDocument entrada = new XmlDocument();
        entrada.Load(path);

        X509Certificate2 myCert = null;
        X509Store store = new X509Store(StoreLocation.CurrentUser);
        store.Open(OpenFlags.ReadOnly);
        var certificates = store.Certificates;
        foreach (var certificate in certificates)
        {
            if (certificate.Subject.Contains("XXXX"))
            {
                Console.WriteLine(certificate.Subject);
                myCert = certificate;
                break;
            }
        }

        if (myCert != null)
        {
            signedDocString = SignXml(entrada, myCert);
        }

        if (VerifyXml(signedDocString))
        {
            Console.WriteLine("VALIDO");
        }

        else
        {
            Console.WriteLine("NO VALIDO");
        }
        Console.ReadLine();
    }
</code>
The xml document must use the encoding ISO-8859-1, this is not optional. And I cannot suppress the special characters.
Any suggestion about how to handle this?
Comment: Does the XML document correctly *identify* its encoding as ISO-8859-1? Is it working *until* the verification, and it's just not verifying correctly? What is the `VerifyXml` method?
Comment: @MichaelKnight: that is kind of strong requirement to have your XML encoded in ISO-8859-1, when most known parsers just honor the encoding information provided in the preamble. But if thi is so, I see no other solution than just skipping any special characters.
Comment: Can you try instead of `entrada.Load(path);` do  `entrada.Load(XmlReader.Create(new StreamReader(path,Encoding.GetEncoding("Windows-1252"))));`
Comment: The header of the document is this . If I modify it to UTF-8 it works. VerifyXml is a method to verify the signature is right. The signature is made, but the verification returns "NOT VALID" when the encoding is ISO-8859-1.
Comment: @rene I tried your tip and even using ISO-8859-1 as encoding. No success in both cases.
Comment: You can configure the encoding when you write out the XML, but you can't use `.OuterXML` to do it.  Try http://stackoverflow.com/a/863501/298754 or http://stackoverflow.com/a/427737/298754
Comment: @Bobson I think my problem is different. The XML already exists and I try to sign it without success because of the reported issue. Actually, the document cannot be modified once the signature is done.
Answer: my fault.
In the verification method I was using utf8:
<code>public bool VerifyXml( string SignedXmlDocumentString )
{
    byte[] stringData = Encoding.UTF8.GetBytes( SignedXmlDocumentString );
    using ( MemoryStream ms = new MemoryStream( stringData ) )
        return VerifyXmlFromStream( ms );
}
</code>
In that step I was altering the encoding and so the document content wasn't the same as the original one. Quite newbie error.
The solution:
<code>        public static bool VerifyXml(XmlDocument SignedXmlDocument)
    {
        byte[] stringData = Encoding.Default.GetBytes(SignedXmlDocument.OuterXml);
        using (MemoryStream ms = new MemoryStream(stringData))
            return VerifyXmlFromStream(ms);
    }
</code>
Comment: I *thought* you had to be using `Encoding` wrong somewhere...  Although I didn't expect it to be like this.  Glad you found it!


If $ f*g$ is a polynomial of degree at most $m$ for all $g \in C_{0}^{\infty} $. Show $f$ is a polynomial of degree at most $m$ almost everywhere

Question: $C_{0}^{\infty}$ denotes the set of smooth functions with compact support.
In attempt of this, I've evaluated the convolution at the (m+1)th derivative to obtain
$$ \frac{d}{d^{m+1}}(f*g) =\int f(x-y)g^{(m+1)}(y)dy = 0 $$
But am lost in how to show that this implies f is a polynomial of degree at most m.
Comment: Hello reinin, and welcome to MathStackExchange. I have a few doubts on your notation: What do you mean with $C_0^{\infty}$? Also, shouldn't your derivative be $\frac{d}{d^{m+1}}$ instead of $\frac{d}{d^k}$?
Comment: ah yes sorry I'll change the derivative so it is correct. and by $C_{0}^{\infty}$ I mean the set of smooth functions with compact support.
Answer: In general $f$ is a distribution. If you assume $f$ is a $L^1_{loc}$ function it doesn't change the argument

If its distributional derivative $f^{(m+1)} $ is not the $0$ distribution then $f \ast g^{(m+1)}=f^{(m+1)} \ast g  \ne 0$ for some $g \in C^\infty_c$.
If $f^{(m)}$ is not constant then $f^{(m+1)}$ is not the zero distribution.
So the $m$-th derivative of $f-c_m x^m$ vanishes and by induction $f$ is a degree $\le m$ polynomial.

If you don't like distributions and their derivatives, pick some $\phi \in C^\infty_c, \int \phi = 1$ and replace $f$ by the smooth functions $f_n = f \ast n\phi(n.)$. You'll find that each $f_n$ is a degree $\le m$ polynomial which implies since $\lim_{n \to \infty} f_n$ converges (to $f$) in the sense of distribution that the same holds for the limit.
Comment: I am new to distributions and have a question concerning them. The general definition for a distribution f acting on a test function $\phi$ is $f[\phi] := \int f(x)\phi(x)$ and the derivative of $f$ as a distribution is given by $f'[\phi] \equiv -f[\phi'] $. But in my question, we are considering convolution, so in this case, does the derivative of $f$ as a distribution become the usual convolution derivative $f'(x)*\phi(x) = f(x)*\phi'(x)$?
Comment: Equivalently distributions are the (continuous) linear maps $g \in C_c^\infty \mapsto f \ast g \in C^\infty$ such that $(f \ast g)(x+a) = (f \ast g(.+a))(x)$. The (continuous+$C^\infty$) follows from being well-defined, and it is what implies $(f \ast g)^{(m)} = f \ast g^{(m)}$. Then $f^{(m)}$ is just defined as $f^{(m)} \ast g =f \ast g^{(m)}$, the point is to show everything is compatible with the usual objects when $f$ is a (continuous, smooth, integrable) function
Comment: Because the $f_n$ in my post $\to f$ the distributions extend the functions in the same way that $L^1$ extends $C^0$ and $\Bbb{R}$ extends $\Bbb{Q}$
Comment: Ah ok thank you. So there are different possibilities of $f$ as a distribution? e.g. $f[\phi] = \int f(x)\phi(x)$ is one possibility for $f$ as a distrubution and the convolution $f*\phi = \int f(x)\phi(x-y)$ is another possibility for $f$ as a distribution, each giving rise to their own distributional derivative?
Comment: No I'm saying $f[\phi(-.)] = f \circ \phi(0)$ so the two (pairing, convolution) are the same. The advantage of the convolution point of view is that continuity of $f$ is made clear : $f \ast \phi \in C^\infty$ for $\phi \in C^\infty_c$


distinguish if function argument optional

Question: How to distinguish if function argument optional?
How to distinguish
(p?: string): object

and
(p: string): object

I tried this
type A = {
  (p?: string): object
}
type B = A extends (p: string | undefined) => object ? string : number
type C = B

but it doesn't work
Is there some way to  distinguish them?
Thanks.
Answer: You can do this by using a conditional type to test if your function is assignable to another that has an optional first argument. So something like:
type A = {
  (p?: string): object
}

type B = {
    (p: string): object
}

type OptionalFirstArg = (a?: never) => unknown;

type IsOpt<F> = F extends OptionalFirstArg ? true : false;

type testA = IsOpt; // testA is true
type testB = IsOpt; // testB is false

Here's a playground link for the above code.
Comment: @MaTianqi This approach requires the `strictNullChecks` compiler option to be on.
Comment: It's a great way to solve this problem. But when I do some thing like this with VS Code. Both value will be the `true`. The version I used is 3.6.2.
Answer: You can make distinction by checking against () => object when parameter is not present.
type A1 = {
  (p?: string): object; // optional input parameter
}
type A2 = {
  (p: string): object; // required input parameter
}
type B<T extends (p: string) => object> =
  T extends () => object ?
    number
    : T extends (p: string) => object
    ? string
    : never;

type C1 = B<A1>; // number
type C2 = B<A2>; // string