Global Lyapunov function to examine global stability?

Question: Consider
\begin{align}
\frac{dS}{dt} &= \mu N -\frac{\beta S I}{N} +\gamma I - \nu S\\[2ex]
\frac{dI}{dt} &= \frac{\beta S I}{N} -\gamma I -\nu I
\end{align}
where $N=S+I$ is the total population.
If $\mu=\nu$, the above reduces to
\begin{align}
\frac{dS}{dt} &= \nu -\beta S I +\gamma I- \nu S\\[2ex]
\frac{dI}{dt} &= \beta S I -\nu I -\gamma I
\end{align}
with equilibrium points:
\begin{align*}
e_1 : \left( S_1^*, I_1^*\right)&= \left(1, 0\right), \\[2ex]
e_2 : \left( S_2^*, I_2^*\right)&= \left(\frac{\gamma+\nu}{\beta}, \frac{\gamma+\nu}{\beta}\left(\frac{\beta}{\gamma+\nu} -1\right)\right)
\end{align*}
I have analysed the global stability of $e_1$ however I haven't managed to find a global Lyapunov function to check stability for $e_2$. I know the Lyapunov function should composites of the Volterra function, any ideas?
EDIT
Consider:
\begin{align}
\frac{dS}{dt} &= \mu N -\frac{\beta S I}{N} - \nu S\\[2ex]
\frac{dI}{dt} &= \frac{\beta S I}{N} -\nu I
\end{align}
Where $N=S+I$ is the total population.
Which reduces to
\begin{align}
\frac{dS}{dt} &= \nu -\beta S I - \nu S\\[2ex]
\frac{dI}{dt} &= \beta S I -\nu I
\end{align}
The equilibrium points now read
\begin{align*}
e_1 : \left( S_1^*, I_1^*\right)&= \left(1, 0\right), \\[2ex]
e_2 : \left( S_2^*, I_2^*\right)&= \left(\frac{\nu }{\beta}, \frac{\nu}{\beta}\left(\frac{\beta}{\nu}-1 \right)\right)= \left(\frac{1}{\mathcal{R}_0}, \frac{1}{\mathcal{R}_0}\left(\mathcal{R}_0-1\right)\right).
\end{align*}
The biological feasible region for this system is the simplex in the first quadrant, the set being $\Omega = \left\lbrace \left(S,I\right)\in \mathbb{R}_+^2 : S\geq 0, I \geq 0, S+I \leq 1  \right\rbrace$. This set is a positively invariant set for our system.
Theorem:
If $\mathcal{R}_0 > 1$, then the endemic equilibrium $e_2$ is globally asymptotically stable in the interior of $\Omega$.
Proof:
Consider the Lyapunov function
\begin{equation}
V(S,I) = \left(S-S_2^*\right)+ \left( I-I_2^*\right) -S_2^* \ln \frac{S}{S_2^*} - I_2^* \ln \frac{I}{I_2^*}.
\end{equation}
This function is positive definite since $V\left(S,I\right) \geq 0$ and $V\left(S,I\right)=0$ at the equilibrium point $e_2$. The derivative of $V$ along solutions of (2.3) and (2.4) we have
\begin{align*}
\dot V &= \dot S +\dot I - \frac{S_2^*}{S}\dot S-\frac{I_2^*}{I}\dot I\\
&= \nu(1-S) -\beta S I + \beta S I -\nu I -\frac{\nu}{\beta S}\left( \nu -\nu S -\beta S I \right) - I_2^*\left(\beta S - \nu\right)\\
&= \nu(1-S) -\frac{\nu}{\beta S}\left( \nu -\nu S \right) - I_2^*\left(\beta S - \nu\right)\\
&= \nu(1-S) -\frac{\nu}{\beta S}\left( \nu -\nu S \right) - \left(1-S_2^*\right)\left(\beta S - \beta S_2^*\right)\\
&= \nu(1-S)\left[1-\frac{\nu}{\beta S}\right] - \left(1-S_2^*\right)\left(\beta S - \beta S_2^*\right)\\[1ex]
&= \nu(1-S)\left[\frac{\beta S -\beta S_2^*}{\beta S}\right] - \left(1-S_2^*\right)\left(\beta S - \beta S_2^*\right)\\[1ex]
&= \nu\beta\left(S-S_2^*\right)\left[\frac{1-S}{\beta S} -\frac{1-S_2^*}{\beta S_2^*} \right]\\[1ex]
&= -\nu\beta\left(S_2^*-S\right)\left[\frac{\beta S_2^*\left(1-S\right) - \beta S\left(1-S_2^*\right)}{\beta S\left(\beta S_2^*\right)}\right]\\[1ex]
&=  -\beta\left(S_2^*-S\right)\left[\frac{\beta S_2^* -\beta S}{\beta S}\right]\\[1ex]
&= -\beta\left(S_2^*-S\right)^2\left[\frac{1}{S}\right]\\[1ex]
& \leq 0
\end{align*}
We notice $\dot V$ is always negative with the exception of the special case where $S$ and $I$ take on the the endemic equilibrium values, thus we can say $\dot V$ is semi positive definite. We see, when $S\rightarrow 0$ or $S \rightarrow \infty$, $\dot V \rightarrow \infty$. Similarly, when $I\rightarrow 0$ or $I \rightarrow \infty$, $\dot V \rightarrow \infty$. We can now conclude that $V$ is a Lyapunov function for our system and according to Lyapunov stability theorems, the endemic equilibrium $e_2$ is globally asymptotically stable in $\Omega$.
Comment: Shouldn't it be impossible to have a global Lyapunov function, since there are multiple equilibria? Or are you ok with a negative semi-definite derivative of the Lyapunov function?
Comment: @Math I don't think your reduction in the case $\mu=\nu$ is right. For example, $N$ is no longer nessecairly preserved by it, despite being constant in the original equation.
Comment: @KwinvanderVeen I am okay with negative semi-definite  then I can apply LaSalle's invariance principle to prove GAS on endemic equilibrium.
Comment: @pax if we take $S=S/N$ and $I=I/N$(I know this isn't good notation...) this reduces to the above and since $\mu = \nu$ surely we can substitute?
Comment: @KwinvanderVeen Actually we don't need to apply LaSalle's Invariance principle here since this system is simple, but we will in more complicated models later.
Comment: @KwinvanderVeen do you know a Lyapunov function for this question that I have placed a bounty: https://math.stackexchange.com/questions/4221373/selecting-a-suitable-lyapunov-function-for-the-following-systems-to-analyse-glob
Answer: This is just in reference to the $\mu=\nu$ case. In this case one can check that $\dot{N}=0$ so we may consider it as a fixed variable. We now compute that
$$\dot{I}=\frac{\beta}{N}(N-I)I-(\gamma+\nu)I=-\frac{\beta}{N}I^2+bI,$$
where we notate $b=\beta-\gamma-\nu$. We assume that $b\neq 0$, though this case can be dealt with similarly. This admits two stable points, $I=0$ and $I=bN/\beta$. This equation is solved by $I=0$ and $$I(t)=\frac{b\exp(bt)}{c+N^{-1}\beta\exp(bt)},$$
The behavior around $c\sim 0$ corrosponds to $I=bN/\beta$, and the behavior around $c^{-1}\sim 0$ corrosponds to $I=0$.
For $b<0$, the point $I=0$ is stable, and $I=bN/\beta$ is unstable. When $b>0$ the point $I=0$ is unstable, and $I=bN/\beta$ is stable. In both cases, the Lyponauv exponent away from the unstable point is $|b|$.
Comment: Maybe I'll edit another model I did before to see what I need, please have a look in due time!
Comment: I did find the solution you posted however I am looking for proving the global stability of the endemic equilibrium when $\mathcal{R}_0>1$. If you have a look at the edited question, you'll see what I mean :)
Comment: why isn't my reduction right in the original post? we have $\mu = \nu$ so this implies $\dot S = \nu N - \frac{\beta S I}{N} -\nu  S$. and taking the fractions $S/N$ and $I/N$ as $S$ and $I$, we have have $\dot S = \nu -\beta S I -\nu S$.
Comment: And is your solution analysing local stability or global stability?


using sum and group by and ifnull

Question: I have a table of money owed, along with a team identifier (could be 1,2,3 for example)
I have another table which gives a name to these team identifiers (so 1 could refer to Team1, 2 could refer to John's jokers etc)
The first table can have multiple entries for money owed and I need to get the total owed per team identifier, and use the team name if it exists.
So I left join the tables and use a sum clause and get a total amount owed per teamname, or null if the teamname is not present. If it is null then I want to use the team identifier, so the results would look like
name            total
.....................
team1            100
John's jokers   1000
99                50

where 99 is a team identifier because there was no teamname and there was a null present.
I tried using ifnull(columnName, teamID) but this failed when using a sum clause.
Could anyone help with this problem please
Answer: I think ifnull() is used like this:
select ifnull(teams.team_name, teams.team_id) from teams;

So in this case it tries to retrieve the name of the team, and if that comes back null it instead uses the team's identifier.  In this case your query would look like this:
select ifnull(teams.team_name, owing.team_id), sum(amount_owed)
  from owing left join teams on owing.team_id = teams.id
 group by owing.team_id

Make sure the group by asks for the ID field from owing, not teams, otherwise you'll be grouping on a null field.
Does this resolve the issue?
Comment: Awesome!! That has fixed it a treat! I think I was grouping on the teams id. Many thanks for your help.

using sum and group by and ifnull


What is the short key to delete the whole row in Excel 2007 without using mouse?

Question: I am trying to find the short key for deleting the entire row in Excel 2007 without taking help of mouse.
Comment: Did you do any research before posting this question? What were the results.
Comment: Shift + Spacebar then Ctrl + -
Comment: Ok. If you do not want your question further downgraded. Describe your problem in more detail e.g. why the default Excel shortcut does not suit you, what is the desired solution and what effort have you made to reach that solution so far
Comment: yes, i have searched on internet but could not find a perfect solution.
Answer: You can use Ctrl + -
<code>Ctrl+-  == Deletes Rows, Columns, or Cells Depends on selection
</code>
You should first select the entire row.
For this you can use Home then  Ctrl + Shift + Right Arrorw.
OR
You can just click on the row number to select entire row.
After selecting the entire row, If you press Ctrl + - then entire row will be deleted.


Structure of the units of the valuation ring of a finite extension of $\mathbb{Q}_p$

Question: Let $K$ be a finite extension of the field of $p$-adic numbers $\mathbb{Q}_p$, call $\mathcal{O}_K$ the valuation ring of $K$ (i.e. the set of elements of $K$ with valuation greater or equal than zero). Call $\mathcal{O}_K^\times$ the multiplicative group of units of $\mathcal{O}_K$ (i.e. the group of elements of $K$ with zero valuation).
I have read that there is a group isomorphism
\begin{equation*}
\mathcal{O}_K^\times\cong \mathbb{Z}_p^{a}\times U
\end{equation*}
for some $a\in\mathbb{N}$ and $U$ finite group. Could you tell me why, or where I can find a proof of this result?
I know that $\mathcal{O}_K\cong \mathbb{Z}_p^{[K:\mathbb{Q}_p]}$ as $\mathbb{Z}_p$-modules, but this isomorphism only involves the additive structure of $\mathcal{O}_K$.
Answer: This should be in any algebraic number theory textbook that mentions the $p$-adics e.g. Neukirch. Here is a rough sketch; the technical details on the $p$-adic logarithm are in Neukirch and other places.
Let $\pi$ be a uniformizer. One knows that the higher unit groups, $U^{(n)} = 1 + (\pi)^n$, are of finite index in $\mathcal O_K^\times$ and that the logarithm gives a homomorphism from $U^{(n)}$ under multiplication to $(\pi)^n$ under addition as $\mathbb Z_p$-modules. For sufficiently large $n$, this is an isomorphism. Since $(\pi)^n$ is isomorphic to $\mathcal O_K$ (under addition), we can see that it is a free $\mathbb Z_p$-module of rank equal to the degree of $K$ over $\mathbb Q_p$. Therefore, $\mathcal O_K^\times$ is a $\mathbb Z_p$-module of rank $[K:\mathbb Q_p]$ (using the finite index fact). So we can decompose it into a free part of that rank times some torsion; the torsion of $\mathcal O_K^\times$ is clearly given by the roots of unity.
Putting it all together, we obtain a slightly more precise version of your claim:
$$\mathcal O_K^\times \cong \mathbb Z_p^{[K:\mathbb Q_p]} \times \{\textrm{roots of unity in $K$}\}$$


Script to Uninstall MS Updates by Date

Question: I'm in a situation where I need to uninstall all windows updates before a certain date to troubleshoot a strange bug.  I found several vb/ps scripts to do this
remove single update
However I'm trying to get at something along the lines of where date > 1/9/13 get rid of it !
The reason I ask is I feel like this is something I end up running into from time to time and ends up being pretty time consuming.  Any ideas ?
I also found the following
<code>wmic qfe get hotfixid,installedon | findstr %01/09/13% >> c:\list.txt
</code>
However this doesn't seem to return an accurate result set
I'm currently working with a windows server 2003 box. Thanks in advance.
Comment: Which version PowerShell can you use? Check `$PSVersionTable`
Comment: @jscott I have PS 2.0 on there now but I'm pretty sure you can run 3.0 on 2003/XP no ?
Answer: Here's one way to filter hotfixes by date using VBScript. You could easily convert it to PowerShell if needed or just call your PowerShell code to remove each hotfix that matches the filter.

On Error Resume Next
Dim strComputer
Dim objWMIService
Dim propValue
Dim objItem
Dim SWBemlocator
Dim UserName
Dim Password
Dim colItems

Dim dateFilter

dateFilter = CDate("1/9/2013")

strComputer = "."
UserName = ""
Password = ""
Set SWBemlocator = CreateObject("WbemScripting.SWbemLocator")
Set objWMIService = SWBemlocator.ConnectServer(strComputer,"root\CIMV2",UserName,Password)
Set colItems = objWMIService.ExecQuery("Select * from Win32_QuickFixEngineering",,48)
For Each objItem in colItems
    hotFixID = objItem.HotFixID
    installDate = objItem.InstallDate

    If IsNull(installDate) Or Trim(installDate) = "" Then
        installDate = objItem.InstalledOn
    End If

    If IsDate(installDate) Then
        If CDate(installDate) > dateFilter Then
            WScript.Echo hotFixID & vbTab & installDate

            ' Call your remove hotfix script or code and pass it the hotFixID and optionally, the machine name
        End If
    End If
Next

Script to Uninstall MS Updates by Date


I'm try to wrote in assembly

Question: I try to write through the cell values coup addresses 100h to 110h to negative values. (If the value is negative - it remains negative). Do not use the Compare CMP. so i try to check the MSB sign with text command and it isn't working I wrote this
code segment
assume ds:code,cs:code
start: mov ax,code
mov cx,10
mov si,100h
check:
mov al,[si]
test al,10000000h//here i have problem!
je isntnegative
inc si
dec cx
cmp cx,0
jz finish
jmp check
isntnegative:
neg al
inc si
dec cx
cmp cx,0
jz finish
jmp check
finish:
int 21h
nop
code ends
end start

I know it's long and effective but it's the best I can do at the moment.
Comment: It's very unclear what are you trying to do, what platform are you writing for, and what result are you expecting. Please edit, and provide some context.
Comment: like i say,i try to convert positive number to negative number
Comment: Why are you expecting to find anything sensible at address 100h? What platform are you targeting? On Windows or Linux, your program will most likely crash. On DOS, it'll process nonsense data.
Answer: AL is an 8-bit register; you appear to be expecting it to be 32 bits.  If you're working with 32-bit data, use the EAX register instead.  If you're working with 16-bit data, use AX.  And if you happen to be working with 64-bit data, use RAX.
And if you really are working with 8-bit values, then test against 10h, not 10000000h.
And assuming you're NOT working with 8-bit values, when you inc si, you probably need to increment it by 4 (for 32-bit values) or 2 (for 16-bit values).
Answer: I imagine int 21h indicates DOS. You need a subfunction number in ah to do any good. The last time you touched ah was the high byte of code! The assume directive does not make it so. You go as far as mov ax, code, you might as well mov ds, ax so what you told assume will actually be true.
You need to test al, 80h to see if it's negative. (You could also or al, al   or and al, al or test al, al to set the flags, and js isnegative... I guess you'd want to jns isntnegative)
If al isn't negative, you negate it. Do you then want to put the negated value back in your array? You don't do it. If you do, then it becomes important where your array at 100h is! If you'd left ds where DOS leaves it in an .exe file, it would point to the PSP (Program Segment Prefix) and offset 100h would probably be where your code starts. You probably don't want to scribble on it! By setting ds to code, offset 100h will probably be past the code for this simple program. It might grow, though! You might want to put your array someplace safer. You might want to initialize it with known values. You might want to display it before and after to "prove it worked". Good start!

I'm try to wrote in assembly


Discrete Proportion data -GLMM, regresion beta or multinominal logistic distribution

Question: I have an experiment that have nine treatments consisting of three strains with three different levels of application. Each treatment involves 20 plants, and measurements were taken at three-time points over 10-day intervals, resulting in repeated measures data.
My dataset includes the proportion of endophytism in leaves, calculated by counting the pieces of leaves where the inoculated fungus was found relative to the total pieces of leaves in the Petri dish. The proportion values range from 0 to 1, excluding both endpoints.
I'm considering one modeling approach using the glmmTMB function in R, but I'm uncertain about the appropriate family to use and whether to include leaf size as a random effect in the Model 1. Here is my proposed model:
M1 <- glmmTMB(Endophytism ~ Treatment * Strain * Days + (1+Days|Plant),
              family=??, data = Datos_OBJT2)

For me is important interactions between treatment, strain, and days. And "days" now is treated as a factor.
See in comments a possible solution using a simple binomial regression.
 m3 <- glmer(cbind(Total_Infected, Total_No_Infected) ~ Treatment * Strain * Days + (1|Plant),                        family = binomial, data = Datos_OBJT2)
I would appreciate any help or recommendations on which analysis approach would be the best for my data.
Comment: Welcome to Cross Validated! Is there some reason why you can't use a simple binomial (e.g., logistic) regression? That should work OK if you have counts for the numbers of infected and non-infected leaf pieces (a 2- column outcome of yes/no counts per Petri dish). But perhaps I'm missing something here in the details of your experiments.
Comment: I've modified the question and I include the potential solutions. Thank you for your assistance!!
Comment: I´m using a binomial regression:

`m3 <- glmer(cbind(Total_Infected, Total_No_Infected) ~ Treatment * Strain * Days + (1|Plant),
                      family = binomial, data = Datos_OBJT2)`

I'm trying to simulate a repeated measures model, but as I understand, a binomial logistic model requires independence of the data. I'm looking for an alternative or to know if what I'm doing is correct when I add a random effect to the model because my data is repeated measures in time.
Comment: Is the first measurement for each plant before or after `Treatment` is applied? How is the `Days` variable coded (factor or numeric)? How many observations are there?
Comment: All measurements are after applying the treatment.
Time is coded as a numeric variable.
In total there are 3 measurements every 10 days, for each treatment.
Each treatment has 20 plants in total.
Comment: To make things easier for new visitors to this page, please edit your question to include the important extra information that you have provided in your comments. Comments are easy to overlook and can be deleted.
Answer: With a simple yes/no for infection status of each leaf piece, this should be handled OK by a binomial (e.g., logistic) regression, with the two-column outcome variable that you show in a comment. Incorporating Plant as a random  effect will take the lack of independence of results within individual plants into account.
Treating Days as numeric might get you into trouble. Numeric coding means that you are assuming a linear association between Days and the outcome (log-odds of a leaf piece being infected if you use logistic regression). That's probably unrealistic. With only 3 values possible for Days it's simplest to treat it as a 3-level categorical predictor, allowing each day to have its own association with outcome.
Whether and how to adjust for Leaf_size depends on your experimental setup and your understanding of the subject matter. If I understand the experimental setup correctly, it seems that a smaller leaf will tend to have fewer pieces placed into the Petri dish; that provides one type of correction (higher variance in proportion estimates with fewer leaf pieces).
If you think that the probability of a leaf piece being infected depends on Leaf_size, other things being equal, then you should use it as a predictor. As Leaf_size is a continuous predictor, you should consider flexible fitting (e.g., a regression spline) so that you don't implicitly make an assumption of a linear association with outcome.
Finally, your original question used only additive terms for the predictors, but the model in a comment includes interactions among all fixed-effect predictors. I suspect that the interactions will be important, but that would depend on your understanding of the subject matter.


How Parzen window density estimate $f_n$ converges to f

Question: I am trying to understand how Parzen window density estimate converges to actual density function f(x).[Actually i am trying to learn machine learning on my own using available free resources. Please help me in the below]
Let $f_n(x)$ be the Parzen window density estimate of actual density f(x). Given $x_1,x_2....x_n $ are iid sample (given training data).
Let h be parameter. $V_n$ be volume (say hypercube). Now in Parzen, we take estimate for density function to be linear sum of kernel functions at sample points. To show that estimate converges to actual f(x), i did in following way(for each sample size n, $V_n, h_n$ , varies and also as $n \to \infty, h_n \to 0, V_n \to 0, $ but $n V_n \to 0$)
$E(\hat f_n(x)) = \frac {1}{n} \sum_{i=1}^n E(\frac{1}{V_n} \phi(\frac{x-x_i}{h_n})) \\ = E(\frac{1}{V_n} \phi(\frac{x-x_i}{h_n})) \\= \int \frac{1}{V_n} \phi(\frac{x-x_i}{h_n}) f(z) dz$
(as each term expectation is same and $\phi $ be some kernel function, f be density )

Above Last integral be (1)

After that how to proceed? I am following https://www.youtube.com/watch?v=esoVuEG-X1I&list=PLbMVogVj5nJSlpmy0ni_5-RgbseafOViy&index=13&t=2617s (At 26.01 )
Here sir says this integral (1) goes to f(x) as $n \to \infty$ but i did not understand how.
I know
$\int \frac{1}{V_n}\phi(\frac{x-x_i}{h_n}) dz = 1$ (since $\phi$ is kernel function)
Also, i tried to expand on final integral(1) using integration by parts
then $f(z)\int \frac{1}{V_n}\phi(\frac{x-x_i}{h_n}) dz - \int f'(z) \int \frac{1}{V_n}\phi(\frac{x-x_i}{h_n}) dz dz = f(z) - f(z)=0$ (as integral of kernel function sums to 1)
Please explain where i did it wrongly or understood wrongly.
Answer: First, they define the following function: $$\delta_n(x)=\frac{1}{V_n}\phi\left({x\over h_n}\right)$$
and this is assumed (check 22m39s) to converge to delta function as $n\rightarrow\infty$. So, basically any kernel that doesn't satisfy this convergence property, even if it converges to the true density, we can't prove it this way. That said,
$$E[\hat f_n (x)]=\int_{-\infty}^\infty \delta_n(x-z)f(z)dz\rightarrow \int_{-\infty}^\infty \delta(x-z)f(z)dz=\int_{x^-}^{x^+}\delta(x-z)f(z)dz=f(x)$$
The last two follows from the properties of delta function.
Comment: thank you sir. I was puzzled at last but 1 step. I understood after going thru shifting property of delta function(missed that approximation of f in that epsilon neighbourhood of z).
Comment: Sir any idea why i am getting 0 if i integrate by parts in the last part of my post(should not become zero rigt?)
Comment: Your expansion seems quite complicated, because you don't use limits, and confuse $x_i$ and $z$'s. I feel that first integral will be $0$.


Intel S5520UR and Raid activation key

Question: If I add Raid Activation Key:
AXXRAKSAS2

and  Memory:
AXXMINIDIMM512

To the S5520UR Intel motherboard, it enables:

"enables full intelligent SAS HW RAID for the Intel Servers with a
  LSI1078-based active midplane."

Does this mean I'll get some performance advantage, or that it just unlocks the new RAID 5,50,60 ..etc.
NOTE: It uses SATA HDDs, not SAS.
Answer: AXXRAKSAS2 Install Guide
According to the guide:

This guide is specific to the Intel
  ®
  RAID Activation Key with the order code, AXXRAKSAS2.
  This key enables hardware RAID across all mod
  es (0, 1, 5, 6, 10, 50, and 60) on these Intel
  ®
  server
  boards and systems that include an Intel
  ®
  Integrated Server RAID Module using the LSI* 1078
  ROC controller:

So, like most, it is designed as a "license key" to unlock the additional RAID levels.  The performance is still limited to the actual LSI card's abilities.

Intel S5520UR and Raid activation key


Vimeo Video Browser While Creating New Page In Drupal

Question: I'm new to Drupal, learning it from past few days.
I want to create a vimeo video browser field widget while creating a page content type. Is there any module available which could help me achieve this?
I have installed various modules like vimeo media module, media embed field which enables me to add the vimeo video URL while creating the new page, I want to make an addition to this functionality like a vimeo video browser window to be opened and I could select the video from the same. Any idea as in how I could accomplish the same?
Comment: Welcome to SO :-), we don't have a code writing service here - please write your own code after doing the appropriate research. If you have issues with that code, that's the right time to ask a question here. Question in current from is too broad to answer. Thanks.
Comment: Thanks you for your Reply! As I said I'm new to Drupal I was just inquiring bout any available modules for the same? or any idea to implement...Thanks
Answer: I can advice you this module
https://drupal.org/project/media
https://drupal.org/project/media_vimeo
I wish it helps you.


