mongod.conf - bindIp refuses connection

Question: I have two servers - one running the API I want to access the DB from and one running the actual database.
This is my mongod.conf file content:
# network interfaces
net:
  bindIp: 220.127.116.11
  port: 27017

This is the output from the ifconfig command on my ubuntu server:
eth0      Link encap:Ethernet  HWaddr be:08:9e:b1:e7:d7
          inet addr:22.214.171.124  Bcast:188.8.131.52  Mask:255.255.240.0
          inet6 addr: fe80::bc08:9eff:feb1:e7d7/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:14502 errors:0 dropped:0 overruns:0 frame:0
          TX packets:13741 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:33725605 (33.7 MB)  TX bytes:1816546 (1.8 MB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:80 errors:0 dropped:0 overruns:0 frame:0
          TX packets:80 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1
          RX bytes:5920 (5.9 KB)  TX bytes:5920 (5.9 KB)

The API is bound on port 80. Now when I remove the bindIp setting from the mongod.conf file the database connects as expected, but when I bind the ip, the database refuses the connection.
EDIT: the database refuses the connection because the service fails. This is the output from the logs (not really informative):

● mongod.service - High-performance, schema-free document-oriented
  database    Loaded: loaded (/lib/systemd/system/mongod.service;
  enabled; vendor preset: enabled)    Active: failed (Result: exit-code)
  since Mon 2018-07-02 11:04:43 UTC; 3s ago
       Docs: https://docs.mongodb.org/manual   Process: 13473 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=exited,
  status=48)  Main PID: 13473 (code=exited, status=48)
Jul 02 11:04:43 minimalistic-ledger-db systemd[1]: Started
  High-performance, schema-free document-oriented database. Jul 02
  11:04:43 minimalistic-ledger-db systemd[1]: mongod.service: Main
  process exited, code=exited, status=48/n/a Jul 02 11:04:43
  minimalistic-ledger-db systemd[1]: mongod.service: Unit entered failed
  state. Jul 02 11:04:43 minimalistic-ledger-db systemd[1]:
  mongod.service: Failed with result 'exit-code'.

EDIT2: this is the error from the mongodb log:

2018-07-02T11:04:43.444+0000 I CONTROL  [initandlisten] options: {
  config: "/etc/mongod.conf", net: { bindIp: "126.96.36.199", port:
  27017 }, storage: { $ 2018-07-02T11:04:43.475+0000 E NETWORK
  [initandlisten] listen(): bind() failed Cannot assign requested
  address for socket: 22.214.171.124:27017 2018-07-02T11:04:43.475+0000
  E NETWORK  [initandlisten] Failed to set up sockets during startup.
  2018-07-02T11:04:43.475+0000 E STORAGE  [initandlisten] Failed to set
  up listener: InternalError: Failed to set up sockets

What am I doing wrong?
Answer: A possible reason for this error could be that the network interface is not configured properly i think, or the IP address is already being used bya nother instance.
Try this out:

Verify that the network interface is properly configured and that
the IP address is available, try running ifconfig on the server.
ifconfig is a command used in Linux-based operating systems (such as
Ubuntu) to view and configure network interfaces and their settings,
including IP addresses, netmasks, and network device names.

Check if any other services are already using the specified IP
address and port combination. You can do this by running the command
sudo lsof -i :27017 on the server. If another service running on the
same port, and you should either stop that service or choose a
different port for MongoDB.

If none above helped you could try to change the bind IP
address to 127.0.0.1 to bind MongoDB to the localhost interface.
This will allow you to connect to the database from the same server
using the loopback IP address.

If not try to keep checking to the log for any other message that could be useful.
Sorry the delay

mongod.conf - bindIp refuses connection


How to prove this function is continuous on $(-1,1)$

Question: How to prove $f(x)=\dfrac{x}{(1-x)^2}$ is continuous on $(-1,1)$, using either the $\epsilon$-$\delta $ definition or some other method.
Comment: The quotient of two continuous functions is continuous as long as you stay away from the point where the denominator vanishes at. Thus...
Comment: oh is this a theorem? where can i find the proof of this theorem?
Comment: A simple proof can be found at https://proofwiki.org/wiki/Combination_Theorem_for_Continuous_Functions/Quotient_Rule
Answer: Let $c \in ]-1, 1[$. If $x \in ]-1,1[$, then
$$
\bigg| \frac{x}{(1-x)^{2}} - \frac{c}{(1-c)^{2}} \bigg| =
\frac{|x(1-c)^{2} - c(1-x)^{2}|}{(1-x)^{2}(1-c)^{2}} = \frac{|x-c||1-xc|}{(1-x)^{2}(1-c)^{2}};
$$
if in addition $|x-c| < 1$, then $|x|-|c| \leq |x-c| < 1$, implying $|x| < 1+|c|$, implying $|xc| < |c| + c^{2}$, implying $|1-xc| \leq |xc|+1 < |c|+c^{2}+1 =: M_{1,c}$, implying
$$
\frac{|x-c||1-xc|}{(1-x)^{2}(1-c)^{2}} < \frac{|x-c|M_{1,c}}{(1-x)^{2}(1-c)^{2}};
$$
if in addition $|x-c| < |c-1|/2$, then
$||x-1| - |c-1|| \leq |x-1-(c-1)| < |c-1|/2$, implying $|x-1| > |c-1|/2 =: M_{2,c}$, implying
$$
\frac{|x-c|M_{1,c}}{(1-x)^{2}(1-c)^{2}} < \frac{|x-c|M_{1,c}}{M^{2}_{2,c}(1-c)^{2}};
$$
given any $\varepsilon > 0$, we have
$$
\frac{|x-c|M_{1,c}}{M^{2}_{2,c}(1-c)^{2}} < \varepsilon
$$
if in addition we have
$|x-c| < \varepsilon M^{2}_{2,c}(1-c)^{2}/M_{1,c}$.
All in all, for every $c \in ]-1,1[$ and every $\varepsilon > 0$ it holds that $x \in ]-1,1[$ and $|x-c| < \min \{ 1, |c-1|/2, \varepsilon M^{2}_{2,c}(1-c)^{2}/M_{1,c} \}$ imply
$|f(x) - f(c)| < \varepsilon$.


Enabling SSL for Remote Desktop

Question: Ok so I'm trying to remove a number of my systems from our Nessus scan from having this medium vulnerability.
Microsoft Windows Remote Desktop Protocol Server Man-in-the-Middle Weakness
I set the following GPO setting:
Computer Configuration\Policies\Administrative Templates\Windows Components\Remote Desktop Services\Remote Desktop Session Host\Require Use of Specific Security Layer for Remote (RDP) Connections: SSL (TLS 1.0)
Once I do this my Windows 7 clients no longer have the Nessus problem however RDP no longer works from Linux or Windows clients.  I get the following errors:
From clients:
Linux:
[ryan@gobo ~]$ rdesktop -0 win7
Autoselected keyboard map en-us
ERROR: recv: Connection reset by peer

Windows:
"the connection cannot proceed becuase authentication is not enabled

One the server system (Windows 7 box running RDP):
Log Name:      System
Source:        TermDD
Date:          4/9/2012 4:28:58 PM
Event ID:      50
Task Category: None
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      gobo-vm
Description:
The RDP protocol component X.224 detected an error in the
protocol stream and has disconnected the client.

and this one:
Log Name:      System
Source:        Schannel
Date:          4/9/2012 4:07:54 PM
Event ID:      36870
Task Category: None
Level:         Error
Keywords:
User:          SYSTEM
Computer:      gobo-vm
Description:
A fatal error occurred when attempting to access the SSL server
credential private key. The error code returned from the
cryptographic module is 0x8009030d. The internal error state is
10001.

I've seen solutions on this being a permission problem with the cert, as in the Network Service account doesn't have permission to access it but I can't find where the cert is on the filesystem to check it.
Other than that I'm out of ideas/options.  I look for the wise here.
Answer: From TechNet:

A certificate is needed to authenticate an RD Session Host server when
  SSL (TLS 1.0) is used to secure communication between a client and an
  RD Session Host server during RDP connections. You can select a
  certificate that you have already installed on the RD Session Host
  server, or you can use the default self-signed certificate. You can
  enable SSL for Remote Desktop connections using the RDP-Tcp Properties
  dialog box, which is accessed from the Remote Desktop Session Host
  Configuration snap-in.
By default, Remote Desktop connections are encrypted at the highest
  level of security available (128-bit). However, some older versions of
  the Remote Desktop Connection client application do not support this
  high level of encryption. If a high level of encryption is needed to
  support legacy clients, the encryption level of the connection can be
  configured to send and receive data at the highest encryption level
  supported by the client.
There are four levels of encryption available:
Low Data sent from the client to the server is encrypted
  using 56-bit encryption. Data sent from the server to the client is
  not encrypted.
Client CompatibleEncrypts client/server communication at
  the maximum key strength supported by the client. Use this level when
  the terminal server is running in an environment containing mixed or
  legacy clients. This is the default encryption level.
HighEncrypts client/server communication using 128-bit
  encryption. Use this level when the clients accessing the terminal
  server also support 128-bit encryption. When encryption is set at this
  level, clients that do not support this level of encryption will not
  be able to connect.
FIPS CompliantAll client/server communication is
  encrypted and decrypted with the Federal Information Processing
  Standards (FIPS) encryption algorithms. FIPS 140-1 (1994) and its
  successor, FIPS 140-2 (2001), describe U.S. government requirements
  for encryption.
The RDP-Tcp Properties dialog box, which is accessed from the Remote
  Desktop Session Host Configuration snap-in, allows you to configure
  the encryption level.
Answer: I would recommend looking into your certificate setup. Have you purchased a third party SSL certificate? Or have you generated one from your RD server? Does it have a private key assigned, because it will need one.
It sounds like an issue with the certificate/private key. I would try add an 'import certificate to personal store' GPO rule inside of your RD host GPO and see if the RD host certificate is required for the client machines to connect. You have just forced SSL but have not installed/shown a trusted certificate.

Enabling SSL for Remote Desktop


Proving the Completeness of a Metric Space

Question: Let $C[0,1]$ represent the set of all continuous functions on $[0,1]$. Is the following subset of $C[0,1]$ complete with respect to the metric $\rho(f,g) = \sup_{x \in [0,1]}|f(x)-g(x)|$?
The subset in question is $$X = \{f \in C[0,1] |  f(x) > 1 \forall x \in [0,1]\}$$
I understand that to prove this we need to show that every Cauchy sequence converges to a limit in the metric space, but I am unsure how to do this.
Comment: You only need to check if it closed since every closed subset of a complete metric space is also complete.
Answer: It is not complete, since it is not closed. And it is not clolsed because, if you define $f_n\in C\bigl([0,1]\bigr)$ by $f_n(x)=1+\frac1n$, then $(f_n)_{n\in\mathbb N}$ converges in $C\bigl([0,1]\bigr)$ to the constant function $1$, which doesn't belong to $X$. However, each $f_n$ belongs to $X$.
Comment: Beat me to it. For OP: strict inequalities do not really play well with completeness. This is a very classic example where it doesn't.
Comment: I suppose what I am confused about is the set-up of the metric $sup|f(x)-g(x)|$. What if I wanted to prove that the subset of continuous functions on [0,1] where $\int_{0}^{1}f(x)dx=1$ is complete with respect to the metric?
Comment: @roc11111111 That set is complete because it is closed. And it is closed because the function $f\mapsto\int_0^1f(x)\,\mathrm dx$ is continuous with respect to your metric and because $\{1\}$ is a closed set.


Integrate $\frac{e^{itx}}{1-it}$

Question: I need this integral to find the probability density function from the characteristic function but I don't know how to find it, every method that I try fails. I tried integration by parts but I didn't get the result that I need to.
The integral is
$$\frac{1}{2\pi}\int_{-\infty}^{\infty}{\frac{e^{itx}}{1-it}dt}.$$
The result I need to get by my computations is $e^{-x}$, but I dont know how.
Comment: https://www.wolframalpha.com/input/?i=integrate+e%5E%7Bitx%7D%2F%281-it%29+dt+ Wolfram dies :P
Comment: i as in $\sqrt{-1}$, right?  Not some arbitrary constant?
Comment: yes it is imaginary i
Comment: The integral is divergent, but it can be interpreted as a Fourier transform of distribution.
Comment: $t \mapsto\frac{1}{1-it}$ is the characteristic function of the exponential distribution with rate 1. So, you could argue via the uniqueness of the characteristic functions, but that would be cheating of course.
Comment: I think you have a sign error on an $i$, in either the exponent or the denominator.
Answer: First we rewrite the expression and interpret it as a Fourier transform:
$$
\int_{-\infty}^{\infty} \frac{e^{itx}}{1-it} \, dt
= \int_{-\infty}^{\infty} \frac{1+it}{1+t^2} e^{itx} \, dt
= \mathcal{F}\left\{ \frac{1}{1+t^2} \right\} + \mathcal{F}\left\{\frac{-it}{1+t^2} \right\},
$$
where
$$
\mathcal{F}\{f(t)\} = \int_{-\infty}^{\infty} f(t) \, e^{-ixt} \, dt
$$
Then, according to rule 208,
$$
\mathcal{F}\{ e^{-|t|} \} = \frac{2}{1+x^2}
$$
so by the inversion theorem, rule 105,
$$
\mathcal{F}\left\{ \frac{2}{1+t^2} \right\} = 2\pi \, e^{-|x|}.
$$
Thus,
$$
\mathcal{F}\left\{ \frac{1}{1+t^2} \right\} = \pi \, e^{-|x|}.
$$
For the other term we use rule 107 giving
$$
\mathcal{F}\left\{ \frac{-it}{1+t^2} \right\}
= -i \mathcal{F}\left\{ t \frac{1}{1+t^2} \right\}
= -i \cdot i \left( \pi \, e^{-|x|} \right)' = -\pi \, \operatorname{sign}(x) e^{-|x|}.
$$
Thus,
$$
\int_{-\infty}^{\infty} \frac{e^{itx}}{1-it} \, dt
= \pi \, e^{-|x|} - \pi \, \operatorname{sign}(x) e^{-|x|}
= \pi \left( 1 - \operatorname{sign}(x) \right) e^{-|x|}
= \pi H(-x) e^{-|x|},
$$
where $H$ is the Heaviside function:
$$
H(x) = \begin{cases}
0, & (x<0) \\
1, & (x\geq 0)
\end{cases}
$$
Comment: Why is the second term $\mathcal{F}\left\{\frac{\color{blue}{-}it}{1+t^2}\right\}$?
Comment: @J.G. I have made a variable change $t \to -t$ because the Fourier transform uses $e^{-ixt},$ not $e^{ixt}.$
Comment: Ah, it comes down to your sign conventionin defining the FT. Thank you.
Answer: $$I_n=\frac 1{2\pi}\int_{-n}^n\frac{e^{itx}}{1-it}dt$$
now let $u=1-it$ $du=-idt\Rightarrow dt=idu$
$$I_n=i\int_{1+in}^{1-in}\frac{e^{(1-u)x}}{u}du=ie^x\int_{1+in}^{1-in}\frac{e^{-ux}}{u}du$$
now we will try and manipulate this integral a bit:
$$\int_{1+in}^{1-in}\frac{e^{-ux}}{u}=\Gamma(0,x(1-in))-\Gamma(0,x(1+in))$$
and your integral is this as $n\to\infty$ with the additional constants at the beginning. Notice that this is undefined/divergent and so we cannot properly express the answer although there way be other interpretations in terms of Fourier

Integrate $\frac{e^{itx}}{1-it}$


Como adicionar um popup com imagem ao acessar o site

Question: Gostaria de fazer um popup parecido com esse da Kabum, porém sem um formulário, só com uma imagem e a opção de fechar.
Procurei e achei esse código:

Clique para abrir a janela POP-up

Porém abre uma página nova e preciso que ele fique no mesmo site como o do exemplo da Kabum.
Answer: Não consegui visualizar o popup do kabum, mas pelo que entendi na sua pergunta você pretende fazer algo como:

var close = document.getElementById('close');
var popup = document.getElementById('popup');

close.addEventListener("click", function() {
  popup.style.display = 'none';
});
#popup {
  position: absolute;
  margin: 0 auto;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  box-shadow: 0px 0px 50px 2px #000;
  padding-bottom: 5px;
}
#close {
  width: 100px;
  background-color: #cc0033;
  color: #ffffff;
  border: none;
  margin-left: 5px;
}

    <button id="close">Sair</button>