Solve two multiplication equations with one multiplication operator

Question: QUESTION
I've been wondering if it's possible to solve two multiplication equations at the same time by only being able to multiply once? It's a very odd question but it's for an algorithm that I'm working on to improve it's time complexity.
THE PROBLEM
2 * 4 = 8
3 * 5 = 15
For example I am multiplying two times to get two separate answers 8 and 15 but what I'm trying to do is multiply ONCE and get the answer for both 2 * 4 and 3 * 5. Though I want the method to work with any number that I'm trying to solve. So long as the solution doesn't require Σ (no extra looping on the equation). What I ideally want is that you can only multiply ONCE and you can add/subtract/divide/mod/etc... beforehand or afterwards.
WHAT I'VE TRIED
I've tried many things that haven't worked. One was reliable method I did was getting the median by manipulating the 4 numbers that I'm going to multiply. Though the median value has the be in between the two solution so I can subtract and add from the median so I can the the answer to both equations. Besides that I've tried other small things that didn't go anywhere because it gave me mixed results with other values.
Hopefully this gives enough context. I'd appreciate the help very much! Thank You!
Comment: Does is help that $2{,}003\cdot 4{,}005=8{,}022{,}015$?
Comment: Wow it does! Though does this work for any number? Even if it's a 3..4..5 digit number?
Answer: Expanding on Hagen von Eitzen's hint: $(ax+c)(bx+d)=abx^2+(ad+bc)x+cd$, so if you take $x$ larger than $ad+bc$ (e.g. by ensuring that $x$ has more than twice as many digits as any of the inputs), then $ab$ and $cd$ are the first and last digits of the base-$x$ representation of $(ax+c)(bx+d)$. You could implement this with bit shifting, taking $x$ to be a sufficiently large power of $2$.
This approach won't improve the asymptotic time complexity of a conventional algorithm, though, because multiplying arbitrarily large integers takes $\Omega(n)$ time in the output length and we're throwing away the inner digits of the result. It's also unlikely to be a worthwhile optimization in practice. If all you want is two multiplications, just do them separately.
Comment: Thank you for the additional context! I also appreciate the source!