Veja funcionando no jsfiddle


Plotting two different-sized hypotrochoids at once in same ring, at different starting positions.

Question: I wish to plot two hypotrochoids moving around a ring-gear in lock-step with respect to each other, with the second hypotrochoid's plotted position being dependent on the first hypotrochoid's parametric (t).
My implementation uses degrees, with 0˚ being cardinally north, 90˚, east.

x1= ((rb - r1) * sin (t)) + (d1 * sin((rb - r1) * t / r1))

y1= ((rb - r1) * cos (t)) - (d1 * cos((rb - r1) * t / r1))

I tried multiplying t by r1/r2 so the two gears would move around the ring at the same rate, and adding 180, but that didn't work well.  This was just a hopeful guess, as I'm quite over my head.

t2= (t * r1/r2) + 180

x2= ((rb - r2) * sin (t2)) + (d2 * sin((rb - r2) * t2 / r2))

y2= ((rb - r2) * cos (t2)) - (d2 * cos((rb - :2) * t2 / r2))

What do I have to do to t and/or the second calculations to plot x2 and y2 for a second hypotrochoid that starts at say, 180˚ (though it could be any offset, I'll be happy with 180˚) from the first, and keeps its relative position?
I'm using t as an index for an array of [x1,y1] and [x2,y2], as the actual plot I want is of a point on a line connecting position 1 to position 2 is a set distance away from position 1.  This is modelled on a physical drawing machine called an "Illumicon".  I have made an implementation without any trig at all in ACSLogo (don't judge :), so I know what results to expect if/when I get the trig right.
Here are some diagrams and some animations to help explain:

Double Hypotrochoid "gear" animation
non-trig implementation animation
Answer: After playing around with the formulae, I determined the virtual gears were already in lock-step for a given value of t, so my attempt at trying to compensate for the different circumferences was causing the unexpected results.
So to get a 180˚ offset, I just multiplied x2 and y2 by -1.  I should probably instead do something like add to t2 1/2 the periodicity of the x2 and y2 hypotrochoid.
Here are two plots of the points 75 units from (x1,y1) towards (-x2,-y2), for t = 1..33300, rb=300, r1=120, d1=60, r2=148, d2=140, the latter when I was modifying t2


Altering the height of a wellpanel in Shiny

Question: I have a nice wellpanel at the top of my Shiny viz that looks good:

...but I am getting annoyed at all the extra grey space above and below the actual controls!  I would like to remove this unnecessary space. My row is a good 50% taller than it needs to be, and I'm not sure why/how Shiny sized it this way.
Does anyone who has skills in css / html / Shiny be able to point me in the right direction, regarding how to modify this? My attempts thus far have been unsuccessful.
Here's the code below:
shinyUI(fluidPage(

  fluidRow(
    column(12,
           wellPanel(
             tags$div(class = "row",
                      tags$div(class = "span"),
                      tags$div(class = "span1", h1(numericInput(inputId="num", label="ID", value=NaN))),
                      tags$div(class = "span2", h1(sliderInput(inputId="age", "Age Range", min=32, max=99, value=c(32, 99), step=1))),
                      tags$div(class = "span1", h1(radioButtons(inputId="gender", "Gender", c("combined" = 0, "male" = 1, "female" = 2), inline=FALSE))),
                      tags$div(class = "span1", h1(textOutput("text")))
             )
           ))),

  fluidRow(

    column(4,
           plotOutput("some_plot_not_shown"))

)))

Thanks for reading this far.
Answer: You can alter the padding:
library(shiny)
runApp(
  list(ui = fluidPage(
    wellPanel(
    tags$div(class = "row",
             tags$div(class = "span"),
             tags$div(class = "span1", h1(numericInput(inputId="num", label="ID", value=NaN))),
             tags$div(class = "span2", h1(sliderInput(inputId="age", "Age Range", min=32, max=99, value=c(32, 99), step=1))),
             tags$div(class = "span1", h1(radioButtons(inputId="gender", "Gender", c("combined" = 0, "male" = 1, "female" = 2), inline=FALSE))),
             tags$div(class = "span1", h1(textOutput("text")))
    )
  , style = "padding: 5px;")
  , wellPanel(
    tags$div(class = "row",
             tags$div(class = "span"),
             tags$div(class = "span1", h1(numericInput(inputId="num1", label="ID", value=NaN))),
             tags$div(class = "span2", h1(sliderInput(inputId="age1", "Age Range", min=32, max=99, value=c(32, 99), step=1))),
             tags$div(class = "span1", h1(radioButtons(inputId="gender1", "Gender", c("combined" = 0, "male" = 1, "female" = 2), inline=FALSE))),
             tags$div(class = "span1", h1(textOutput("text1")))
    )
    , style = "padding: 45px;")
  )
       , server = function(input, output, session){

       }
       )
  )

Answer: I think you're trying to use spans when adding columns is really what you're after -- try this:
shinyUI(fluidPage(
  fluidRow(
    column(12,
      fluidRow(
        wellPanel(
          fluidRow(
            column(3, h1(numericInput(inputId="num", label="ID", value=NaN))),
            column(3, h1(sliderInput(inputId="age", "Age Range", min=32, max=99, value=c(32, 99), step=1))),
            column(3, h1(radioButtons(inputId="gender", "Gender", c("combined" = 0, "male" = 1, "female" = 2), inline=FALSE))),
            column(3, h1(textOutput("text")))
          )
        ) # End wellPanel
      )
    )
  ),
  fluidRow(
    column(4, plotOutput("some_plot_not_shown"))
  )
))


Bring text/line segments in Lilypond in the same vertical position

Question: I have many places in my Lilypond score where my line+text combination stand in different heights. I would like them to be in the same height. Here is an example:

I have defined these as:

dord = {\once \override TextSpanner.bound-details.right.text = # " ord "
        \once \override TextSpanner.bound-details.right.stencil-align-dir-y = #0
        \once\override Staff.TextSpanner.bound-details.right.arrow = ##t }
dspt = {\once \override TextSpanner.bound-details.right.text = # "  s.p. "
        \once \override TextSpanner.bound-details.right.stencil-align-dir-y = #0
        \once\override Staff.TextSpanner.bound-details.right.arrow = ##t }

How can I force them to stay on the same y-position?
Answer: Do you use \new Dynamics?  So for instance:
\new Staff { c''4 4 4 4 }
\new Dynamics { s4 s2.\p }
\new Staff { c'4 4 4 4 }

Comment: I don't see the relation of your answer to my question! In what way could using \new Dynamics solve my problem? Please elaborate more.
Comment: My answer should have probably been a comment, but @Elements in Space has given a good example.
Answer: To get dynamics or similar markup to appear at a constant vertical position, use a \new Dynamic block.  Fill this with spacer rests (s) of the right values to get the correct horizontal position.  And attach the dynamics/markup to these spacers.
Combine the dynamic block with the regular staff block in parallel (<< \new Dynamics {...} \new Staff {...} >>) .
(This is particularly useful for instruments like piano that have their dynamics centred between two staves.)
dspt = {
    \once\override Staff.TextSpanner.bound-details.right.text = #" s.p."
    \once\override Staff.TextSpanner.bound-details.right.arrow = ##t
}

dord = {
    \once\override Staff.TextSpanner.bound-details.right.text = #" ord"
    \once\override Staff.TextSpanner.bound-details.right.arrow = ##t
}

<<
     \new Dynamics {
        \dspt s1\startTextSpan |
        s4 s4\stopTextSpan \dord s2\startTextSpan |
        s2 s2\stopTextSpan |
    }
    \new Staff {
        r2 r4 e''8 8 |
        e''16 16 16 16 \repeat tremolo 8 {g''32} \repeat tremolo 16 {32} |
        \repeat tremolo 16 {32} c'''2 |
    }
>>


A metric similar to the metric of a revolution surface

Question: It is already known that for revolution surface in $\mathbb{R}^3$, with parametric function $\langle r(s)\cos \theta,r(s)\sin \theta , z(s)\rangle$ (here $s$ is the arc length parameter for the curve $\langle r(s),z(s) \rangle$, i.e. $r'(s)^2+z'(s)^2=1$), the metric $g=ds^2+r^2(s)d\theta^2$. If we consider the curve to be a straight line, that is $r(s)=as,z(s)=\sqrt{1-a^2}s$; then the metric will have the form $g=ds^2+a^2s^2d\theta^2$, with some $|a|\leq 1$. And for $|a|>1$, this kind of metric $g=ds^2+a^2s^2d\theta^2$ will no longer be the metric of some revolution surface. So is it possible to find some surface in $\mathbb{R}^3$, s.t. the metric of this surface is $g=ds^2+a^2s^2d\theta^2$, $|a|>1$?
Comment: Hi, I am really sorry that I made terrible typos in my question, now I have edited the problem.
Answer: This is really a local question. By letting $\varphi = c\theta$, with $c>|a|$, you reduce to the case of a (portion of a) cone, as before, with metric $ds^2+b^2s^2\,d\varphi^2$, with $0<b<1$.
Comment: Actually, to solve this problem, it will be very helpful if you could consider the Riemann surface in complex analysis.


Nginx request subset to different pool

Question: I have an nginx server with some requests that are slower and as such could saturate a PHP FPM pool.  I don't mind if these requests get dropped and also more importantly they don't affect the normal requests.
I thought that I could create another limited PHP-FPM pool for these requests and I have done this but am struggling with the nginx side of things.
My current config looks like...
location ~ \.php$ {
        include snippets/fastcgi-php.conf;

        # With php7.0-fpm:
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }

What I want to happen is that any request to certain explicit paths such as /test/update.php to go to another pool with the address of fastcgi_pass unix:/run/php/php7.0-fpm-secondary.sock;.
Is this possible?
Comment: Are you sure your question is written correctly? In your configuration all of the requests ending in .php will be processed to `fastcgi_pass unix:/run/php/php7.0-fpm.sock;`. That is, there is nothing wrong here.
Comment: Yes it is just a snippet of the config granted. And yes well spotted on the typo!
Answer: This might do what you are looking for, but it is not tested.
location ~ /test/update.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php7.0-fpm-secondary.sock;
}

Nginx request subset to different pool


How is adding noise to training data equivalent to regularization?

Question: I've noticed that some people argue that adding noise to training data equivalent to regularizing our predictor parameters. How is this the case?

Some of the examples listed on SE discussing this topic focus more on e.g. LSTMs and SVMs, but can we do this for simpler models like a multiple linear regression?

How will it affect our parameters' confidence intervals?

Will there be any differences in effects choosing between the various types of white noise, e.g. Gaussian vs uniform white noise?
Comment: Exactly how do you contemplating "adding noise"?  To which variables?
Comment: This is maybe an interesting paper on the topic https://arxiv.org/abs/1805.10939v1
Comment: You may be interested in https://en.wikipedia.org/wiki/Regression_dilution aka attenuation bias (see https://econ.lse.ac.uk/staff/spischke/ec524/Merr_new.pdf)
Comment: Related post, https://stats.stackexchange.com/questions/531241/tikhonov-regularization-equivalence-to-adding-random-noise?rq=1 a bit more involved mathematically though.
Answer: Adding noise to the regressors in the training data is similar to regularization because it leads to similar results to shrinkage.
The linear regression is an interesting example. Suppose $(Y_i,X_i)_{i=1}^n$ is a set of i.i.d. observations and that
$$ Y_i = \beta_0 + \beta_1X_i + U_i \qquad \mathbb{E}[U_i \mid X_i] = 0 $$
The population coefficient for $\beta_1$ is equal to
$$ \beta_1 = \frac{Cov(Y_i,X_i)}{Var(X_i)} $$
The estimated OLS coefficient $\hat{\beta}_1$ can be written as a sample analog of $\beta_1$. Now suppose that we add white noise $Z_i = X_i + \varepsilon_i$ and assume that $\mathbb{E}[\varepsilon_i] = 0$, $Var(\varepsilon_i) = \sigma^2$, and that that $\varepsilon_i$ is independent of $Y_i,X_i$. I have made no other assumption about the distribution of $\varepsilon_i$.
Then the population coefficient for a regression of $Y_i$ on $Z_i$ (the noisy regressor) is equal to,
$$ \tilde{\beta}_1 = \frac{Cov(Y_i,Z_i)}{Var(Z_i)} = \frac{Cov(Y_i,X_i + \varepsilon_i)}{Var(X_i + \varepsilon_i)} =  \frac{Cov(Y_i,X_i)}{Var(X_i) + \sigma^2} = \frac{Var(X_i)}{Var(X_i)+\sigma^2} \times \beta_1 $$
Therefore, $\tilde{\beta}_1$ shrinks to zero for higher values of $\sigma^2$. The estimator for $\tilde{\beta}_1$ will also shrink to zero. We can use the test data to choose a sequence $\sigma_n^2 \to 0$ that achieves the optimal bias-variance trade-off via cross-validation.
If you want to do inference, you clearly need to do some form of adjustment both because the estimator is biased and the variance depends on $\sigma^2$. The process for selecting $\sigma^2$ can also distort the confidence intervals.
Comment: In pictures: suppose your data is in form of a sequence of points along a continuous but nowhere smooth curve. If you add noise, the curve thickens and a possibility emerges to approximate with a smooth line staying inside that thickened curve.
Answer: Overview: For linear regression, I'll show that $\ell_2$ regularization (a.k.a. ridge regression) arises from minimizing the expected squared error over random perturbations of the regressors. The distributional form of the perturbations doesn't matter beyond some minimal requirements (i.i.d., zero mean). The variance of the perturbations controls the regularization strength.
Let  $\big\{(x_i, y_i)\big\}_{i=1}^n$ be the data, with regressors $x_i \in \mathbb{R}^d$ and responses $y_i \in \mathbb{R}$. Suppose we first add random noise to the regressors, then compute predictions as a linear function of the perturbed regressors:
$$\hat{y}_i = (x_i + \delta_i)^T w$$
$w \in \mathbb{R}^d$ are the regression coefficients and the perburbations $\{\delta_i\}$ are i.i.d. random vectors with mean $\vec{0}$ and covariance matrix $\lambda I$. It's not necessary to assume that perturbations are generated from any particular parametric family.
We seek coefficients that minimize the expected squared error $L(w)$, where the expectation is taken over the random perturbations:
$$L(w) = E \left[ \frac{1}{n} \sum_{i=1}^n (y_i - \hat{y}_i)^2 \right]$$
Plug in the above expression for $\hat{y}_i$ and expand:
$$L(w) = E \left[ \frac{1}{n} \sum_{i=1}^n
  (y_i - x_i^T w)^2
  - 2 \delta_i^T w (y_i - x_i^T w)
  + w^T \delta_i \delta_i^T w
\right]$$
By linearity of expectation:
$$L(w) = \frac{1}{n} \sum_{i=1}^n \left(
  (y_i - x_i^T w)^2
  - 2 E \Big[ \delta_i \Big]^T w (y_i - x_i^T w)
  + w^T E \Big[ \delta_i \delta_i^T \Big] w
\right)$$
Note that $E[\delta_i] = \vec{0}$ and $E[\delta_i \delta_i^T] = \lambda I$ are the mean and covariance matrix of the random perturbations:
$$L(w) = \frac{1}{n} \sum_{i=1}^n \left(
  (y_i - x_i^T w)^2
  + \lambda w^T w
\right)$$
Simplify, noting that $w^T w = \|w\|_2^2$:
$$L(w) = \frac{1}{n} \sum_{i=1}^n (y_i - x_i^T w)^2 + \lambda \|w\|_2^2$$
This is the mean squared prediction error for the original (non-perturbed) data, plus a penalty on the squared $\ell_2$ norm of the coefficients. Notice that it corresponds exactly to the cost function for ridge regression, with penalty strength $\lambda$.
Comment: How did you come to the result of E[δiδTi]=λI ? I mean how it can be a diagonal matrix ? Is it that expected covariance of different noise coming from same distribution = 0 ?Please elaborate or provide some links.
Comment: @GadaaDhaariGeek I began by *defining* each $\delta_i$ as a random vector with mean zero and covariance matrix $\lambda I$. Because $\delta_i$ has mean zero, $E[\delta_i \delta_i^T]$ is its covariance matrix, which is equal to $\lambda I$ by definition.
Comment: My question is, why the covariance matrix is a diagonal matrix ?
Comment: why do you compute the optimizer of the expected loss rather than compute the expectation of the optimized loss? That is, suppose we draw n noisy data $z_i = x_i + \delta_i$ and put them in an $n\times d$ matrix $Z = X + \Delta$ then solve for $w^* = \text{argmin}_w \lVert Zw - y\rVert$. This seems to describe a more practical scenario and would result in expected loss $E_\Delta[L(w^*)]$, compared to the loss you compute, $\text{min}_w E_\delta [L(w)]$. Or is it true that $E[L(w^*)] = \text{min}_w E[L(w)]$?
Comment: Okay, I think I got it. Since, the noise vectors  is independent and identically distributed, their covariance matrix will only have diagonal entries, which is in fact variance of their distribution and other entries as 0. Also, since they are identically distributed their variance is all same. Please, correct me if I am wrong.
Comment: @GadaaDhaariGeek Not quite. $\delta_i$ is a random vector representing the noise added to the $i$th point along each input dimension (each point has its own $\delta_i$). Defining the covariance matrix of $\delta_i$ as $\lambda I$ means the noise added to each dimension is uncorrelated, and has equal variance in all directions.
Answer: The basic concept behind regularization is that we start with our Bayesian prior for the coefficients being a decreasing function of the magnitude of the coefficient. That is, the Bayesian prior for the coefficient being large is smaller than the prior for the coefficient being small. If the basic loss function gives a large estimate for the coefficients, our final estimate is a balance between the Bayesian prior giving more weight to smaller estimates, and the data providing evidence for larger ones.
If the random noise corresponds to coefficients being $0$, then it will also pull our final estimates towards being smaller; our actual data saying the coefficients are large will have to compete with the random noise saying the coefficients are small. Another way of looking it is that if we add noise that is generated according our priors, then that will decrease the degree to which our data causes our final estimates of the coefficients to deviate from our priors. Both regularization and random noise are ways of increasing the effects of our priors on our final estimates.


Remove/delete each minimum value in each row of a NxM matrix?

Question: Is it possible to remove/delete each minimum value in each row of a NxM matrix
creating a new matrix?
I´ve tried this so far without any luck:
for n in range(0,len(matrix_name)):
    Ma = grades.remove(np.min(matrix_name[n,:]))

and this too:
for n in range(0,len(matrix_name)):
    Ma = np.delete(matrix_name,np.min(matrix_name[n,:]))

Comment: Do you want to remove exactly one value per row or all that equal the min val in that row? In the latter case, what format should the output have?
Comment: Is this a NumPy matrix? Have you tried anything yet?
Comment: Yes, it is a numpy matrix.
I´ve tried np.delete, matrix_name.remove and matrix_name[n>np.matrix_name]
Comment: @CEFOG We kind of need to know the answer to the above question in order to remove the right number of values.  Are you trying to drop all 0's from the gradebook or just one of the ones tied for the lowest?
Comment: There is only one minimum value in each row(sorry I should have mentioned that). So I just need to remove one value
Comment: @CEFOG [Please consider accepting whichever answer](https://stackoverflow.com/help/someone-answers) helped you the most.
Answer: If reconstructing the desired result from the original array instead of modifying the original array by deleting the min values, is allowed then this approach should do the job:
# some test array
In [19]: arr
Out[19]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])

In [20]: r, c = arr.shape

# find the minimum along axis 1 (i.e. along rows)
In [21]: min_vals = np.min(arr, axis=1, keepdims=True)

# reshape the result to 2D array
In [22]: (arr[np.where(arr != min_vals)]).reshape(r, c-1)
Out[22]:
array([[ 1,  2,  3],
       [ 5,  6,  7],
       [ 9, 10, 11],
       [13, 14, 15],
       [17, 18, 19]])

Note: This approach assumes that there's only one minimum value in each row.
Answer: If duplicates are not an issue or if deleting only one of them per row is acceptable:
m, n = a.shape
np.where(np.arange(n-1) < a.argmin(axis=1)[:, None], a[:, :-1], a[:, 1:])


Navbar bootstrap3 - how to change active item style

Question: I want to change style for active item. Instead of standard grey border

I want add some image like this.

Is there any way for this kind of modification?
Comment: Post your code mate
Answer: I'm not sure what your code looks like but you can do something like this
.navbar #nav > .active > a {
    color: red;
}

or  target the class or id however you want
Answer: Add CSS pseudo element ::before in active class.
You may adjust color and position. Sample code below.
a.nav-link.active::before {
    content: "";
    height: 2px;
    width: 10px;
    background: #000;
    left: 25px;
    position: absolute;
    top: 45px;
}


Strict mode error only in IE11. Can I take off strict mode just for this browser?

Question: I get the error `Assignment to read-only properties is not allowed in strict mode' on this line of my code:
wrapper.style = 'transition: transform 3s;';

This is a chunk of the function it's in:
'use strict';
function work() {
  var wrapper = document.getElementById( 'wrp' ),
  infoPage = document.getElementById( 'i-pg' ),
  body = document.getElementById( 'body' ),

  carA = document.getElementById( 'car-a' ),
  keyA = document.getElementById( 'key-a' ),
  manualA = document.getElementById( 'manual-a' ),
  wheelA = document.getElementById( 'wheel-a' );

  if( this.id === 'info' ) {
    wrapper.style = 'transition: transform 3s;'; //PROBLEM LINE
    wrapper.classList.add( 'up' );
    body.classList.add( 'dark' );
    infoPage.classList.remove( 'down' );
  }
}

This code works perfectly in all modern browsers i've tested. Only in IE11 is this breaking the entire site, stopping all subsequent lines from running.
If I take out the first line: 'use strict'; everything works fine.
Is there a simple fix while keeping strict mode on? Or just target IE11 and somehow remove strict mode for that browser?
There might be a better approach.
Comment: can you try this wrapper['style'] = 'transition: transform 3s;';
Answer: Why not fix it, instead of ignoring the error?
wrapper.style.transition = 'transform 3s;';

Comment: That's because most modern browsers [have a workaround built in](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style#Setting_style). Technically, the `style` property returns a [`CSSStyleDeclaration`](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration) and is read-only.
Comment: The way in my original code works in all modern browsers. However is my code at fault here or IE11?
Answer: I think you might get an errror cause you're trying to assign a transform 3s to style property, while actually you should assign it to a transition property.
Like this: wrapper.style.transition = 'transform 3s';
Answer: Checkout:
https://devtidbits.com/2016/06/12/assignment-to-read-only-properties-is-not-allowed-in-strict-mode/#comment-1611
Apparently you're supposed to use this something like
myEle.style.cssText = "color: red;" // or
myEle.setAttribute("class", "myClass"); // Multiple style properties
//For newly created style sheet objects, you must first append the element to the document before you can set cssText.

However I still get the same error even after applying that fix...


Module for OneSignal for Appcelerator

Question: Recently I found OneSignal platform we can send push notifications for free, their service is really complete. I'm trying to implement it on Appcelerator but I can't find any module for Appcelerator.
Did anyone already use their services on Appcelerator? How can I create a module for OneSignal for appcelerator I am a newbie with all of this :/
Answer: You can find guides on Appcelerator module development here:

Android_Module_Development_Guide
iOS_Module_Development_Guide

Module for OneSignal for Appcelerator


os.walk folder exclusion based on .txt file

Question: I would like to have a Folders_To_Skip.txt file with a list of directories separated by new lines
ex:
A:\\stuff\a\b\
A:\\junk\a\b\

I have files which are breaking my .csv record compiling that this is used for and I want to exclude directories which I have no use for reading anyway.
In the locate function I have what I tried to implement from Excluding directories in os.walk but I can't seem to get it to work with directories in a list let alone while reading from a text file list as when I print files accessed it still includes files in the directories I attempted to exclude.
Could you also explain whether the solution would be specific excluded directories (not the end of the world) or if it can be operated to exclude subdirectories (would be more convenient).
Right now the code preceding locate allows for easy lookup of controlling text files and then loading those items in as lists for the rest of the script to run, with the assumption that all control files are in the same location but  that location can change based on who is running the script and from where.
Also for testing purposes Drive_Locations.txt is setup as:
A
B

Here is the current script:
import os
from tkinter import filedialog
import fnmatch

input('Press Enter to select any file in writing directory or associated control files...')
fname = filedialog.askopenfilename()
fpath = os.path.split(fname)

# Set location for Drive Locations to scan
Disk_Locations = os.path.join(fpath[0], r'Drive_Locations.txt')
# Set location for Folders to ignore such as program files
Ignore = os.path.join(fpath[0], r'Folders_To_Skip.txt')

# Opens list of Drive Locations to be sampled
with open(Disk_Locations, 'r') as Drives:
    Drive = Drives.readlines()
    Drive = [x.replace('\n', '') for x in Drive]
# Iterable list for directories to be excluded
with open(Ignore, 'r') as SkipF1:
    Skip_Fld = SkipF1.readlines()
    Skip_Fld = [x.replace('\n', '') for x in Skip_Fld]

# Locates file in entire file tree from previously established parent directory.
def locate(pattern, root=os.curdir):
    for path, dirs, files in os.walk(os.path.abspath(root), topdown=True):
        dirs[:] = [d for d in dirs if d not in Skip_Fld]
        for filename in fnmatch.filter(files, pattern):
            yield os.path.join(path, filename)

for disk in Drive:
    # Formats Drive Location for acceptance
    disk = str.upper(disk)
    if str.find(disk, ':') < 0:
        disk = disk + ':'
    # Changes the current disk drive
    if os.path.exists(disk):
        os.chdir(disk)
    # If disk incorrect skip to next disk
    else:
        continue
    for exist_csv in locate('*.csv'):
        # Skip compiled record output files in search
            print(exist_csv)

Comment: Hi @tv006, welcome to the site. You've given us *a lot* of code here, and it's not entirely clear what you're asking about. It seems to me like the most obvious place to implement the filtering you seem to want would be in the `locate` function where you're doing the `os.walk` call (it can't work anywhere else), but you don't seem to be attempting to modify `dirs` at all. Can you cut out some of the irrelevant code from your example, and perhaps show us what you've actually attempted, with respect to the directory skipping?
Comment: You really need to extract and provide a [mcve]. As a new user, please also take the [tour] and read [ask]. In particular, saying "I tried something vaguely specified" followed by "it didn't work" is both not helpful. Provide facts, not interpretations.
Comment: Variable and function names should follow the `lower_case_with_underscores` style. The inconsistent naming and the sheer amount of code make this practically impossible to read.
Comment: I can also see a bunch of areas which could be simplified, notably at the beginning of the program, where you're reading all the files.
Comment: AMC - Unfortunately I can't think of a solution to cleanup the section for reading the files as I'm trying to set this up so coworkers could feasibly run this without any coding just check if they want to change the text files which is more user friendly in my opinion. The most I think that section could benefit from is some way to kill the `tk` window that pops up with the windows explorer search.
Comment: That's not at all related to your actual question, though. Reduce this to a [mre] and maybe ask a new question about `tk`, similarly reduced to the essential code for reasoning about the specific problem you are trying to solve.
Comment: tripleee - I was simply responding to AMC's comment. This in my opinion is ease of reproducibility any drive letter can be added to `Drive_Locations.txt` file and placed adjacent to `Folders_To_Skip.txt` having some .csv files in the drive letter file tree to search for and adding a directory to `Folders_To_Skip.txt` and see if it disappears from the print readout.
Answer: The central bug here is that os.walk() returns a list of relative directory names. So for example when you are in the directory A:\stuff\a, the directory you want to skip is simply listed as b, not as A:\stuff\a\b; and so of course your skip logic doesn't find anything to remove from the list of subdirectories in the current directory.
Here's a refactoring which examines the current directory directly instead.
for path, dirs, files in os.walk(os.path.abspath(root), topdown=True):
    if path not in Skip_Fld:
        for filename in fnmatch.filter(files, pattern):
            yield os.path.join(path, filename)

The abspath call is important to keep; good on you for including that in your attempt.
Your list of directories to skip should have single backslashes, or perhaps forward slashes, and probably no final directory separator (I fortunately have no way to check how these are reported by os.walk() on Windows).
Comment: I have not examined the rest of the script; there may be additional bugs.
Comment: I tried using it and modified it to use a for loop since I do want an iterable but I it doesn't seem to work. I'm wondering if it might be an issue with how python converts read paths into strings could be rendering the string inoperable. I tried running as many formatting options as I could think of on my paths to exclude but nothing seems to stick. I even considered that it required raising the path up one level but that doesn't seem to work either.
Comment: Rather that guess at the problem, add strategic `print` statements to show the values of your variables, and compare against what you expect.
Comment: That's the thing though, is that based on use of `print` statements a string of a path, when brought in as a list of strings the input =/= output. My assumption of the issue is that I add the equivalent of `path` in a list of strings and in the process of python reading `path` into as a string it becomes `path*` essentially if that makes sense. So therefore `Skip_Fld` will never contain `path` items as `path*` items are what are iterated. The only way I've solved this before was use of raw strings to handle file paths, but I don't know how I could implement that into building a list.
Comment: Again, if the script could be reduced to a [mre] and you could mention and perhaps even demonstrate this observation in your question, you'd be more likely to get help to reach a solution. The pesky GUI in particular obscures the problem because it's harder to know *exactly* how to reproduce your problem. Take out all moving parts so that only the problem remains.


Web Audio API - Removing filter

Question: I'm building a visualiser with multiple graphic modes. For a few of them I need to calculate the beat of the track being played, and as I understand I then need to apply a lowpass filter like the following, to enhance frequencies that are most probable to hold drum sounds:
var filter = context.createBiquadFilter();

source.connect(filter);
filter.connect(context.destination);

filter.type = 'lowpass';

But what if I want to turn the filter off? Do I have to re-connect the source every time I need to remove the filter? Would this have any negative effect on performance?
Related question: how much performance loss would I experience if I have two two sources, from the same audio source, and apply the filter to one of them?
Comment: I don't understand. Why can't you just connect your single audio source to the destination directly, _and_ to a filter which you then connect to whatever you use to determine bpm?
Comment: @JohnWhite My problem is that I want to switch between a visualiser that reacts to all frequencies, and one that just reacts to beats. Are you suggesting I always have two sources, and one is always connected to the filter?
Answer: According to article WebAudio intro | html5rocks, I would have to toggle the filter on and off, by disconnecting the source and itself like so:
  this.source.disconnect(0);
  this.filter.disconnect(0);
  // Check if we want to enable the filter.
  if (filterShouldBeEnabled) {
    // Connect through the filter.
    this.source.connect(this.filter);
    this.filter.connect(context.destination);
  } else {
    // Otherwise, connect directly.
    this.source.connect(context.destination);
  }

Comment: An alternative: Stick a gain node between the filter output and context.destination.  When you don't care about the filter output anymore, set the gain to 0.
Comment: I'm leaving my question open in case someone comes with a better solution.
Answer:
how much performance loss would I experience if I have two two sources, from the same audio source, and apply the filter to one of them

You can connect a single audio node to multiple destinations, thus you never need a duplicate source just to spread-connect it. If you need filtered and raw audio simultaneously, you can just setup your connections accordingly:
var filter = context.createBiquadFilter();

source.connect(filter);
source.connect(context.destination);
filter.connect(context.destination);

filter.type = "lowpass";

Anyways, setting the type property of a FilterNode to "allpass" will effectively disable all filtering, without having to reconnect:
filter.type = "allpass"

Comment: Thank you! I was thinking about all-pass, but according to MDN it "lets all frequencies through, but changes the phase-relationship between the various frequencies". I was afraid of the phase changes.

Web Audio API - Removing filter


Interpretation of the ratio of two estimated population means

Question: I have two datasets. Lets say average of 1st dataset is 10, and average of second dataset is 12. Is it acceptable to divide 12/10 and say that the relationship between both datasets is 1.2? I am interpreting 1.2 as, for one event in 1st dataset 1.2 events happen in 2nd dataset. Is this a correct interpretation?
Note: values of 1st dataset happen 1st. 2nd dataset is not dependent on the 1st one.
Comment: No, it is wrong. The ratio of two means is not the mean of paired ratios.
Comment: @Carl what would be the best way to pair both values so a relationship can be expressed as a single digit?
Comment: Well, if the situation is that one outcome could be paired with any outcome of a second population, then one method would be to randomly sample population one for an outcome with replacement, pair it with a random sample from population two with replacement, divide, and repeat that process 1000 times, then average the ratios. That is called `bootstrap`.
Comment: Bootstrap may or may not be what you need, depending on exactly what you want to do.
Comment: I was just hoping to understand if it would make sense to divide two averages and use division's product as a coefficient?
Answer: It depends on the context whether it is right. Your interpretation is ambiguous.

You would be right when you say that the population has from the one data-set 1.2 events for every event in the the other dataset.
Sidenote: You could still make this more precise by adding confidence intervals (How to compute the confidence interval of the ratio of two normal means).

You would be wrong when you use some paired data interpretation (for instance the data-sets relates to the same individuals) and you say that for every individual you have 1.2 events from the one dataset for every event in the other dataset (as in a linear relationship).

Example, of the contrast: Say the one dataset contains the number of times a person watches television (say 5 times per week) and the other dataset contains the number of times a person reads a book (say 1 time per week). Then you can say that the population watches 5 times more often television than reading books. But you can not say that an individual person watches 5 times television for every time it is reading a book (in fact it might be some negative correlation and a person is gonna watch less television for every time it is reading a book).
Sometimes the context may clearly indicate which of the two interpretations is used. For instance it is obviously a comparison on the population level when the two populations that relate to the two different datasets are different (such that no individual relates to both data-sets). An example: say the one dataset is the number of statisticians in a sample of a million inhabitants in the UK and the other dataset is the number of statisticians in a sample of a million inhabitants in the USA.
Answer: Suppose I have for a first group of numbers $\{2,4\}$ and for a second group $\{-2,2\}$ then the mean of the first group is $\frac{2+4}{2}=3$, and of the second group is $\frac{-2+2}{2}=0$. Then the ratio of the mean values is $\frac{3}{0}=?$. By convention some people call this $+\infty$.
Now there is another way to look at this. Suppose we wanted to see the mean of all possible fractions. Then we would construct the fractions that can be formed from the two groups: $\left\{\frac{2}{-2}, \frac{2}{2}, \frac{4}{-2}, \frac{4}{2}\right\}=\left\{\ -1, 1, -2, 2\right\}$, the mean of which is $\frac{-1+ 1 -2+ 2}{4}=\frac{0}{4}=0$.
Now am I pulling a fast one? OK, suppose I interchanged the groups then in the first case I would have gotten $\frac{0}{3}=0$, which is now a number (at least) and in the second case I would have gotten $\left\{\frac{-2}{2}, \frac{2}{2}, \frac{-2}{4}, \frac{2}{4}\right\}=\left\{\ -1, 1, -\frac{1}{2}, \frac{1}{2}\right\}$, the mean of which is $0$, and no different from the prior mean of all possible fractions.
Now which of these answers is suspect $\{+\infty,0,0,0\}$? Well, obviously the first answer is suspect, but it may be correct, that depends. Making fractions and finding mean values are not commutative operations, that is, the fraction of two mean values is not the same as the mean value of many fractions, and it is generally, but not always, more consistent to do the latter.
It is unclear what pairing of numbers to make fractions is implied by the question. For example, if I were handing out right shoes of different sizes to individuals regardless of their right foot lengths, then there would be one shoe size for each foot length, i.e., only $n$ fractions for $n$ shoes and $n$ people.
In the numerical example I gave, I had two groups of sizes $n$ and $m$, where in my case both $n$ and $m$ were equal to two, but in general that would make for $n\times m$ fractions. There are still other possibilities, but whatever the case is we cannot work backwards from the ratio of two mean values to even venture a guess. Taking an average erases any knowledge of what $n$ (or $m$) might have been, or whether $n$ or $m$ were taken with replacement or without replacement. For example, if I want to calculate my odds of winning by counting cards in a poker game with some cards showing on the table, I am doing so without replacement, that is, if a card is showing, it isn't available elsewhere. Nevertheless, after a night of poker, it is perfectly fair to say that if I am up by $\$2$, that would have been the terminal running average of my winnings, and if Jack only had $\$1$ for his winnings then I can say without fear of contradiction that I won twice what Jack did. So taking a ratio of average values is not necessarily incorrect. It is the meaning that is different for different calculations having different answers.


Perl hash argument in use Module

Question: Some Perl modules are imported with hash argument, like:
use Test::Simple tests => 1

which is not consistent with documented use usage variants:

use Module VERSION LIST
use Module VERSION
use Module LIST
use Module
use VERSION

Imports some semantics into the current package from the named module, generally by aliasing certain subroutine or variable names into your package.

while in our case, we are using hash instead of list, at least semantically - of course,
use Test::Simple qw(tests 1)

is equivalent, but makes no sense for the human outsider, who is expecting the list to be a list of names to import.
How do you explain/defend this deviation? Is it the recommended syntactic sugar to allow a module to be imported with parameters?
Answer: perlop

The => operator is a synonym for the comma except that it causes a
word on its left to be interpreted as a string if it begins with a
letter or underscore and is composed only of letters, digits and
underscores. This includes operands that might otherwise be
interpreted as operators, constants, single number v-strings or
function calls. If in doubt about this behavior, the left operand can
be quoted explicitly.
Otherwise, the => operator behaves exactly as the comma operator or
list argument separator, according to context.

So it's use Module LIST syntax
Comment: @mykhal, if you know it, I don't understand what is the question. `tests => 1` = `'test', 1` = `qw(test 1)`.
Comment: it's just equivalent to `require Module; Module->import( 'test', 1 );` You are free fo define any `import` sub. it can even do no import at all
Comment: it should be obvious from the question text that the questioner knows that, and the question is higher-level..
Comment: Suic: would you import an integer literal from a module?
Answer: First, you should reread the documentation you quoted.
Imports some semantics into the current package from the named module, generally by aliasing certain subroutine or variable names into your package.
It's not just for importing a list of subs.

How do you explain/defend this deviation?

You mentioned three deviations.

The belief that => indicates a hash.
This stems from the misconception that there's such a thing as a hash initializer. Explain that Perl doesn't have initializers, that = denotes an ordinary assignment even when the LHS of it is %hash or my %hash. Hashes and arrays are types of variables, not data.
The belief that the list passed to use Test::Simple is a list of symbols to import.
I'm not sure how that's a problem. You can refer them to Test::Simple's documentation if it is.
The belief that the list passed to use MODULE is a list of symbols to import.
There are plenty of counter examples, including commonly used core modules strict, warnings, CGI, CGI::Carp and Test::More.

None of the deviations should be defended. These aren't useful metaphors.
Comment: worth emphasizing whenever the confusion in 1. arises: "hash" and "array" are *variable* types, not *data* types.  and there is no variable here.
Answer: As you have stated, this falls under the use Module LIST category.
I think the key to understanding how to interpret the use for LIST is to realize that use Module LIST; translates to the following line:
BEGIN { require Module; Module->import( LIST ); }

The module appears to treat the LIST as elements to populate a hash because the relevant package has a custom import subroutine:
sub import {
    my($class) = shift;

    # Don't run all this when loading ourself.
    return 1 if $class eq 'Test::Builder::Module';

    my $test = $class->builder;

    my $caller = caller;

    $test->exported_to($caller);

    $class->import_extra( \@_ );
    my(@imports) = $class->_strip_imports( \@_ );

    $test->plan(@_);

    $class->export_to_level( 1, $class, @imports );
}

Test::More also utilizes this "pattern".
Comment: the question is yet higher-level (i'd say philosophical). focus on "Imports some semantics into the current package from the named module, generally by aliasing certain subroutine or variable names into your package."
Answer: ikegami does an excellent job answering "How do you explain/defend this deviation?" (that is, there is no deviation here).
To answer: "Is it the recommended syntactic sugar to allow a module to be imported with parameters?"
No, a general purpose module should usually avoid doing this, at least for configuration settings, because it encourages a design of global variables in the module controlling functionality.  And that means two independent other modules cannot use the module in question with different configuration.  An example of this misuse is Math::BigInt (and friends).
The Test modules are a special case; they are only likely to be used by a main script (or as a superclass of a module used in a main script), so my objection doesn't apply.
(Certainly a module could go to the trouble of making whatever is passed to import have pragma-like lexical scope or be bound to a particular calling package, but those two options are slightly different in effect and you create the possibility of erroneous expectations in the cases where they differ, as well as making it difficult for the same caller to use multiple configurations.)
In almost every case, it would be far better to support an OO interface and have such settings be instance attributes.
Answer: Using this form use Test::Simple tests => 1 is normal way for Perl as the symbol => is the same as comma operator ,. So it is not syntactic sugar that's just another way to do something. TIMTOWTDI

Perl hash argument in use Module


Determining best path for lighting up my bookshelf

Question: I'm having an issue determining the best pathway. I have a bookshelf custom-made and here's a photo of it:
And here are the measurements of the same bookshelf. Other than the topmost rectangle which has a height of 42cm, the rest of them are equal and smaller i.e. 35.5cm. The width of all rectangles is the same i.e. 55cm and the extra non-rectangle one-side open portion is 25cm thus the total width of the shelf is 80cm.
I purchased 10m USB-based string light (which has a USB port on one end and is just a linear piece of wire with bulbs on it) and this is supposed to go along the front rims of the shelf (cannot go inside as books are placed) starting from ORIGIN point (marked in red) which is where its power source is. I intend to tape over it so that when I switch it on, the shelf lights up beautifully. I'm trying to find the best path to take to cover the entirety of the bookshelf. I do not see a single straight pathway and so overlapping is unavoidable. However, since it is unavoidable I would like to overlap the main rectangles if possible to maximize the bulbs and give the bookshelf the best overall appearance. How can I determine the best pathway for this structure? Thanks.
Answer: You have a total of $6 \times 80$ horizontal cm and $2 \times 182$ vertical cm for a total of $444$ cm. That's less than half the $10$ m of light strip.
That suggests to me that you should just start at the outlet and follow the edges until they are all doubled. That's mathematically possible. It's a little tricky but a nice puzzle. You should be able to figure out a way to do it.
Comment: @Aplateofmomos Yes, with an argument that shows that it is not as hard as the OP first imagined. There is no need to optimize the doubled part, and the assertion that it is possible to double everything.  They can ask for more detail if necessary, but figuring it out might be fun.
Comment: So ultimately your answer to OP is to tell them to figure it out themself.


Running a command from apache user as ec2-user

Question: I'm trying to run the following command
/usr/bin/ocr 1.pdf 1.xml

from Apache, but unfortunately this command only works with ec2-user. So I've tried to edit my PHP file to make it run like that:
/usr/bin/sudo -u ec2-user /usr/bin/ocr 1.pdf 1.xml

But I got the following error:
sudo: no tty present and no askpass program specified

So I've added the following line to /etc/sudoers
apache ALL=(ALL) NOPASSWD: /usr/bin/sudo -u ec2-user /usr/bin/ocr

But I still have the same error.
The only thing that worked was:
apache ALL=(ALL) NOPASSWD: ALL

But if I'm right, it allows apache to run any command with sudo, so it's a major security breach.
Do you have any idea of how I could do this in a clean way?
Answer: Simply do this:
apache ALL=(ec2-user) NOPASSWD: /usr/bin/ocr


sum em duas tabelas numa única consulta

Question: Tenha duas consultas, uma em cada tabela.
select SUM(quantidade) as total1 FROM tbmateria GROUP by codigomateria
select SUM(quantidade) as total2 FROM tbmateriaestoque GROUP by codigomateria

preciso fazer (total2 - total1), mas tem que ser uma única query.
tentei fazer assim, mas sem sucesso
SELECT
(SUM(tbmateria.quantidade) - SUM(tbmateriaestoque.quantidade)) as soma4,tbmateria.nomemateria

FROM
    tbmateria
INNER JOIN tbmateriaestoque ON(tbmateria.codigomateria = tbmateriaestoque.codigomateria)
GROUP BY
    tbmateria.codigomateria
Comment: veja se isso responde sua pergunta: https://pt.stackoverflow.com/q/454569/57220
Comment: O que você quer dizer com "sem sucesso"? Deu erro? O resultado não foi o esperado?
Comment: os cálculos estão errados. aparece um números muito altos, por ex: 1537406.250
Answer: Olá,
Veja se resolve, mas tem alguns problemas de validação ainda! Se não existir o resgitro do codigomateria nas 2 tabelas!
SELECT

t.codigomateria,
(
(SELECT SUM(tte.quantidade) FROM tbmateriaestoque tte WHERE tte.codigomateria = t.codigomateria GROUP BY tte.codigomateria)
-
(SELECT SUM(tt.quantidade) FROM tbmateria tt WHERE tt.codigomateria = t.codigomateria  GROUP BY tt.codigomateria)
) AS diferenca

FROM tbmateria t
JOIN tbmateriaestoque te ON (t.codigomateria = te.codigomateria)
GROUP BY t.codigomateria

Neste caso, iria fazer trazer todos codigos... para filtrar, adicione um WHERE no final!
Não consegui testar... mas acho que vai dar certo!
Comment: Perfeito duda, só precisei colocar GROUP BY t.codigomateria no final. muito obrigado.
Comment: Acho que isso seria necessário se t.codigomateria não for UNIQUEKEY... mas beleza, vou atualizar a resposta!

sum em duas tabelas numa única consulta


Is it possible to compute trasnformation matrix $T$ knowing $P$ and $C$ in $T^T·P^T·P·T = C^T·C$?

Question: It's probably dumb question, but I haven't used matrices for very long time and I really need that one.
I have two $3\times 3$ matrices $P$ and $C$, which have positive determinants and unknown transformation matrix T.
$$ T^TP^TPT = C^TC $$
Is there a way to compute $T$?
Answer: In general, the answer is no, since there can be many such $T$ that satisfy that equation. For instance, if $P = C = I$, then $T$ can be any orthogonal matrix, so there's no way to know which one without more information.
If you need to find all such $T$, multiply by $C^{-T}$ on the left and $C^T$ on the right. The equation becomes $$ C^{-T}T^TP^T PTC^{-1} = (PTC^{-1})^T(PTC^{-1}) =  I $$
In this case take $Q$ to be any orthogonal matrix, and simply take $$ PTC^{-1} = Q$$ so that we have $$ T = P^{-1}QC $$
If you just need one such, $T$, the simplest case is that $Q = I$, whence $$ T = P^{-1}C $$ gives a solution.
Comment: Thank you Cade. Actually I came up with the same equation (T=P^-1C) and it's not working for my test case. One can always hope.


Is it possible to add inline css styling to a twig email template?

Question: Is it possible to add inline css styling to a twig email template? Not as a source file reference but by inclusion of css within the template similar to html functionality.
Answer: For HTML emails, you have to use the inline style attribute.
The Mimemail module might be able to inline your external CSS.


how to show listbox string to another listbox

Question: Public Class frmAppliances
    Private Sub frmAppliances_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        lstApp.Items.Add(New Product("Electric fan", 500.0))
        lstApp.Items.Add(New Product("Refrigerator", 9000.0))
        lstApp.Items.Add(New Product("Washing Machine", 4000.0))
        lstApp.Items.Add(New Product("Oven Toaster", 550.0))
        lstApp.Items.Add(New Product("Flat Iron", 350.0))
        lstApp.Items.Add(New Product("VCD Player", 1200.0))
        lstApp.Items.Add(New Product("Mini Component", 3500.0))
        lstApp.Items.Add(New Product("Television", 5000.0))
        lstApp.Items.Add(New Product("Air Conditioner", 10000.0))
        lstApp.Items.Add(New Product("Rice Cooker", 600.0))
        lstApp.Items.Add(New Product("Electric Stove", 1000.0))
        lstApp.Items.Add(New Product("Electric Pot", 800.0))
        lstApp.Items.Add(New Product("Karaoke", 2500.0))
        lstApp.Items.Add(New Product("Microwave Oven", 3000.0))
    End Sub

    Private Sub lstApp_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstApp.SelectedIndexChanged
        Dim prc As Double = CType(lstApp.SelectedItem, Product).Price
        lstPrice.Items.Add(prc)
        Dim parts As String = lstApp.Items.ToString()
        lstSold.Items.Add(parts)

    End Sub

    Public Class Product
        Public Name As String
        Public Price As Double

        Public Sub New(ByVal pName As String, ByVal pPrice As Double)
            Name = pName
            Price = pPrice
        End Sub

        Public Overrides Function ToString() As String
            Return Name
        End Function
    End Class

It says windows system form objection in the listbox that I want to show, the other listbox is for the price.
Comment: *"It says windows system form objection in the listbox"*. No it doesn't. In this case, we can work out what it actually says but that may not always be the case so please provide the actual information rather than a vague approximation.
Answer: The issue is here:
Dim parts As String = lstApp.Items.ToString()

The Items property is a collectiion of all the items in the ListBox so why would you think that displaying a String representation of that would be of use here? Like the vast majority of types, its ToString method simply returns the name of the type. You already know how to get a value from the selected item because you're doing iit for the Price, so why would you think that doing it for the Name would be any different?
Dim selectedProduct = DirectCast(lstApp.SelectedItem, Product)
Dim price = selectedProduct.Price
Dim name = selectedProduct.Name
lstPrice.Items.Add(price)
lstSold.Items.Add(name)

That said, you're going about this in the wrong way altogether. Firstly, you should pretty much ALWAYS use properties rather than field:
Public Class Product
    Public Property Name As String
    Public Property Price As Double

    Public Sub New(name As String, price As Double)
        Me.Name = name
        me.Price = price
    End Sub

    Public Overrides Function ToString() As String
        Return Name
    End Function
End Class

Next, you should be creating a list of Product objects and binding that to the control:

Dim products = {New Product("Electric fan", 500.0),
                New Product("Refrigerator", 9000.0),
                New Product("Washing Machine", 4000.0),
                New Product("Oven Toaster", 550.0),
                New Product("Flat Iron", 350.0),
                New Product("VCD Player", 1200.0),
                New Product("Mini Component", 3500.0),
                New Product("Television", 5000.0),
                New Product("Air Conditioner", 10000.0),
                New Product("Rice Cooker", 600.0))
                New Product("Electric Stove", 1000.0),
                New Product("Electric Pot", 800.0),
                New Product("Karaoke", 2500.0),
                New Product("Microwave Oven", 3000.0)}

With lstApp
    .DisplayMember = "Name"
    .ValueMember = "Price"
    .DataSource = products
End With

Note that data-binding requires properties. Finally, you can get the Name and Price of the selected Product like so:
lstSold.Items.Add(lstApp.Text)
lstPrice.Items.Add(CDbl(lstApp.SelectedValue))

You should pretty much always use data-binding if it is an option.


What regex (if any) could be used to remove query strings in WordPress?

Question: On my WordPress site, with Google and Facebook adding query strings like ?GCLID=34o8u343 or ?FBCLID=2o38u3ljlkj, it breaks my redirects. Like:
Old Url: website.com/old-url
Redirects to New Url: website.com/new-url
When Facebook sends someone over, it's website/old-url?fbclid=9283u4938u4 or whatever.
Is there regex that can simply strip off everything starting with ? so the redirects continue to work?
Comment: Show us what you've tried.
Answer: As the query string starts from the first question mark in the URL, you can use the following:
^(.*?)\?.*$
^ start of the line
(.*?) group containing all characters (lazy-expansion)
\? up to the first question mark
.* any characters
$ end of the line
You can see it in action on regex101.com here with the URL you provided.
Comment: Excellent. How would I throw this in a regex redirect in WordPress? As in:

Regular Expression = ?
and
URL = ?
Comment: You asked for the regex, you got the regex. I don't know how to apply them in WordPress, sorry.


Add a custom property to HTML element via Javascript

Question: I am trying to add a custom element to Select html element.
 var sel=document.getElementById("sel1");
  sel.setAttribute("customprop","blabla");

In chrome it works, in IE8 it doesn't.
NO JQUERY
Comment: You mean custom _attribute_ (not _element_), right? Anyway, what are you trying to do with that?
Comment: Maybe you should try to use a `jQuery.attr('name', 'value')`? Provided that you use jQuery.
Comment: It should work: http://msdn.microsoft.com/en-us/library/ie/ms536739(v=vs.85).aspx. Is `sel` non-null?
Comment: @Paul Draper, no jquery
Comment: @yuris, you mean WojciechFrącz, no jquery?
Comment: Works well even in IE5 Quirks mode on IE 10, so it is hard to believe that it would not work on IE 8. Please provide sufficient code to actually demonstrate the problem and specify how you infer from the results that it does not work on IE 8.
Comment: Adding custom attributes violates HTML specifications. And it would be more natural to add a custom *property*, simply by an assignment like `sel.customprop = 'blabla'`.
Comment: Jukka K. Korpela, sel.customprop = 'blabla' didn't work neither in chrome or IE (i don't see it in View Source).
Comment: Just because it doesn't appear in the source in the IE Dev tools doesn't mean its not there. Have you tried setting it, then getting it? `elem.setAttribute('name','value')` then `console.log(elem.attributes)` to see if it's there? Also, when JS changes HTML elements in IE dev tools, you have to press the dev tools 'reload' button to refresh the source code to show any modifications.
Answer: Check the question: Replace setAttribute with IE compatible script
It seems you need to add doctype on top of your page:
<!DOCTYPE html>

and then the following tag inside your head element to make setAttribute work:
<meta http-equiv="X-UA-Compatible" content="IE=edge" />


Como consumir uma API através do Flutter?

Question: Não estou conseguindo listar os objetos que estão vindo da minha API back-end num aplicativo flutter. Ele não gerar erros ele simplesmente não carrega. Eu sou novo como desenvolvedor flutter e preciso de ajuda.
Esse é meu endPoint que carrega meu objeto.

localhost:8080/discipulos

Essa é minha lista
{
    "content": [
        {
            "codigo": 1,
            "nome": "Wladimir",
            "logradouro": "Rua das tantas",
            "telefone": "(11)93434-2413",
            "dataNascimento": "2017-02-10",
            "origem": "Convite",
            "tipo_interesse": {
                "codigo": 1,
                "modelo": "NIVEL_A",
                "descricao": "Frequenta a igreja e não há impedimento para ser batizado"
            },
            "tipo_atendimento": {
                "codigo": 1,
                "modelo": "ATENDIMENTO_1",
                "descricao": "Pequeno Grupo"
            },
            "discipulador": {
                "codigo": 1,
                "nome": "Flávia",
                "ocupacao": {
                    "codigo": 1,
                    "nome": "Membro"
                }
            }
        },
        {
            "codigo": 2,
            "nome": "Paulo da cunha",
            "logradouro": "Rua das tantasjdscnsdnjkjdsnkfjnsd",
            "telefone": "(51)93434-2413",
            "dataNascimento": "2017-02-10",
            "origem": "Convite",
            "tipo_interesse": {
                "codigo": 1,
                "modelo": "NIVEL_A",
                "descricao": "Frequenta a igreja e não há impedimento para ser batizado"
            },
            "tipo_atendimento": {
                "codigo": 1,
                "modelo": "ATENDIMENTO_1",
                "descricao": "Pequeno Grupo"
            },
            "discipulador": {
                "codigo": 1,
                "nome": "Flávia",
                "ocupacao": {
                    "codigo": 1,
                    "nome": "Membro"
                }
            }
        },
        {
            "codigo": 3,
            "nome": "Marcelo Das tantas",
            "logradouro": "Rua das tantasjcnsdkjncdskjncsdk",
            "telefone": "(81)93434-2413",
            "dataNascimento": "2017-02-10",
            "origem": "Convite",
            "tipo_interesse": {
                "codigo": 1,
                "modelo": "NIVEL_A",
                "descricao": "Frequenta a igreja e não há impedimento para ser batizado"
            },
            "tipo_atendimento": {
                "codigo": 1,
                "modelo": "ATENDIMENTO_1",
                "descricao": "Pequeno Grupo"
            },
            "discipulador": {
                "codigo": 1,
                "nome": "Flávia",
                "ocupacao": {
                    "codigo": 1,
                    "nome": "Membro"
                }
            }
        }
    ],
    "pageable": {
        "sort": {
            "empty": true,
            "sorted": false,
            "unsorted": true
        },
        "offset": 0,
        "pageSize": 20,
        "pageNumber": 0,
        "paged": true,
        "unpaged": false
    },
    "last": true,
    "totalElements": 3,
    "totalPages": 1,
    "size": 20,
    "number": 0,
    "sort": {
        "empty": true,
        "sorted": false,
        "unsorted": true
    },
    "first": true,
    "numberOfElements": 3,
    "empty": false
}

No meu aplicativo flutter está assim;
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:interessado/components/DiscipulosWidget.dart';
import 'package:http/http.dart' as http;
import 'package:interessado/models/discipulo.dart';

class DiscipuloOverView extends StatelessWidget {

  final _baseURL = 'localhost:8080/discipulos'; /* >>>> aqui é o EnPoint*/

  const DiscipuloOverView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    final List<Discipulo> discipulos = []; /* >>>> aqui iniciando a lista*/

    Future<void> loadDiscipulos() async{
      /* >>>> Esse é um método que precisa ser chamado, porém não sei como fazer ele ser chamado*/
      /* >>>> Eu não sei se este método está certo*/
      final response = await http.get(Uri.parse(_baseURL));
      Map<String, dynamic> data = jsonDecode(response.body);
      data.forEach((discipulosId, discipulos) {
        Discipulo(
          codigo: discipulos['codigo'],
          nome: discipulos['nome'],
          dataNascimento: discipulos['dataNascimento'],
          logradouro: discipulos['logradouro'],
          origem: discipulos['origem'],
          telefone: discipulos['telefone'],
        );
      });
    }

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.teal,
        title: Text('Lista de Discipulos'),
      ),
      body: ListView.builder(
        /* >>>> Ele precisa ser carregado aqui*/
        itemCount: discipulos.length,
      itemBuilder: (ctx, i) => DiscipulosWidget(discipulo: discipulos[i]),
      )
    );
  }
}

Comment: Não vi o import do `import 'dart:convert';` para ser usado para ler o json que seria `json.decode(response.body)`
Comment: https://docs.flutter.dev/cookbook/networking/fetch-data#5-display-the-data
Answer: Vamos lá, fiz algumas alterações no código e vou te explicar melhor.
Como você precisa construir o widget com informações que vem da API, você pode utilizar o FutureBuilder que vai esperar a future resolver e com o resultado dela montar o widget.
Corrigi alguns pontos no seu código:

Você estava fazendo a chamada para a API dentro do builder e isso não é nada interessante pois o builder vai executar toda vez que o flutter identificar que precisa fazer o rebuild do mesmo (seja por um setState ou por algum retorno da sua API. No seu código poderia acontecer do build executar novamente após o a future do http.get resolver);

Seu método de chamada estava praticamente pronto, o que faltava era adicionar os discípulos no array e retorná-lo;

Como explicado anteriormente, para poder montar o widget com o dado da API, utilizei um FutureBuilder que vai aguardar o retorno da API e, com o dado, montar o widget;

Utilizando o !snapshot.hasData eu verifico se há dado, caso não, retorno um loading no centro, mesmo caso do snapshot.hasError. Se houver erro, retorna um text no centro da tela com a mensagem de erro;

Com o dado pronto (quando o snapshot.hasData for true), verifica se o array de discípulos não está nulo ou não está vazio (sempre verifico se está nulo pois já tive problemas com isso), retorna um ListView.builder com o dado, caso não, retorna um text no centro avisando que não há discípulos.

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
//import 'package:interessado/models/discipulo.dart';

class Discipulo {
  final String? codigo;
  final String? nome;
  final String? dataNascimento;
  final String? logradouro;
  final String? origem;
  final String? telefone;

  Discipulo(
      {this.codigo,
      this.nome,
      this.dataNascimento,
      this.logradouro,
      this.origem,
      this.telefone});
}

class DiscipuloOverView extends StatelessWidget {
  final _baseURL = 'localhost:8080/discipulos'; /* >>>> aqui é o EnPoint*/

  const DiscipuloOverView({Key? key}) : super(key: key);

  Future<List<Discipulo>> loadDiscipulos() async {
    List<Discipulo> discipulos = []; /* >>>> aqui iniciando a lista*/
    /* >>>> Esse é um método que precisa ser chamado, porém não sei como fazer ele ser chamado*/
    /* >>>> Eu não sei se este método está certo*/
    final response = await http.get(Uri.parse(_baseURL));
    Map<String, dynamic> data = jsonDecode(response.body);
    if (response.statusCode == 200) {
      data.forEach((discipulosId, discipulos) {
        discipulos.add(
          Discipulo(
            codigo: discipulos['codigo'],
            nome: discipulos['nome'],
            dataNascimento: discipulos['dataNascimento'],
            logradouro: discipulos['logradouro'],
            origem: discipulos['origem'],
            telefone: discipulos['telefone'],
          ),
        );
      });

      return discipulos;
    }
    return [];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.teal,
        title: const Text('Lista de Discipulos'),
      ),
      body: Column(
        children: [
          Expanded(
            child: FutureBuilder<List<Discipulo>>(
              future: loadDiscipulos(),
              builder: (context, snapshot) {
                if (snapshot.hasError) {
                  return Center(
                    child: Text(
                      snapshot.error.toString(),
                    ),
                  );
                }

                if (!snapshot.hasData) {
                  return const Center(
                    child: CircularProgressIndicator(),
                  );
                }

                List<Discipulo>? discipulos = snapshot.data;

                return discipulos != null && discipulos.isNotEmpty
                    ? ListView.builder(
                        itemCount: discipulos.length,
                        itemBuilder: (_, i) {
                          return Text(discipulos[i].nome!);
                        },
                      )
                    : const Center(
                        child: Text('Ops, sem discipulos'),
                      );
              },
            ),
          ),
        ],
      ),
    );
  }
}


react native: importing a file with dynamic filename

Question: In React Native:
I would like to import a file using require at runtime.
e.g.
let mydata = require('../data/' + new Date().getFullYear().toString() + '.json');
Since I have more than a couple hundred json files it is not feasible to hard code all the files.
in angular you can just use the above code and it works, but I think RN requires a static path. I am hoping there is an alternative way to do it.
any help appreciated!!!
Answer: This is one of the problems i have encountered. As i have heard of, react's require()only uses static url not variables, that means that you have to do require('/path/file'). Here is my version of solution:
const images = {
    profile: {
        profile: require('./profile/profile.png'),
        comments: require('./profile/comments.png'),
    },
    image1: require('./image1.jpg'),
    image2: require('./image2.jpg'),
};
export default images;

not the best option, but you can get away with it sometimes.
Comment: thank you, but that solution is not going to work for me, coz i have hundreds of files and cannot hard code all into individual require statements


Polynomials and Number Theory

Question: Given the equation
$(1+x+x^2+x^3+x^4)^{496}=a_0+a_1x+a_2x^2+...+a_{1984}x^{1984}$
a) What is the gcd of $(a_1,a_2,a_3,...
a_{1983})$?
b) Show that $10^{340}< a_{992}< 10^{347}$.
By the Leibinz theorem, I know that the general term of this polynomial is
$\frac{496!}{a!b!c!d!e!}\cdot x^{b+2c+3d+4e}$.
And $a+b+c+d+e=496$.
So, the first answer is 496, I think, but how can I solve the question b?
Answer: For the first part:
Taking $x=1$ gives us $$5^{496}=\sum_{i=0}^{1984}a_i=2+\sum_{i=1}^{1983}a_i$$
Hence, if $d=\gcd (a_1, \cdots, a_{1983})$ then $d\,|\,(5^{496}-2)$.  Since $a_1=496$ we see that $d\,|\,\gcd(5^{496}-2, 496)$.
Now $496=2^4\times 31$ and, since $5^{496}-2$ is clearly odd we see that $\gcd(5^{496}-2, 496)\in \{1,31\}$.  It is easy to compute that $5^{496}-2\equiv 3 \pmod {31}$ so we must have  $$\gcd(5^{496}-2, 496)=1$$ hence $d=1$.

Polynomials and Number Theory


Convert US Dollar / lb to Canadian Dollar / kg

Question: I can find exchange rate conversions and lbs to kgs. How can I convert USD/LB to CAD/KG? What is the formula? Specifically, I have $1.61 / lb and I need to know what that is in CAD/KG.
Thanks!
Answer: There are 0.76 Canadian dollars per U.S. dollar (I had to look that up) and 2.2 pounds per kg. (I was pretty sure of that but looked it up anyway).
So one Us Dollar/pound= (one US Dollar/pound)* (2.2 pound/kg)(0.75 Canadian Dollars/US Dollar)= (2.2)(0.75) Canadian Dollars/kg= 1.65 Canadian Dollars per kilogram.
Comment: Your exchange rate is wrong. It is the other way around, 0.75 USD for 1 CAD. :)
Comment: But I'm not going from 1 CAD to USD or KG to LB. I'm going from 1.61 USD to CAD.and LB to KG. 1 USD = 1.32 CAD. and 1 LB is 0.4535923 KG.
Answer: If the exchange rate is $a$ CAD/USD, and you have $b$ lbs/kg, then $$Y\left[\frac{CAD}{kg}\right]=X\left[\frac{USD}{lbs}\right]a\left[\frac{CAD}{USD}\right]b\left[\frac{lbs}{kg}\right]$$
Alternatively, you can just google "USD/lbs to CAD/kg"
Comment: Give that CAD is 1.32 to 1 USD, is the following correct? [1.61/1]*[1.32/1]*[1/0.4535923] = 4.6853 CAD per KG
Comment: Yes, that's correct. See [google's conversion](https://www.google.com/search?channel=fs&q=1.61+USD%2Flbs+to+CAD%2Fkg)
Answer: The money change rate is not something fixed so you need to check it on Google or elsewhere. For the formula lbs <-> kg you have:
1 pound = 0.4535924 kilograms
That means 1 dollar / lb = 1 dollar / 0.4535924 kg
if 1 US dollar = R CA dollar then
X USD / lb =  X*R/0.4535924 CAD
Comment: So R is the CAD? Today that would be 1.32.
Comment: If that's the case then 1.61/lb = 1.61*1.32/0.4535924, which is 4.6853 CAD/KG, right?
Comment: @TomHolt that's right


Squares in rings of algebraic integers

Question: Let $K$ be a cubic field, and let $\alpha \in \mathcal{O}_K$ be an irrational algebraic integer. Does there exist a rational integer $m \ne 0$ such that $m \alpha$ is a square in $K$? What about number fields of other degrees?
Answer: Let $L$ be the Galois closure of $K/\mathbb{Q}$, then Chebotarev's density theorem or this argument enable us to find a prime $p$ that splits completely in $L$. So $p$ also split completely in $K$, and we denote
$$p\mathcal{O}_K=\prod_{i=1}^{[K:\mathbb{Q}]}\mathfrak{p}_i.$$
Since the class group of $K$ is finite, it is easy to find an ideal $\mathfrak{a}\subseteq\mathcal{O}_K$ coprime to $p\mathcal{O}_K$ such that $\mathfrak{p_1}\mathfrak{a}$ is principal. Let $\alpha\mathcal{O}_K=\mathfrak{p_1}\mathfrak{a}$, then $\nu_{\mathfrak{p}_1}(\alpha)=1$ while $\nu_{\mathfrak{p}_2}(\alpha)=0$.
However, for any non-zero integer $m\in\mathbb{Z}$, we have $\nu_{\mathfrak{p}_1}(m)=\nu_{p}(m)=\nu_{\mathfrak{p}_2}(m)$. Therefore, one of $\nu_{\mathfrak{p}_1}(m\alpha)$ and $\nu_{\mathfrak{p}_2}(m\alpha)$ must be odd, thus $m\alpha$ can not be a square in $K$.
This construction works for any finite extension $K/\mathbb{Q}$ with $[K:\mathbb{Q}]\geqslant2$.
Answer: Contrary to @Mercury, my answer will not be number theoretic, but Galois theoretic. It will be specific to the cubic case, but will give necessary and sufficient criteria. Let $K$ be the given cubic field over $\mathbf Q$. If $\alpha \in K$ and $\notin \mathbf Q$, necessarily $K= \mathbf Q(\alpha)$ because $3$ is a prime number. Let $\phi_{K/\mathbf Q}$ be the natural map $\mathbf Q^*/{\mathbf Q^*}^2 \to K^*/{K^*}^2$. The condition $m\alpha \in {K^*}^2$ can be translated as : $\alpha {K^*}^2 \in Im \phi_{K/\mathbf Q}$ (*). In other words, the problem amounts to the determination of $Im \phi_{K/\mathbf Q}$ in terms of parameters in $K$. The minimal polynomial of $\alpha$ over $\mathbf Q$ can be classically reduced to the form $X^3 + pX + q$, with discriminant $D= -4p^3 - 27q^2$. Introduce "the" normal closure $N$ of $K$, with Galois group $G$ isomorphic to $S_3=D_6$ or $A_3 = C_3$. The distinction between the two cases depends on $D$ being or not in ${\mathbf Q^*}^2$ :
1) If $D$ is a square, then $N=K$ and $G\cong C_3$, and $Im \phi_{K/\mathbf Q}$ can be conveniently determined using Kummer theory and Galois cohomology. The exact sequence of $G$-modules $1 \to (\pm 1) \to K^* \to {K^*}^{2} \to 1$  (1) gives rise to the cohomology exact sequence $ H^1(G, K^*)\to H^1(G, {K^*}^2)\to H^2(G,(\pm 1))$. But $H^1(G, K^*)=1$ by Hilbert's thm. 90 and $H^1(G,(\pm 1))=1$ because $G$ and $(\pm 1)$ have coprime orders. Finally $H^1(G, {K^*}^2)=1$. Besides, the exact sequence $1\to {K^*}^2 \to K^* \to K^*/{K^*}^2\to 1$  (2) produces an exact sequence
$1\to ({K^*}^2)^G \to {K^*}^G=\mathbf Q^*\to (K^*/{K^*}^2)^G \to H^1(G, {K^*}^2)=1$, so $Im \phi_{K/\mathbf Q}= (K^*/{K^*}^2)^G $. As for $Ker \phi_{K/\mathbf Q}$, note that $({K^*}^2)^G={K^*}^2 \cap \mathbf Q^*$ and the latter group is just ${\mathbf Q^*}^2$ because the square root of each of its element gives rise to an extension of degree 1 or 2 inside $K$ which has degree 3 over $\mathbf Q$ ; in other words, $\phi_{K/\mathbf Q}$ is injective. In conclusion, $\mathbf Q^*/{\mathbf Q^*}^2 \cong (K^*/{K^*}^2)^G $. Note that $K^*/{K^*}^2$ parametrizes the quadratic extensions of $K$ whereas $(K^*/{K^*}^2)^G $ parametrizes those among them which are normal over $\mathbf Q$ (easy Galois exercise) . The isomorphism just obtained means that those particular quadratic extensions of $K$ are obtained by composing $K$ with quadratic extensions of $\mathbf Q$, and this due essentially to $2\neq 3$.
2) The more complicated case is when $N\neq K$ and $G=Gal(N/\mathbf Q) \cong S_3$, which occurs when $D$ is not a square. The subextensions of $N/\mathbf Q$ are the following : $L=\mathbf Q(\sqrt D)$ is the fixed field of $A_3$ and the unique quadratic field contained in $N$; the three conjugate roots $\alpha, \alpha ', \alpha ''$ generate three cubic subextensions $K, K', K''$ fixed by the transpositions of $S_3$, and $N=K(\sqrt D)$. Put $H=Gal(N/L)$ and $J=G/H=Gal(L/\mathbf Q)\cong Gal(N/K)$. We want to determine the image of $\phi_{K/\mathbf Q}$ using the same cohomological machinery as in 1). To circumvent the inconvenient that $K/\mathbf Q$ is not Galois, just exploit the transition formula $\phi_{N/\mathbf Q}=\phi_{N/K}. \phi_{K/\mathbf Q}=\phi_{N/L}.\phi_{L/\mathbf Q}$. I don't give all the details, only the key steps :
a) To compute $\phi_{L/\mathbf Q}$, take as before the cohomology of the analog of the exact sequence (1) relative to $L/\mathbf Q$. The point is that $[L:\mathbf Q]=2$ so we can no longer conclude that $H^1(J, {L^*}^2)=1$. Going on to $H^2$, we get instead $H^1(J,{L^*}^2)=\epsilon$, where $\epsilon = (1)$ or ($\pm 1$), and $\epsilon=1$ iff $-1$ is a norm in $L/\mathbf Q$ (this condition is a kind of Pell-Fermat equation). Then the cohomology of the analog of the exact sequence (2) gives that $Ker \phi_{L/\mathbf Q}= D.{\mathbf Q^*}^2/{\mathbf Q^*}^2$ and $(L^*/{L^*}^2)^J/Im\phi_{L/\mathbf Q}=\epsilon$.
b) Replacing $\mathbf Q$ by $L$ in 1), the computation of $\phi_{N/L}$ goes on exactly as in 1) to yield  $Im \phi_{N/L}= (N^*/{N^*}^2)^H $ . In conclusion, $Im \phi_{N/\mathbf Q}$ "is $(N^*/{N^*}^2)^G $ up to $\epsilon$". The same kind of interpretation in terms of quadratic extensions as at the end of 1) is still valid here. The quadratic field $L$ is ruled out because it's already contained in $N$.
Remarks.
(i) All the calculations above can be carried on over any field of characteristic $\neq 3$ instead of $\mathbf Q$.
(ii) Part 1) remains valid for any odd prime $p$ in place of $3$. So do some pieces of part 2).

Squares in rings of algebraic integers


babel-node is not recognized as internal or external command - Babel 7

Question: I'm using babel v7.6.x and have set up the following.
package.json
 "scripts": {
    "dev": "nodemon --exec babel-node bin/index.js",
    "start": "babel-node bin/index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
...
"devDependencies": {
    "@babel/core": "^7.6.4",
    "@babel/node": "^7.6.3",
    "@babel/preset-env": "^7.6.3",
    "nodemon": "^1.19.4"
  }

.babelrc
{
    "presets":[
        "@babel/preset-env"
    ]
}

yet i am still getting :
'babel-node' is not recognized as an internal or external command,
operable program or batch file.

It used to be working but since doing a recent npm install to get updated versions it has failed to start up successfully.
my node version is 10.15.2
npm version is 6.12.0
Thank you in advance!
Answer: Remove package directory:
rm -rf node_modules

Install again:
yarn

or
npm install

Check there is no errors
Check enough free space available
Check existence of files:

node_modules/.bin/babel-node
node_modules/.bin/babel-node.cmd - windows only
node_modules/@babel/node/bin/babel-node.js
Comment: only this "node_modules/@babel/node/bin/babel-node.js" is not available in my node_modules, rest of the two files under .bin i could able to see. what we can do now ? is that any way to install this file alone ?
Comment: Have you installed "@babel/node" package as in question snippet of package.json demonstrated. Different versions may has different path (and amount of tools).
Answer: I have also run into the same problem. but found the problem might have been with the plugin versions i was using.
Check out this question


change an add entity route to a custom route in order to not use admin theme

Question: I will start off by saying i have already studied these posts, to no avail:
Overriding an entity add/edit form through alterroute
How to load my Entity in Entity form
https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones
I am trying to alter my add-entity route to be not under /admin, as we want this form to use the default theme, not admin theme.
My module is 'project', my entity is 'project'.
Here is my route in the project.routing.yml file:
<code>mycompany.project.add_form:
  path: '/mycompany/project/add/{project_type}'
  defaults:
    _entity_form: 'project.default' #I have also tried custom form_mode here
    _title: 'Add Project'
  requirements:
    _permission: 'add project entities'
</code>
I get the error: Call to a member function id() on string in /Applications/MAMP/htdocs/sfchapter6nov2/core/lib/Drupal/Core/Entity/EntityForm.php on line 363
Yes, this error has been documented before, with posts such as the ones above.  I believe my unique problem is because my entity has an entity type, ie a bundle.  The {project_type} is my bundle name.  The EntityForm does not have an instance of the entity, and I cannot find where to create it.
Help and suggestions much appreciated!
Mary Edith
Answer: The problem is that now the route parameter is a string and so you generate the error. You need to upcast the route parameter to an entity (the config entity of the bundle):
<code>  options:
    parameters:
      project_type:
        type: entity:project_type
</code>
More info https://www.drupal.org/docs/8/api/routing-system/parameter-upcasting-in-routes
Comment: Thank you very very much, 4k4.  This information was in the other posts, but not in a way that enabled me to I understand how to use it.  I had tried 'type:project:city_project', using my bundle name rather than bundle type name.   I appreciate so much getting speedy answers on this site!!!!