Split the String with comma and Star

Question: Hi i am developing the android application now getting the String like under. I want to split my string with comma and with the Star is well.
The String Is : kushal,naren,dhrumil,email@example.com,*Bcc:email@example.com
And What I want is :

kushal,naren,dhrumil in String str1
email@example.com in str2
email@example.com in str3
Answer:     String str = "aaa,bbb*ccc";
    System.out.println(Arrays.toString(str.split("[,*]")));

Comment: i have to display the s;it string in different text view. So how can i do so.
Comment: I am sorry, @Kushal Shah, I did not understand what do you exactly want. If your problem is still relevant could you plz ask separate question?
Comment: Actually i want aaa in some other string bbb in other String and ccc in other String.

Split the String with comma and Star


JavaScript Object Literals: Property names as strings vs. "raw"

Question: Can there ever be a difference between:
var x = {
  hello: 'world'
};

and
var x = {
  'hello': 'world'
};

?
That is, under what conditions does giving a property name as a string have different results than giving it as a "raw" name? For example, I know that var x = {}; x['@£$%'] = 'bling!'; is valid (since any string can be a property), but x.@£$% = 'bling!' won't work. Neither will language keywords or reserved keywords as property names (so var x = {for: 'good', class: 'y'}; won't work.
Anything else?
For example, what if
var hello = 'goodbye';

is defined in the above example? Or something else, like
function hello() {
  return 'goodbye';
}

?
Should I always make my property names strings, just to be safe?
Comment: Have a look at [this question](http://stackoverflow.com/questions/2348867/why-are-some-object-literal-properties-quoted-and-others-not)
Answer: I almost never specify anything beyond a-zA-Z as my key so I don't really worry about characters such as @. If for whatever reason you really need these characters, then sure go ahead and use quotes.
If you are sure the key word is a reserved word or even remotely think it may be, just wrap it in quotes and be safe .. otherwise just go quoteless and save typing time.
A variable with the same name as your key has absolutely no bearing because it's taken literally.
var hello = 'god';
({hello:2})['hello'] // 2

Answer: In an object literal, you can use either a string literal (quoted) or an identifier (unquoted). In the first case, you can therefore use whatever characters you like, while in the second, you have to follow the rules for identifiers laid out in the ECMAScript spec. The same identifier rules apply when using the dot notation property accessor. Simplified summary:

The identifier must start with a letter, _ or $ (both of which may also appear anywhere in the identifier)
After the first character, more characters are allowed, including numbers
The identifier must not be a reserved word (new, var, function, delete, etc)


How can I close all notifications of a page before unload it (without use Window#onunload)?

Question: I have a page that notifies the user about server updates, using window.webkitNotifications.
It's not a Google Chrome extension.
I want to close all page notifications before the page unload.
I'm trying to do it with:
var notifications = new Array();

// ...
var popup = window.webkitNotifications.createNotification(...);
// ...
notifications.push(popup);

// ...
function closeAll(){
  for (notification in notifications) {
    notifications[notification].cancel();
  }
}

//...
$(window).unload(function() {
  closeAll();
});

But the notifications are not closed when I reloads the page.
I found this issue on Chromium project: https://code.google.com/p/chromium/issues/detail?id=40262
How can I ensure that page notifications are closed without use the Window#onunload ?
Comment: i just ran into this issue today, it doesn't seem like that bug ever got fixed either, sucks. If the user refreshes the page the notification is just left there handing. Did you ever find a workaround?
Answer: I wonder if you can add some javascript to the notification popup and settimeout withing the actual popup, that way it will close eventually.
I will have to try and test this out.
Answer: Use this :)
$(window).on('beforeunload', function() {
    closeAll();
});

Answer: Use the beforeunload event instead of unload.


ASP.NET MVC - How do I implement Paging?

Question: I'm relatively new to MVC and looking to output some data and paginate through it. I don't want some fancy JQuery pagination or anything like that, it has to run server side. I have done this sort of thing previously using Gridviews etc, but not sure how to achieve this using ASP.NET MVC. Does anyone have any ideas how to do this?
I am using the following:
Razor,
C#
Entity Framework,
LINQ
Comment: possible duplicate of [Is there a paging solution for ASP.NET MVC that does paging in the database?](http://stackoverflow.com/questions/1105336/is-there-a-paging-solution-for-asp-net-mvc-that-does-paging-in-the-database)
Comment: possible duplicate of [Paging & Sorting grids with ASP.Net MVC](http://stackoverflow.com/questions/496470/paging-sorting-grids-with-asp-net-mvc)
Answer: This is a famous tutorial http://nerddinnerbook.s3.amazonaws.com/Part8.htm
Answer: I think you'll find that this should help you http://msdn.microsoft.com/en-us/magazine/gg650669.aspx


Need help transferring a jpg from web server to S3 - PHP and CodeIgniter

Question: I have a Flash application that captures an image and passes an encoded image to my web server. The web server then decodes the image and saves it to a tmp directory. That part works fine. Next I want to move this image from the web sever to my S3 account but am having trouble. I am using the code below. Any help is appreciated.
In the CodeIgniter Controller Constructor:
    $this->load->library('S3');

In the function (also within the controller for now)
    /************** S3 upload example***************/
    if (!defined('awsAccessKey')) define('awsAccessKey', 'xxxxxxx');
    if (!defined('awsSecretKey')) define('awsSecretKey', 'xxxxxxx');

    $s3 = new S3(awsAccessKey, awsSecretKey);

    if($s3->putObjectFile($filePathTemp, "bucket", $filePathNew, "ACL_PUBLIC_READ_WRITE")){
            @unlink($filePathTemp);
    }

I can't even get the $s3 variable to return anything in an "echo" statement by returning a value on the first line of the S3 constructor. I can't access the S3 object/class, but the following statement returns a "1":
    echo "S3 --> " . class_exists('S3');

Thanks in advance for your time.
-Tim
Answer: I'm assuming (you don't say: you should specify which one) you are using this. Your usage looks correct: I'm assuming your keys are wrong. If
print_r($s3->listBuckets());
doesn't return anything check your server logs.
Comment: Yes I am using the class from undesigned.org. Unfortunately print buckets did not work either. I will check the logs as well. Thanks!


How to pass image batches as locals to profile.runctx?

Question: I want to send a batch of images to profile.runctx  Ex
profile.runctx('print (inference(image_batch,batch_size)); print()',
               globals(),
               {'image_batch':'how to send image batch?','batch_size':128})

I have a function called inference which accepts a sequence image batches as input. How to pass a sequence of images as parameter in profile.runctx?
Answer: You've left many details out the example code in your question, but here's a guess:
import profile

def inference(image_batches, size):
    for i in range(size):
        print('image_batches[{}]: {}'.format(i, image_batches[i]))
    return 42

image_batch = ['image1', 'image2']
batch_size  = 2

profile.runctx('print(inference(image_batch, batch_size)); print()',
               globals(), locals())

Alternatively you could do something more explicit like this:
profile.runctx('print(inference(image_batch, batch_size)); print()',
               globals(), {'image_batch': ['image1', 'image2'],
                           'batch_size': 2})


automate dpkg-reconfigure tzdata

Question: I'm using puppet to admin a cluster of debian servers.  I need to change the timezone of each machine on the cluster.  The proper debian way to do this is to use dpkg-reconfigure tzdata. But I can only seem to change it if I use the dialog.  Is there some way to automate this from the shell so I can just write an Exec to make this easy?
If not, I think the next best way would probably be to have puppet distribute /etc/timezone and /etc/localtime with the correct data across the cluster.
Any input appreciated!
Comment: Note that the currently accepted answer has been wrong [since 2017](https://bugs.launchpad.net/ubuntu/+source/tzdata/+bug/1554806/comments/9). The correct answer is [this one](https://serverfault.com/questions/84521/automate-dpkg-reconfigure-tzdata/846989#846989).
Answer: You need to specify the frontend as `noninteractive' and it will save your current settings.
dpkg-reconfigure will take the current system settings as gospel, so simply change your timezone the way you would normally and run it with the non-interactive flag
e.g. for me to change to "Europe/Dublin" where I am:
# echo "Europe/Dublin" > /etc/timezone
# dpkg-reconfigure -f noninteractive tzdata

Obviously this allows you to use puppet/cfengine as you like to distribute /etc/timezone also.
EDIT:
after @gertvdijk comment pointing to https://bugs.launchpad.net/ubuntu/+source/tzdata/+bug/1554806 and @scruss answer you will probably have to do it like this in most modern distributions:
$ sudo ln -fs /usr/share/zoneinfo/Europe/Dublin /etc/localtime
$ sudo dpkg-reconfigure -f noninteractive tzdata

Comment: Heads up! Newer Ubuntu/Debian versions don't work this way anymore. Behaviour changed. https://bugs.launchpad.net/ubuntu/+source/tzdata/+bug/1554806
Comment: as an alternative to changing permissions, you could do something like this.

`echo 'Europe/Dublin' | sudo tee /etc/timezone > /dev/null`
Comment: For completeness, another way to echo via sudo is `sudo bash -c 'echo "Europe/Dublin" > /etc/timezone'`
Answer: Since the accepted answer no longer works (Debian Jessie, April 2017), an approach modified from @gertvdijk's comment link appears to do the job now:
sudo ln -fs /usr/share/zoneinfo/Europe/Dublin /etc/localtime
sudo dpkg-reconfigure -f noninteractive tzdata

Answer: You should be able to use debconf-set-selections to preset the configuration.  Install debconf-utils and run debconf-get-selections | grep tzdata on a properly configured system to figure out what to set it too.
Comment: For things that are debconf based, this should work. But tzdata prefers the config from /etc/timezone. So this does not work on an already installed (wheezy) system.
Answer: You can also use the recipe from the (now defunct) Puppet wiki (archive) which replaces /etc/localtime with the appropriate zoneinfo file from /usr/share/zoneinfo:-
class timezone {
    package { "tzdata":
        ensure => installed
    }
}

class timezone::central inherits timezone {
    file { "/etc/localtime":
        require => Package["tzdata"],
        source => "file:///usr/share/zoneinfo/US/Central",
    }
}

class timezone::eastern inherits timezone {
    file { "/etc/localtime":
        require => Package["tzdata"],
        source => "file:///usr/share/zoneinfo/US/Eastern"
    }
}

class timezone::pacific inherits timezone {
    file { "/etc/localtime":
        require => Package["tzdata"],
        source => "file:///usr/share/zoneinfo/US/Pacific"
    }
}

class timezone::mountain inherits timezone {
    file { "/etc/localtime":
        require => Package["tzdata"],
        source =>
             "file:///usr/share/zoneinfo/US/Mountain"
    }
}

I'm not sure if dpkg-reconfigure does anything extra, but I have used the above recipe and it works perfectly.
Answer: sudo EDITOR='sed -Ei "
    s|tzdata/Areas=.+|tzdata/Areas=\"Asia\"|;
    s|tzdata/Zones/Asia=.+|tzdata/Zones/Asia=\"Shanghai\"|
    "' dpkg-reconfigure -f editor tzdata

Related answer: How do you set a locale non-interactively on Debian/Ubuntu?
Answer: dpkg-reconfigure -f noninteractive not very intuitive.
I want to point out another way.
A. debconf frontend: teletype
It's a hidden option (seems debconf builtin frontend).
echo -e 'Asia\nTokyo' | sudo dpkg-reconfigure tzdata -f teletype

It's easy to read and write.
 debconf frontends
see all frontends (but no teletype listed)
dpkg-reconfigure debconf
or
dpkg-reconfigure debconf -f teletype

Dialog
Readline
Gnome
Kde
Editor
Noninteractive

 check timezone
$ ll /etc/localtime; tail -v /etc/timezone
lrwxrwxrwx 1 root root 30 Apr 30 02:59 /etc/localtime -> /usr/share/zoneinfo/Asia/Tokyo
==> /etc/timezone <==
Asia/Tokyo

NOTE: sometimes maybe you need rm /etc/localtime first (if it is broken link).
B. manually edit file
maybe off-topic
ln -sf /usr/share/zoneinfo/Asia/Tokyo /etc/localtime
echo 'Asia/Tokyo' > /etc/timezone

OR
ln -sf /usr/share/zoneinfo/Asia/Tokyo /etc/localtime
apt install tzdata        # it will use the linked timezone

OR
ln -sf /usr/share/zoneinfo/Asia/Tokyo /etc/localtime
dpkg-reconfigure tzdata   # it will use the linked timezone

tested on ubuntu18 & 20
Answer: Its very simple and only need to type a command and answer the simple questions.
then run:
/usr/bin/tzselect

Comment: man tzselect: "Note that tzselect will not actually change the timezone for you. Use 'dpkg-reconfigure tzdata' to achieve this."

automate dpkg-reconfigure tzdata


Minimal code to create a Direct3D9 Device

Question: This isn't for stable release code, I just need to get a windowed D3D9 device created in a C++ app from a HWND on my dev PC for testing something... it can default on loads of options.
I was trying to hack it together from an old D3D8 class I had but I'm getting D3DERR_INVALIDCALL.
Basically I have this now:
    HWND mHWnd = ...;
    LPDIRECT3D9 mpD3D = Direct3DCreate9(D3D_SDK_VERSION);

    D3DPRESENT_PARAMETERS md3dpp;
    ZeroMemory( &md3dpp, sizeof(D3DPRESENT_PARAMETERS) );
    md3dpp.Windowed                 = true;
    md3dpp.SwapEffect               = D3DSWAPEFFECT_DISCARD;
    md3dpp.BackBufferCount          = 1;
    md3dpp.EnableAutoDepthStencil   = 0;
    md3dpp.hDeviceWindow            = mHWnd;
    md3dpp.BackBufferWidth          = 0;
    md3dpp.BackBufferHeight         = 0;
    md3dpp.FullScreen_RefreshRateInHz = 0;
    md3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
    md3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
    md3dpp.MultiSampleType = D3DMULTISAMPLE_NONE;
    md3dpp.MultiSampleQuality = 0;

    LPDIRECT3DDEVICE9 mpD3DDevice=0;
    HRESULT hr = mpD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,mHWnd,0,&md3dpp,&mpD3DDevice);

I figure some D3DPRESENT_PARAMETERS options might be to blame - I don't care about back-buffers of z-buffers or stencils or AA, any old plain device is fine.
Have I copy-pasted together some incompatible flags?
Answer: 1 problem is that you need to set some Behaviour flags.
From the docs on CreateDevice.:

BehaviorFlags [in]
   DWORD
   Combination of one or more options that control device creation. For more information, see D3DCREATE.

And from the D3DCREATE docs:

D3DCREATE_HARDWARE_VERTEXPROCESSING, D3DCREATE_MIXED_VERTEXPROCESSING, and D3DCREATE_SOFTWARE_VERTEXPROCESSING are mutually exclusive flags. At least one of these vertex processing flags must be specified when calling CreateDevice.

Try:
HRESULT hr = mpD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,mHWnd,D3DCREATE_MIXED_VERTEXPROCESSING,&md3dpp,&mpD3DDevice);

Comment: Doh! That's what comes from brainless code-pasting. It works as expected now.
Comment: @John: Hehehe, its easy to miss :)


Construction of a sequence associated to the Heisenberg uncertainty principle.

Question: In harmonic analysis, we have the Heisenberg uncertainty principle, i.e.

Suppose $f\in\mathcal{S}(\mathbb{R})$, which satisfies the normalizing condition $\int_{\mathbb{R}}|f(x)|^2dx=1$, then
$$\left(\int_{\mathbb{R}}x^2 |f(x)|^2 dx \right)\left(\int_{\mathbb{R}}\xi^2 |\hat{f}(\xi)|^2 d\xi \right)\geq \frac{1}{(4\pi) ^2}.$$
Where $\hat f(\xi)=\int_{\mathbb{R}}f(x)e^{-2\pi i x \xi}dx.$

And this formula can be generalized to $n$-dimension:

Suppose $f\in\mathcal{S}(\mathbb{R}^n)$, which satisfies the normalizing condition $\int_{\mathbb{R}^n}|f(x)|^2dx=1$, then
$$\left(\int_{\mathbb{R}^n}|x|^2 |f(x)|^2 dx \right)\left(\int_{\mathbb{R}^n}|\xi|^2 |\hat{f}(\xi)|^2 d\xi \right)\geq \frac{n^2}{(4\pi) ^2}.$$
Where $\hat f(\xi)=\int_{\mathbb{R}^n}f(x)e^{-2\pi i x\cdot\xi}dx.$

Since we still have
$$\left(\int_{\mathbb{R}^n}x_i^2 |f(x)|^2 dx \right)\left(\int_{\mathbb{R}^n}\xi_i^2 |\hat{f}(x)|^2 dx \right)\geq \frac{1}{(4\pi) ^2}.$$
Then, we derive the generalized inequality  by using the Cauchy-Schwartz inequality.
And the equalities can be achieved: Consider the Gaussian distribution function and adjust the coefficients suitably.
Now, I am looking for a sequence of functions $\{f_k\}_{k\geq 1}\subset \mathcal{S}(\mathbb{R}^n)$, each $f_{k}$ satisfies the normalizing condition, but for $i\neq j$, we have
$$\left(\int_{\mathbb{R}^n}x_i^2 |f(x)|^2 dx \right)\left(\int_{\mathbb{R}^n}\xi_j^2 |\hat{f}(x)|^2 dx \right)\to 0, \quad (k\to \infty).$$
Maybe we can construct such sequence by adjusting some coefficients of the Gaussian distribution function? Any help would be appreciated.
Comment: For completeness, the integral inequality you state is proven [here](https://math.stackexchange.com/q/2925300/631742) in one dimension and [here](https://math.stackexchange.com/a/253928/631742) in multiple dimensions. (In fact, the proof in multiple dimensions that I cite is sloppy because it doesn't state in which function space the identities used hold and where they are inferred by continuity arguments, but oh well...)
Answer: We consider the function with the form
$$ f=c\cdot e^{-(k_1 x_1^2+k_2 x_2^2+x_3^2+\cdots+x_n^2)/2} $$
and then adjust the coefficients.
First, since $$ \Vert f\Vert_{L^2}=1$$
we have
\begin{align*} 1 &=c^2\cdot \Big(\int e^{-k_1 x_1^2}\, dx_1\Big)\Big(\int e^{-k_2 x_2^2}\, dx_2\Big)\Big(\int e^{-x_3^2}\, dx_3\Big)\cdots \Big(\int e^{- x_n^2}\, dx_n\Big) \\
&= c^2\cdot \big(\frac{\pi}{k_1}\big)^{1/2}\cdot \big(\frac{\pi}{k_1}\big)^{1/2}\cdot \pi^{(n-2)/2}
\end{align*}
thus, we can take $$c=\Big(\frac{k_1 k_2}{\pi^n}\Big)^{1/4}. $$
Furthermore, we have
\begin{align*}
\int x_1^2 |f|^2\,dx &=c^2\Big(\int x_1^2 e^{-k_1 x_1^2}\,dx_1\Big)\cdot \Big(\int e^{-k_2 x_2^2}\,dx_1\Big)\Big(\int e^{-x_3^2}\, dx_3\Big)\cdots \Big(\int e^{- x_n^2}\, dx_n\Big)\\
&=\Big(\frac{k_1 k_2}{\pi^n}\Big)^{1/2}\cdot \frac{\pi^{1/2}}{2k_1^{3/2}}\cdot \frac{\pi^{1/2}}{k_2^{1/2}}\cdot \pi^{(n-2)/2}\\
&=\frac{1}{2k_1},
\end{align*}
and
\begin{align*}
\int \xi_2^2|\hat{f}|^2\,dx &=\int |\partial_{x_2}f|^2\,dx\\
&=\int |k_2x_2\cdot f|^2\,dx\\
&=k_2^2\cdot \frac{1}{2k_2}\\
&=\frac{k_2}{2}
\end{align*}
thus $$\Big(\int x_1^2|f|^2\,dx\Big)\Big(\int \xi_2^2|\hat{f}|^2\,dx\Big)=\frac{k_2}{4k_1} $$
so, what we need is to take suitable coefficients $k_1,k_2$ such that
$$\frac{k_2}{k_1}\to 0.$$


Agrupar elementos de um array durante um loop no php

Question: Boa noite pessoal, venho com mais uma dúvida em um loop no php.
Estou precisando criar um PDF de um relatório bem extenso. Uma alternativa que o próprio MPDF indica, é criar blocos e ir escrevendo as páginas uma a uma. Vai ser uma sobrecarga mas, preciso gerar um pdf, com um relatório que pode ter até 100 mil registros (pretendo exibir 100 por página ou ir adaptando), por isso o MPDF não consegue receber o html todo de uma vez.
A questão é que estou com um array, onde cada índice recebe uma linha de dados (uma tag
) que recebo do banco de dados. Porém eu queria agrupar isso em blocos de 100 por exemplo, ou seja, cada índice, agrupar 100 linhas.
O meu array atual segue esse formato
$tr = [
  0 => "
Valor 1
",
  1 => "
Valor 2
",
  2 => "
Valor 3
",
  3 => "
Valor 4
",
  4 => "
Valor 5
",
  ...
];

No exemplo acima, se fosse por exemplo 2 elementos por índice, eu precisaria que ficasse assim:
$tr = [
  0 => "
Valor 1

Valor 2
",
  1 => "
Valor 3

Valor 4
",
  2 => "
Valor 5
" ...
];

Eu tentei fazer um loop, que mais parece uma gambiarra, mas dá alguns erros de índice e acaba perdendo alguns elementos, o que tentei foi isso:
$group = [];
for($i = 0; $i <= count($tr); $i++) {
    for($i2 = 0; $i2 < 100; $i2++) {
        $group[$i] .= $tr[$i2];
        unset($tr[$i2]);
    }
    $tr = array_values($tr);
}

O que tentei fazer é, a cada laço do loop, preencher até os 100, e a laço do segundo for eu faço um unset limpando aquela variável, pra quando sair do for e ir pro próximo loop de fora, reorganizar o array sem os itens que já foram contabilizados.
Alguém consegue me ajudar com essa lógica. Não estou conseguindo pensar em uma maneira limpa e formar isso
Answer: Você pode utilizar a função array_chunk() para quebrar sue array em blocos de 100 elementos. A cada um desses blocos você pode agrupar seus elementos usando a função implode() que junta elementos de um array em uma string.
No exemplo criei um array $tr contendo 731 elementos
 e apliquei o raciocínio descrito acima.
<?php
//Cria um array com 731 elementos para o exemplo.
for($i=1;$i<=731;$i++){
  $tr[]="
Valor $i
";
}

//Quebra o array em blocos de 100 elementos e itera sobre eles.
foreach(array_chunk($tr, 100) as $item){
  $resultado[]= implode($item); //Agrupa cada bloco em uma string e a adiciona ao resultado.
}

print_r($resultado);

Teste o código no Repl.it


Find a tangent line on a function equal to a specific slope

Question: Find the tangent line on $f(x)=x^2$ which runs parallel to the slope of $y=2x+6$.
Comment: Welcome to MathSE.  When you pose a question here, it is expected you include your own thoughts on the problem.  You should show what you have attempted and explain where you are stuck so that you receive responses that address the specific difficulties you are encountering.  This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.
Comment: Does this answer your question? [Tangent Line to the curve that is Parallel to the line](https://math.stackexchange.com/questions/484873/tangent-line-to-the-curve-that-is-parallel-to-the-line)
Comment: The slope of y=2x+6 is 2, and y=2 is precisely a horizontal line. When is the tangent line to f(x)=$x^2$ horizontal?
Comment: This is not the right equation.
Comment: See [How To Ask A Homework Question](https://math.meta.stackexchange.com/questions/1803/how-to-ask-a-homework-question). That aside, this question has been asked here many times, albeit with different numbers. A quick search will find several examples. [This answer](https://math.stackexchange.com/a/484877/265466 ) in particular is quite detailed and complete. You might also look through the related questions in the list at right.
Answer: Solution 1: The equation of the tangent line is $y= 2x -1$
Explanation: Suppose  $y= 2x + c .......(1)$
be the equation of the tangent we're looking for. Why the slope of the line is $2$? Think about it. Since this straight line is a tangent to the graph of $y= x^2$........(2), there is exactly one solution to the equation $(1)$ and $(2)$. If we substitute the $y$ value from (1) into the equation (2), then we have the following equation
$$ x^2 = 2x +c.$$ Equivalently, $$ x^2 -2x -c.$$ This quadratic equation must have discriminant equals to $0$. Think about it why? Therefore, we have $$(-2)^2 - 4.1. (-c)= 0.$$ Hence, $$ c= -1$$. This gives our required tangent line.
Solution 2: Easy one
Let $(p, p^2)$ be point on the graph where the tangent line touches the graph.
Note that the derivative of the function $x^2$ at the point $(p, p^2)$ is $2p$. You see why? This derivative is essentially the slope of the tangent line. Hence $$2p = 2.$$ Therefore, $p =1$. Then the point on the graph is basically $(1,1)$. Now use our favorite point-slope formula to find the equation of the tangent line. So, the equation of the tangent line is $$y-1 = 2(x-2),$$ and we're done.


How to increment variable in Twig file?

Question: I'm using a view grid template and a views-view-fields--view-machine-name.html.twig template file in order to render some pictures in grid format. I want to assign dynamic CSS classes to every picture that is being rendered, for example, using the following markup.

{{ fields.field_picture.content }}

I have set a variable in Twig with the following code, but since there is no loop, it doesn't get incremented.
{% set id = 0 %}

So for every picture I have the same CSS classes (profile-pic pic0).
I want to get the following.

Picture 1
profile-pic pic0
Picture 2
profile-pic pic1
Picture 3
profile-pic pic2
Picture 4
profile-pic pic3

If I use the following code, the same imagine is rendered instead of the pictures I have.
{% for field in fields -%}

{{ fields.field_picture.content }}

{%- endfor %}

How do I get the counter to be increased, and all the images to be rendered?
Answer: You don't need another preprocess function anymore as you can easily do this in only Twig now. But you need another template. The one you are currently using loops through all fields of one row. Not just your image field. But you want to have the template that targets exactly this one image field, where you want to loop through all items of this field's .content.
For mere demonstration purpose I'll leave that untouched for now and only show you how to increment variables in a for-loop in Twig:
{% set id = 0 %}

{% for field in fields -%}

{{ fields.field_picture.content }}

  {% set id = id + 1 %}
{%- endfor %}

You might also wanna have a look at the loop variable where {{ loop.index }} or {{ loop.index0 }} simply gives you the current iteration of a loop. Two more lines saved.
{% for field in fields -%}

{{ fields.field_picture.content }}

{%- endfor %}

And last but not least this little gem: slice – to display a subset of items. Let's say only the first five ones.
{% for field in fields|slice(0, 5) -%}

{{ fields.field_picture.content }}

{%- endfor %}

Answer: As you mentioned, there's no loop, so you can't do this in the template file (well you could, but it wouldn't be worth the effort).
Instead, you could maintain a static variable in a preprocess function:
function MYTHEME_preprocess_views_view_fields__view_machine_name(&$vars) {
  static $counter = 0;
  $vars['counter'] = $counter++;
}

And refer to it in the template as normal:

{{ fields.field_picture.content }}

You might need to tweak that, for example if the View is rendered twice on the same page.
Comment: Yeah I think the duplicate images are a symptom of the way the OP is trying to implement a loop in the template @kiamlaluno (when it's the parent template preprocess that would actually implement that Views-row loop)
Comment: @Clive I know that is the reason: The OP is referring the same field all the times. Is the preprocess function you are referring called for each field on the view? if it so, then probably that should be remarked, just in the case the OP didn't get it.
Comment: @NoSssweat The only difference between a static var and normal var is that it remembers its value when you leave the function, so it's the same next time the function is called. Aside from that, it can be treated as a normal variable in any PHP context
Comment: There's no way without doing _some_ amount of preprocessing - quite simply there's no incrementing variable available to you in the context, so you need to provide one. You could do it at a more generic level, for example so that all views-fields templates have a row index in them, but there's no way to do that in Twig alone. You need PHP to provide that data, Twig will consume it. Which is exactly how it should be, Twig is for display, not logic
Comment: I take the OP's problem is not only to get the counter increased, but also not getting the same image rendered 4 times.
Comment: @kiamlaluno that happened because of the for loop she used on twig `{% for field in fields -%}`.
Comment: @Clive thanks, its working fine now. A nice learning experience for me. But can't we do this same thing without writing any preprocess functions? Just for curiosity..
Comment: @SugandhKhanna I'd like to believe there is twig template only way, but haven't discovered it yet.
Comment: @Clive – Things might have changed in the meanwhile as I found some nice samples without the need to use another preprocess function. See my answer.
Comment: @Clive can I conclude from your answer that any static variable inside a preprocess variable can be outputted easily on twig `{{ staticvarname }}` or only certain preprocess functions? hmm now that I think about it, it's probably the $vars array.
Comment: Yes, you could. But it would be awkward and unnecessary, and not something I'm interested in figuring out right now :)
Comment: @kiamlaluno I thought you would ;) And yeah, worth mentioning

How to increment variable in Twig file?


Expected number of happy children

Question: This is a followup on Arrangements of children.  (I am transcribing my notes, and making up problems to test my understanding and confirm their correctness)  I'll restate the set up.  $n$ children must be arranged in a row, but $k$ pairs of children will be unhappy unless they are together.  The others will always be happy.  If they are randomly arranged, is the expected number of happy children?
The game plan is to use linearity of expectation.  Let
$$ X_i = \begin{cases} 1 & \text{if the $i$th child is happy} \\
                       0 & \text{otherwise}
         \end{cases}
$$
and let $F_i$ denote the event that the $i$th child is "fussy" -- he belongs to one of the pairs.  Then we have:
$$
 P(X_i = 1) = P(X_i = 1|F_i')\cdot P(F_i') + P(X_i = 1|F_i)\cdot P(F_i)
$$
This expression holds in general.  But we have a boundary condition.  In particular,
$$P(X_1 = 1|F_1) = 1/n = P(X_n = 1 | F_n)$$
Since the $X_i$'s are indicators, we have $E(X_1|F_1) = \frac{n+1-2k}{n} = E(X_n|F_n)$.
For all the rest, we have $P(X_i = 1)  = E(X_i) = 1\cdot \frac{n-2k}{n} + \frac{2}{n}\cdot \frac{2k}{n}$
So it looks like
$$
  E(X) = \frac{2}{n} (n + 1 - 2k) + (n-2)\left(\frac{n-2k}{n} + \frac{4k}{n^2}\right)
$$
Is that correct?
Edit: Here is a write up of my first attempt,  which I thought was fallacious, but which got the same answer as André.
Let
$$X_i = \begin{cases} 1 & \text{if the $i$th is happy} \\
                      0 & \text{otherwise}
        \end{cases}
$$
We have
$$
P(X_i = 1) = P(X_i = 1|F_i')P(F_i') + P(X_i = 1|F_i)P(F_i) \\
           = 1 \cdot \frac{n-2k}{n} + \frac{2}{n}\frac{2k}{n}
$$
so that
$$
E(X) = n E(X_i) = n P(X_i = 1) = n - 2k + \frac{4k}{n}
$$
The mystery to me is that I basically sampled with replacement (and ignored the boundary) to get that $P(X_i = 1|F_i) = \frac{2}{n}$.
Comment: Let us do a careful evaluation of $\Pr(X_i=1|F_i)$. Child $i$ could be sitting in a non-end seat, and then the probability her friend sits next to her is $\frac{2}{n-1}$, or she could be in an end seat, in which case the probability is $\frac{1}{n-1}$. That gives probability $\frac{n-2}{n}\cdot \frac{2}{n-1}+\frac{2}{n}\cdot \frac{1}{n-1}$, which simplifies to $\frac{2}{n}$. So the $\frac{2}{n}$ is right.
Answer: There are $n-2k$ children who will be happy with probability $1$. We need to find the expected number of happy fussy children.
Divide the $2k$ fussy children into $k$ couples. Call these couples $1$ to $k$. Let $X_i=1$ if the two children in couple $i$ are happy, and let $X_i=0$ otherwise. We want $2E(\sum X_i)$, which is $2\sum E(X_i)$.
There are $\binom{n}{2}$ equally likely ways to choose the pair of spots occupied by couple $i$. Of these, $n-1$ are "favourable." Thus $\Pr(X_i=1)=\frac{2}{n}$.
It follows that the expected number of happy fussy children is $\frac{4k}{n}$. Add $n-2k$ to this.
Comment: Thanks André.  I got that answer on my first try, but I used a different (and I think fallacious method).  Can you take a look at that write up in a few minutes and comment?  Basically, the difference is I didn't mess about with the boundary.
Comment: Sure. I think separating out the $n-2k$ is useful, it lets us concentrate on the "variable" component.
Comment: I agree.  My argument is an artifact of how I write on paper.  I end up making a "table" of equations.  You can sort of see that the $1$ is below $P(X_i=1|F_i')$, $(n-2k)/n$ is below $P(F_i')$, etc, because they are equal.  It looks neater on paper though.
Comment: I have left a comment below your post, justifying your $\frac{2}{n}$. My solution had another justification of $\frac{2}{n}$.

Expected number of happy children


Looking for mathematical account of ANOVA

Question: I am looking for a freely available, mathematical description of the standard analysis of variance (several factors, one dependent variable). It should be self-contained and be readable by a person without any knowledge of statistics but a good background in mathematics and probability theory.
Almost all texts I find are either step-by-step instructions on example data-sets, heuristic outlines written for scientists from applied areas or they use a lot of statistical lingo to explain the concept (with only crippled math).
Ideally, the text would include a derivation of the F-distribution (why does it emerge in this setting?) and the F-test as well as the relation to regression.
Comment: ANOVA viewed through the lens of linear regression theory is, to me, the most appealing and unified method of learning and understanding the topic. A mathematician of most any stripe will feel quite comfortable thinking in terms of linear algebra and, in particular, projections. The $F$-test can then be understood both in terms of ratios of sums of squares and as a monotone transformation of a likelihood-ratio test, which give two complementary viewpoints. For one such text, Seber & Lee (2003), *Linear Regression Analysis*, 2nd edition, Wiley is a choice I can recommend, though it's not free.
Comment: @cardinal Another good one is *Plane Answers to Complex Questions*, by Christensen (ISBN 978-0387953618).
Comment: @chl: I have heard of this book, but am not familiar with it. Judging by the table of contents, though, it seems to be a good option. I might even consider adding it to my library. Thanks for mentioning it.
Answer: Everything you ask for is beautifully accomplished by Jack Kiefer in his classic Introduction to Statistical Inference (Springer-Verlag 1987).  ANOVA is introduced as a special case of the General Linear Model (i.e., regression) in chapter 5, then taken up again at the end of chapter 8 as an application of normal-theory tests.  Chapter 8 begins with a statement of the distributions associated with the Normal--t, F, and chi-squared along with their noncentral versions--and shows from first principles how they arise in each setting.  General background on estimation is developed in chapters 1-4.
Because this is not a math text, no effort is made to derive explicit formulations of the PDFs of these distributions: the focus is on specifying certain optimal properties and additional criteria (such as invariance, unbiasedness, or linearity) and then deriving, from first principles, the tests that satisfy them and critically evaluating the characteristics of those tests.  The math is reasonably rigorous and all statistical terminology is developed ab initio and clearly defined in mathematical terms.
I'm not sure what you mean by "freely available," but this book remains in print, is not expensive, and used copies can be had for very little.
Comment: thanks for the suggestion, I will check it out. I was hopen for an online-text, though :-)
Answer: This paper of Terry Speed may interest you.
Special invited paper:
What is an Analysis of Variance?
T. P. Speed
Annals of Statistics Vol 15 No 3 (1987)
Available from project Euclid with commentary from some big names including Tukey (who says he's not equipped to comment adequately on the mathematical niceties and careful craftsmanship of the paper.)
Link


Find new range over linear transformation using change of variables technique

Question: I have encountered some problems when solving problems of bivariate continuous random variables finding the new support. For example,
f(x,y) =\begin{cases}
2e^{-x-2y},  & \ {0<x<y<\infty} \\
0, & \text{else where}
\end{cases}
To find the distributions of U and V when where U = Y -  X, V = Y, I found the joint pdf of U and V as the following:
f(u,v)=
\begin{cases} 2e^{-3v+u}, & \in \color{red}{ T=\{(u,v): 0<u<v,v < u+v, v<\infty \}} \\
0, & \text{else where}  \end{cases}
My challenge is to find the correct T/range as support for the joint density function of U and V and, then I will use it to find the marginals of each. What is also challenging is finding the support (range) of these marginals as well.
I have looked up for similar questions but it does not seem that I have grasped the method to do so. Is there a more intuitive way to think about it and solve such problems?
Also, I would appreciate more references to read and practice on this particular part of the problem.
Answer: Take the original constraint $0<x<y<\infty$ and write it in terms of $u$ and $v$ to get $0 < v-u < v < \infty$. Rewriting these last inequalities gives $0 < u < v < \infty$. This is what you have (note that your $v < u+v$ inequality is redundant with $0 < u$).
To find the support of the marginals, just take the constraints from the joint PDF and ignore the other variable. So $0 < u < \infty$ and $0 < v < \infty$.
Comment: Can you explain further how did you rewrite the initial inequality? And why we should ignore the other variable from the constraints of the joint PDF?
Comment: Substitute $x=v-u$ and $y=v$ into $0<x<y<\infty$. To get the support of the marginal of $U$, just think about what values $u$ can take in the region $0<u<v<\infty$.
Comment: If I have take the integral of f(u,v) over [u,∞] I get f(u)= \begin{cases} 2/3 e^{-2u} , & 0<u<∞ \end{cases} and if I integrate f(u) over [0,∞], I get 1/3 which is incorrect and it should be 1. Or did I miss something here?
Comment: @iAziz I think your original PDF (in $x$ and $y$) is not actually a PDF; it would be if you changed the constraints to $0 < x < \infty$ and $0 < y < \infty$.
Comment: I just realised that my PDF function is not correct and that is why I am getting everything else wrong.


Body Field Trimming

Question: Does anyone have a solution to the following issue?
I have a body field that I would like to have initially trimmed with a "Read more" link to expand the remainder of the text. This is specifically only on the Node page (so not a views issue) of a custom content type.
I have tried the Smart Trim module, but it doesn't expand the text when click, it just links back to the node page, which is what I'd expect from a views to node link.
Does anyone have any other ideas? I'm stuck currently, either I leave it consistently expanded or just have it trimmed with no "read more" link. Thanks
Answer: If I understood your question correctly, you need the Expand Formatter module. From the project page:

This module provides a formatter for existing text, long text and text with summary widget types. This module allows you to change how the content is being display (formatted) by providing new format types:
Trimmed (expandable)
Summary or Trimmed (expandable)

Granted, this is only for D7, but you didn't tag your question with core version, so I'm guessing that you're using D7.

Body Field Trimming


Couchbase increase number of vbuckets in a bucket

Question: I have a questions about couchbase bucket.
Is there anyway to change the number of vbuckets of a bucket. By default, it is 1024.
Anyone know, pls tell me.
Thank you
Answer: vBuckets are an internal representation of Buckets (and are not visible to the application) that allow Couchbase to shard data evenly across the cluster. The quantity of vBuckets is not configurable, but also is factored into the key hashing algorithm that determines which vBucket a k/v pair lives on (which is why it isn't configurable). Is there a reason you wanted to change this?
Answer: If you have issues trying to do cbrestore between environments (say Linux to Mac) due to the difference in vbuckets (linux has 1024, mac has 64 or 256), then read this article:
http://docs.couchbase.com/couchbase-manual-2.5/cb-admin/#couchbase-backup-restore
Specifically, use the memcached protocol instead:
<code>cbrestore /linuxbackup/today memcached://mac:11211 -b default -B default
</code>


Application free trial via registry

Question: For my VB.NET applications, I am wanting the user to have a free trial for x amount of days.
Where is the best place to record the amount of days past?
In the registry? Can't someone just delete the registry key, and then have the full x amount of days again?
Is there a better way?
Answer: Anything you store on the user machine could be compromised.
If you are serious about this thing then your "best" option is to have a webservice that your apps call at every startup passing some form of identification string.
(And this could be compromised too).
For the purpose to generate an identification string you could look at this question and the following answers
Answer: It doesn't matter where you store something on the local machine because it can always be removed.
A user could start up a Virtual PC install your app, and then roll back the virtual PC after 28 days and install again.
One option is to generate a key that is unique to the machine and then verify this with a web service. This is not completely hacker proof but it is better.
Answer: You could add some information to any file saved with the trial version of your app which is unique to that specific version of the app (perhaps a timestamp from when it was installed).
When a trial version of your app tries to open a file, it will check this signature and ensure that it was created with that same instance, otherwise refuse to open the file.
This essentially neuters the ability to simply reinstall the app and continue using it.

Application free trial via registry


Module with block plugin not using custom template

Question: I am struggling to get my custom module template to get use by by block plugin.
I have followed the solution given at: Twig Template for a Custom Block Plugin but continually get this error:

The website encountered an unexpected error. Please try again later.
  Twig_Error_Loader: Template
  "modules/custom/lrg_osm/templates/block--osmnhd.html.twig" is not
  defined in Twig_Loader_Chain->getCacheKey() (line 64 of
  themes/contrib/bootstrap/templates/block/block.html.twig).
  Drupal\Core\Template\TwigEnvironment-->getTemplateClass("modules/custom/lrg_osm/templates/block--osmnhd.html.twig")
  (Line: 424)

I have tried to also fiddle the name of the twig file in various ways to not avail.
My module file structure is shown below with relevant code if anyone is able to point out the error of my ways please:

src/Plugin/Block/osmnhdblock.php
<?php
declare(strict_types=1);

namespace Drupal\lrg_osm\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;

/**
 * Provides a 'OSM Block for Home development Landing page' block.
 *
 * @Block(
 *   id = "osmnhdblock",
 *   admin_label = @Translation("OSM New Homes Development (NHD) block"),
 *   category = @Translation("LRG")
 * )
 */
class OsmNhdBlock extends BlockBase implements BlockPluginInterface
{
    /**
     * {@inheritdoc}
     *
     */
    public function build()
    {
        return array(
            '#theme' => 'osmtheme',
            '#jsonDataLocations' => 'nhd some data',
            '#title' => 'nhd some title',
        );

        /*
         '#attach' => [
                'css' => '/css/openstreetmap.css',
                'js' => '/js/openstreetmap.js',
            ],
         */
    }
}

lrg_osm.module
<?php
declare(strict_types=1);

function lrg_osm_theme($existing, $type, $theme, $path) {

    return array('osmtheme' =>
        array(
            'variables' => array(
                'title' => null,
                'jsonDataLocations' => null
            ),
            'template' => 'block--osmnhd'
        )
    );
}

templates/block--osmnhd.html.twig
{#
/**
 * @file
 * Some description
 */
#}

{{ title }}

{{ jsonDataLocations }}

Answer: The templates directory must always be a direct descendent of the module or theme root directory, in your case /modules/custom/lrg_osm/templates/ (not modules/custom/lrg_osm/src/templates/).


Form API select list remove blank entry (default select an entry)

Question: I populate an select list using the following code.
$getCompanies = 'SELECT nid, title FROM node where type = "my_type"';
        $companiesResult = db_query($getCompanies);
        $companyArray = array();
        $companyArray['empty'] = "";
        while ($data = db_fetch_object($companiesResult)) {
            $companyArray[$data->nid] = $data->title;
        }
        $form['company'] = array(
            '#title' => t('Type'),
            '#type' => 'select',
            '#description' => t(''),
            '#options' => $companyArray,
        );
    }

This gives me an empty result first. I want to remove this empty result. I tried adding #required by it does not add a default selection. What can I do to remove an empty element?
Answer: The blank option was added by yourself:
$companyArray['empty'] = "";

If you remove that line you wont have a blank line, or alternatively your could change it to
$companyArray['empty'] = t("Please select");

To make the phrase Please select appear as default in the select option.
Answer: Try adding the property: '#required' => TRUE into $form['company'].
Comment: I did. It adds an * by the field but it does not remove the blank option.
Comment: Can you `dpm()` the array `$companyArray` ?
Comment: And also, what's the use of that line `$companyArray['empty'] = "";` ?


Is this feature or bug, for Setting focus to a textbox?

Question: This can be seen on Knockout.js site as well.
When I open this page in IE11 or FF 38, and go to Example 2: Click-to-edit and click on the Name - Bert Bertington, the Caret (cursor) of textbox is at the start of text, while in Chrome it is at the end.
If this is a feature, could somebody suggest how to keep the caret in the end when the label changes to textbox in IE11 and FF38.
I was able to fix this in FF38 by resetting the contents of observable as below, but his does not work in IE11.
<code>    var str = self.msg();
    self.msg('');
    self.msg(str);
</code>
I am using knockout-3.2.0 if that matters.
UPDATE
The issue seems to be with browsers rather than Knockout (sorry for the confusion).
I tried setting focus of the text field using JQuery and javascript .focus() functions and am still getting same result on IE11 and Firefox 38.
Any help would be appreciated.
Answer: You are correct, this is an issue of how different browsers handle the focus event. A workaround would be to manually set the cursor to the end of the text within the textbox.
An example of doing this can be found here. If you want this to happen automatically using knockout, you would have to create your own custom binding based on the hasFocus binding, or modify the KnockoutJS library directly. The focus event is triggered on line 3813 of the Knockout 3.2.0 non minified JS file.
Comment: Something I used to know .. .then I forgot and now I know again .. :) thanks.


AWS bootstrap AMI with credentials for downloading form a private s3 bucket

Question: I'm trying to bootstrap an AMI to download a file from a private S3 bucket.
I've set the credentials correctly and when I try to copy a file from my bucket to my EC2 instance I can see in the system log that it was unable to detect my credentials.
What's weird that when I log to my instance using SSH and using the same command I'm successfully copying my file to my instance.
Here is the bash script for the UserData:
#! /bin/bash
yum update -y
sudo yum remove java-1.7.0-openjdk -y
sudo yum install java-1.8.0 -y
mkdir -p home/ec2-user/.aws
cat > home/ec2-user/.aws/config << EOF
[default]\n
aws_access_key_id=my_access_key_id\n
aws_secret_access_key=my_secret_key\n
region=eu-west-1
EOF
aws s3 cp s3://my_bucket_name/filename home/ec2-user/filename

Thanks,
Comment: You should consider using EC2 Instance Profiles to provide IAM credentials to your instances, instead of configuring credentials in a file like this.
Comment: Even better idea, thanks
Answer: It looks like your script will only run when the current directory is / because:
cat > home/ec2-user/...

is relative. This will work when you log in and happen to run with CWD=/.
I haven't tested it yet but I would suspect cloudinit does not run UserData from /.  You can either prove that by updating the script with a leading / or I can confirm it later.
Comment: Thanks for the response,
The instance is running from the root when bootstrapping, therefor i'm starting "home/ec2-user/...".
The creation of the directories and the config file are being created just fine.
For some reason the execution of the "aws s3 cp ..." gets an error.
Comment: The cloudinit normally runs as root but you want to use ec2-user credentials.  So it will look in root's Home directory. You can insert su to change user or look for a command line switch or env var to locate the credentials.  E.g. AWS_CONFIG_FILE. There are a few env vars will adjust the cli.
Comment: uh, I see I will give it a try.


Find the maximum and minimum under following constraint

Question: Find the maximum and minimum of $f(\textbf{x}) = x_1 + x_2 + \cdots + x_n $ under the constraint $\|\textbf{x}\|=1$.
My attempt:
For local optima, $Df(x) = \lambda Dg(x)$, where $g(x) = \|\textbf{x}\|^2-1$, so $[1,1,\dots,1] = \lambda [x_1 , x_2 , \dots , x_n]$. Note that $\lambda \neq 0 $, so what we have is that $x_1 = x_2 = \cdots = x_n = \frac{1}{\lambda}$ and putting it on constraint we have that $\lambda = \sqrt{n}$.
Now $f(x) = \sqrt{n}$ but I am not sure whether it is maximum and minimum. There seems to be only one value satisfying the lagrangian. Another point is that we know that both global minimum and global maximum exist  and shouldn't there be at least two different values of $\lambda$?
Answer: What Lagrange multipliers theorem gives you is some necessary condition on $x$ to have a constrained local extremum at $x$. When you want to find a global maximum/minimum (say of a continuous function over a compact set), it basically allows you to automatically rule out a large amount of candidate solutions.
In the case of $f$, we have that if $x$ is a local extremum of $f$ on $S^{n-1}$, then $x$ must satisfy $x_1=\ldots=x_n$. Plugging this into the $\{\lVert x\rVert=1\}$ constraint leads to $x_i^2=1/n$, ie. $x_i=1/\sqrt{n}$ for all $i$ or $x_i=-1/\sqrt{n}$ for all $i$. Note that there are 2 local extrema (not 1). The first case corresponds to the global maximum and the second one to the global minimum.


using statement in conjunction with Repeater DataBinds and events

Question: In relation to the below code, does the using statement take into consideration objects called via _ItemDataBound methods and Eval methods when finding objects that need disposing of?  Or will it try to dispose before attached events and evals are fired since they occur later in the life cycle?
In other words, does it only dispose the datacontext after all the Evals and attached Events to the repeater are called or will this cause datacontext has already been disposed errors?
protected void Page_Load(object sender, EventArgs e)
{
    using (EventManager manager = new EventManager())
    {
        EventDates = manager.GetWhatsOn(Request.QueryString["category"]);

        rptEventDates.DataSource = EventDates;
        rptEventDates.DataBind();
    }

...
public class EventManager : IDisposable
{
    private MainDataContext db;
    public EventManager()
    {
        db = new MainDataContext();
    }

    ....other methods....

    public void Dispose()
    {
        db.Dispose();
    }
}

Answer:
In relation to the below code, does the using statement take into consideration objects called via _ItemDataBound methods and Eval methods when finding objects that need disposing of?

No. It doesn't "find" objects to dispose at all - it just disposes of the object referred to in the first part of the statement. So your code is broadly equivalent to:
EventManager manager = new EventManager();
try
{
    EventDates = manager.GetWhatsOn(Request.QueryString["category"]);

    rptEventDates.DataSource = EventDates;
    rptEventDates.DataBind();
}
finally
{
    manager.Dispose();
}

Nothing else will be disposed, but the EventManager itself definitely will be disposed.
If anything requires the resource not to be disposed of until later, you shouldn't use a using statement.
Comment: Thanks Jon, makes sense.  So really that code is fine, but I shouldn't be wrapping the repeater with a using statement, instead let garbage collection do it's job?
Comment: @A-Bop: I don't know what `EventManager` is or what the `GetWhatsOn` method does, so it's hard to say whether your code is okay or not.
Comment: That's fair enough, I'll try to explain what I'm getting at - sorry if it's not very clear.  If EventDates contains objects that are called on Eval() on the repeater, but the object originated from the datacontext inside the EventManager - is the datacontext disposed of at Eval because it's in a using statement?
Comment: @A-Bop: If you just force eager evaluation, e.g. calling `ToList()`, then you should be okay to dispose of the data context. I don't think `Eval` is going to dispose of anything - you'd just end up with a data context which isn't disposed of. I don't know which LINQ provider you're using, but for LINQ to SQL that's generally not a problem.


Criação de Masks com javascript

Question: Eu preciso de criar máscaras para uns inputs que eu tenho no código, e já tinha perguntado sobre isso, mas penso que o post ficou desatualizado e então ficou "esquecido". No entanto o que tinha conseguido com aquele post foi:
HTML:
Dentro do :

Dentro do :
<input type="text" name="search" id="search" placeholder="Escreva o número de processo aqui..." required maxlength="5">

Javascript depois de :

Edit: montei um fiddle: https://jsfiddle.net/61tok014/ e aparentemente funcionou.
Comment: tentei o que falaram, mas continua a não funcionar. não ha outra maneira de fazer mascaras?
Comment: Faço todas as minhas masks com esse plugin sem problema. Tem certeza que os arquivos estão carregando.?
Comment: Eu uso muitos plugins, para obter icons do font-awesome, modals de bootstrap etc..será por causa disso? devo meter as mask primeiro?
Comment: Que você tem que colocar primeiro o jquery depois os plugins eu tenho certeza
Comment: Eu uso o sublime text, e costumo guardar os projetos com UTF-8 with BOM faz diferença?
Answer: Consegui! Alterei

para

Obrigado pela ajuda

Criação de Masks com javascript


Hook module and Drop table

Question: I would know if it's possible to drop a database table created by a module.
I could see the hook "uninstall" and "disabled" but nothing works.
Can you help me please?
Answer: It could sound a stupid question, but have you enabled your module?
Have you launched the uninstall procedure?
Comment: Disable does *not* uninstall. You need to go the the uninstall tab and uninstall your module there. Also, show your code.
Comment: @Berdir It seems the OP is asking about a third-party module. What you report about disabled modules is correct, indeed.
Comment: Hum, yes I have. I have enabled my module and I disabled. But the table doesn't drop

Hook module and Drop table


Select apenas 24 registros por dia

Question: Preciso de ajuda pra elaborar uma query que selecione apenas 24 registros de cada dia.
Por exemplo:
Dia 1: 100 registros
Dia 2: 50 registros
Dia 3: 34 registros
Quero pegar apenas 24 de cada dia: 1, 2 e 3...(nesse exemplo somaria: 72 registros)
SELECT date_format(hora,'%d/%m/%Y'), SUM(ponto) FROM `pontos` WHERE user = "teste" AND hora >= '2019-08-20' AND hora < NOW()

*Da forma que está, minha query traz a soma de todos os registros

Qual a melhor maneira de fazer isso?
Comment: Charles, você quer pegar apenas 1 valor por hora, é isso? tipo, pegar o valor da hora 00:00 do dia, depois o valor da hora 01:00 do dia e assim até dar as 24 horas e somar, é isto?
Comment: Como vc sabe que o valor 170 não é o resultado dos 24 registros? O que tem na coluna "ponto"?
Comment: tem o valor 1 (UM), onde quero pegar 24 pontos de cada dia
Comment: em um dia o cara pode fazer quantos pontos ele quiser (mais de MIL), mas eu quero pegar somente 24 por dia
Comment: @Heathcliff sim, isso é uma solução que resolve também, pois pegando 1 ponto por hora eu terei os 24 de cada dia.
Comment: @Sam acredito que o comando NOW considera a hora do registro, onde os registros de hoje(conforme o print) entraram em um horário inferior ao horário de NOW
Comment: Postei uma resposta atualizada agora. Veja se resolve.
Answer: Use uma subquery com LIMIT 24. Crie um alias para date_format(hora,'%d/%m/%Y') e use GROUP BY nesse alias para retornar todas as datas com o resultado de SUM(ponto):
SELECT date_format(hora,'%d/%m/%Y') AS dia, SUM(ponto) FROM
(SELECT hora, ponto
      FROM `pontos`
      WHERE user = "teste" AND hora >= '2019-08-20' AND hora < NOW()
      LIMIT 24
) AS subquery
GROUP BY dia

Veja no SQLFIDDLE
Comment: Bem estranho isso, o limit deveria funcionar :(... Mas se a resposta foi favorável, creio que mereça finalizar a pergunta com ✔.. Abs!
Comment: muito obrigado! Acredito que esse é o caminho certo...no entanto a query trouxe somente os 24 pontos do dia 2, eu gostaria que trouxesse a soma dos dias anteriores a partir da data 2019-08-20, nessa imagem da pra ver os registros das datas anteriores: https://uploaddeimagens.com.br/imagens/table-png-e590c062-3755-4bc8-93aa-3545aa8a8858
Comment: Eu atualizei o código na resposta. Testa aí de novo.
Comment: Aqui ainda não funcionou, https://uploaddeimagens.com.br/images/002/313/781/full/query.png?1567441302, mas eu vi o seu teste no SQLFIDDLE e é exatamente isso que eu preciso, eu vou tentar descobrir aqui porque não trouxe o mesmo resultado.
Comment: Tenta ver qual a versão do seu MySQL.
Comment: Opa, removi o LIMIT 24 e agora ele trouxe os resultados da soma do dia: https://uploaddeimagens.com.br/imagens/query-png-0c3a1667-0935-4f7a-b364-fd49228888b8, com isso eu vou fazer uma if no php onde se o valor for maior que 24, ele considera apenas 24 e soma tudo.
Comment: Agradeço muito pela ajuda! Abs!
Answer: Podes usar o LIMIT:
SELECT date_format(hora,'%d/%m/%Y'), SUM(ponto)
FROM pontos
WHERE user = "teste"
  AND hora >= '2019-08-20'
  AND hora < NOW()
LIMIT 24

Comment: não funcionou...pois mesmo com o LIMIT 24, a query continua trazendo a soma do total de registros do dia. *Anexei uma imagem na pergunta.

Select apenas 24 registros por dia


Intuitive understanding of instrumental variables for natural experiments

Question: I am wondering if my understanding of Instrumental vairables to exploit natural experiments is correct, or if I am misunderstanding something.
Is the logic as follows: by using an instrument, you are now comparing the outcomes of those who recieved higher levels of treatment because they had higher exposure to the instrument to those who received lower levels of treatment because they had lower exposure to the instrument, but these latter units would have recieved higher treatment had they been more exposed to the instrument?
so should I think intuitively as if it is to some degree a random experiment on a subset of units?
Comment: Perhaps, but one of the main ways IV are used is for de-confounding. Suppose $A\to X\to Y,$ but also $X\leftarrow Z\to Y.$ Then you may be able to use $A$ to de-confound $Z.$
Comment: Sure, and i meant this as one of the uses of IV for natural experiments for precisely this reason. But I am more wondering- beyond the causal paths and technical details, what intuitively are the comparisons we are making in the data when running an IV?
Answer: I interpret the background to be, you are interested in evaluating the effect of some (endogenous) "treatment" on some "outcome," and we assume that there is a valid "instrumental variable" for "treatment."

so should I think intuitively as if it is to some degree a random experiment on a subset of units?

Basically, yes. A valid instrument should be very much like a random experiment as follows:

With a valid experiment, treatment is randomly assigned, therefore treatment is independent of potential outcomes

With a valid instrument, the instrument is randomly assigned, therefore the instrument is independent of potential outcomes (and potential treatments).

Generally when you use instrumental variables, you are no longer estimating the effect of "treatment" on the "outcome." Instead, you are estimating the effect of "treatment" on the "outcome" for those units whose "treatment" can be changed by the "instrument."
The italicized part is the subset.

Is the logic as follows: by using an instrument, you are now comparing the outcomes of those who recieved higher levels of treatment because they had higher exposure to the instrument to those who received lower levels of treatment because they had lower exposure to the instrument, but these latter units would have recieved higher treatment had they been more exposed to the instrument?

Regarding the logic, for simplicity assume a binary instrument. You are comparing the outcomes of those exposed to the instrument, to the outcomes of those not exposed to the instrument. You then divide this comparison by the difference in the treatments of those exposed to the instrument, to the treatments of those not exposed to the instrument.
This ratio estimates the effect of "treatment" on the "outcome" for those units whose "treatment" can be changed by the "instrument."
Comment: With a continuous instrument, you are still estimating the effect of "treatment" on the "outcome" for those units whose "treatment" can be changed by the "instrument." However, the interpretation is no longer as simple/intuitive as in the binary instrument case.
Comment: Thank you for this answer. Just a quick follow up on the logic part- this still is exactly the logic with a continuous instrument, correct? it is just that thinking of it in terms of a binary one makes it clearer/more intuitive?


Modal Error property n does not exist on type component

Question: I'm quite new to angular. I'm trying to show my modal when I click a marker. It compiles succesfully and then outputs error. Sometimes doesnt compile succesfully. How can I fix this error? Is it because I set up jquery wrong? All of this code is in a component called HomeComponent. Code and error:
Answer: The m variable is no need in this case, you can remove it.
If you need pass parameter you can set #variable and pass it to markerClick.
(markerClick)="markerClick()"

markerClick(){
  $("myModal").modal("show");
}

Comment: Yeah, it's expecting 1 input if I remove the m. If you dont mind could you show me how to do it?
Comment: https://pastebin.com/fvqyNhcX , I tried to remove the marker passable parameter but the click didn't do anything.
Comment: with your html code, i think you don't need pass parameter, if you want you can pass $event as (markerClick)="markerClick($event)"
Comment: markerClick($event : MouseEvent){
    console.log($event)
    $("myModal").modal("show");
  }

like this? It registers the click but doesnt pop up the modal, and I changed the html code as you said
Comment: did you install bootstrap for your app?
Comment: yeah I set it up when I started the project,  I have "node_modules/bootstrap/dist/js/bootstrap.min.js" in the angular json.


Use ML to predict rule based model's output

Question: We have a legacy rule based model as a binary classier (0 vs 1). We want to replace it with a ML model. This rule based model uses only 4 features (age, race, gender, salary) and output 0/1. We have 20 extra features. So in total there are 24 features for 10 M unlabelled data points.
Here is our planned process:

Use this rule based model to generate label for this 10 M data points (using only 4 features)
Use ML models( like RF/logistic regression) to train on these data. The ML model will use 20+4 features to try to predict the label generated by rule based model

Questions:

Will this ML model has any chance to outperform the rule based model?
Will it be able to "extrapolate" from label generated by rule based model? Or will it just use the extra 20 features to add noise?
Any document / site discussing about this approach?
Comment: Machine learning can't squeeze blood from a stone.
Comment: So your features are age, race, gender.... I don't even want to know what you are trying to do...
Comment: @Harry Li - may I know how did you solve this issue? Even am stuck with similar problem due to lack of ground truth. So, your learning from this problem would be helpful for me. can I seek your inputs on how did you solve this problem?
Answer: I would expect it to decide that only the 4 features of the original model matter and to come very close to completely matching the old model.
Clearly, a new model will never do better at predicting the output of the old model than the old model itself.
Unless you for it ground truths or at least information that is better than predictions of the old model, how could it outperform it on real outcomes (other than by pure chance)? If you had real outcomes available for this many cases, I would expect some state-of-the-art ML approach to do pretty well, if some the additional predictors matter at least a little bit and your training data is reasonably representative of the actual task.
Comment: The argument that ML model might outperform is because it uses all 24 features and may be able to extrapolate while rule base's model only use 4 features?
Comment: Let's assume that the original rule based model has high precision and low recall. Can the new ML model (trained on the previous system output but with a larger feature set) aim for higher recall at similar precision?


Can't acces field collection with $content

Question: I try to render a field collection in my node--1.tpl.php template with print render($content['field_image_teaser']) with no succes. I followed the example at http://drupal.org/node/1155752
The strange thing is, when I do a print of $content width var_dump () my field is listed:
var_dump ($content);
//...
["field_image_teaser"]=>
      array(1) {
        ["und"]=>
        array(2) {
          [0]=>
          array(1) {
            ["value"]=>
            string(1) "1"
          }
          [1]=>
          array(1) {
            ["value"]=>
            string(1) "2"
          }
        }
      }
//...

but when I do a print of $content ['field_image_teaser'] the var_dump print out a NULL.
Edite:
I'm using the current recommended version 7.x-1.0-beta4.
With the answer of Neograph734 I spot that the the dump of the field "field_image_teaser" cames not direct form "field_image_teaser". It cames from the $node Object (which is referred in every field), but I can't render that value. There is no output with: print render($node->field_image_teaser);
So is there a way to get the field collection in a renderable form to use the regular template system, or is something else wrong?
Answer: field_view_field() would probably do the trick:
$rendered = drupal_render(field_view_field('node', $node, 'field_image_teaser'));

There are other options you can pass to the function (display mode for example), so it might be worth checking out the docs to see exactly how you want to use it.
Answer: var dump can dump arrays and objects. You are assuming it is an array by using array syntax $content ['field_image_teaser'].
However you probably get presented an object. Give $content->field_image_teaser a try.
Comment: When I do a var_dump ($content->field_image_teaser); the result is unfortunately the same: "NULL".


Statement ou PreparedStatement, por qual motivo evitar usar o Statement

Question: Quais problemas podem acontecer caso eu utilize o Statement ao invés do PreparedStatement na conexão JDBC ao banco de dados
//Código usando PreparedStatement, setando os valores da query através de métodos
<code>    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    String query = "SELECT * FROM exemplo WHERE coluna1 = ? AND coluna2 = ?";
    try {
        con = DBConnection.getConnection();
        ps = con.prepareStatement(query);

        ps.setString(1, valorExemplo1);
        ps.setString(2, valorExemplo2);
        rs = ps.executeQuery();
</code>
//Código usando Statement, concatenando os valores das variáveis à query
<code>        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        String query = "SELECT * FROM exemplo WHERE coluna1 = '"+valorExemplo1+"'
                        AND  coluna2 = '"+valorExemplo2+"';
        try{
            con = DBConnection.getConnection();
            stmt = con.createStatement();
            rs = stmt.executeQuery(query);
</code>
Comment: Isso serve prevenir ataques de [SQL Injection](https://pt.stackoverflow.com/q/100729/112052) <- esta pergunta é sobre C#, mas a ideia é a mesma
Answer: Boa Tarde Tudo bem?
A diferença está na velocidade, facilidade de manutenção e segurança da informação entre os objetos.
Quando você utiliza o Statement, tem todo o processamento desta declaração para ser processada no banco, o que demora um pouco mais de tempo, porem não é tão nítido com um volume baixo, o código não fica tão legível e você está passando sua declaração "toda em aberto".
<code>"SELECT * FROM exemplo WHERE coluna1 = '"+valorExemplo1+"' AND  coluna2 = '"+valorExemplo2+"';
</code>
Para alguém interceptar seu código, fazer injeção de SQL é mais fácil, está mais vulnerável.
Quando você usa o PreparedStatement, você já preparou toda a declaração, o que fica mais rápido para processar no banco, você tem a legibilidade e uma manutenção no código, visto que em grande parte dos casos os getters e setters são utilizados e você tem uma isenção desta vulnerabilidade (injeção de SQL), seu comando SQL só é "construída" depois, dificulta na interceptação.


How would I increment this number in mongoose?

Question: I want to increment or decrement the likes value in the schema. My fear is that if two people were to grab the value of likes close to the same time, and they both incremented it, the value would only increment once.
For instance if likes = 100 and person A incremented it at the same time person B incremented it, likes would be 101 instead of 102.
Should I make a separate schema for likes and for each like I give it a postId?
var postSchema = mongoose.Schema({
    name: {
        type: String,
        required: true,
        unique: false
    },
    likes: {
         type: Number,
         default: 0
    }
});

Answer: You can use this in mongoose to increment(change likes to -1 for decrement)
var query = {};
  var update = {$inc: {likes: 1}};
  var options = {'new': true};
  PostSchema.findOneAndUpdate(query, update, options, function (err, doc) {...
  })