Puppet CSR Issue using external certificates

Question: I am hoping that someone might be able to help me with a CSR (Certificate Singing Request) issue that I am facing. I currently have a Puppet server and Puppet agent on a single server. However, I am using external certificates for these. The Puppet server and Puppet agent should have there own individual certificates. I am hopping for some advice on how to stop the agent trying to send a CSR as we are not using puppet's internal Certificates.
The Issue that I am seeing is when I run /opt/puppetlabs/bin/puppetserver ca list --all
I see the following error:
Fatal error when running action 'list'
  Error: Failed connecting to https://server.altname.example.com:8140/puppet-ca/v1/certificate_statuses/any_key
  Root cause: SSL_read: sslv3 alert certificate unknown

I then went on to check the status of the agent and when I run service puppet status I can see the following error:
server puppet-agent[7056]: Failed to submit the CSR, HTTP response was 404

Note; the puppet server and agent are in a running state.
This is showing that there is a CSR issue. However, I don't think this should be happening as I am using external Certificates that I have set up on the machine.
I have also updated the ca.cfg file to disable the certificate authority as I had read this need to be done when using external certificates. This file looks like this:
#puppetlabs.services.ca.certificate-authority-service/certificate-authority-service
puppetlabs.services.ca.certificate-authority-disabled-service/certificate-authority-disabled-service
puppetlabs.trapperkeeper.services.watcher.filesystem-watch-service/filesystem-watch-service

I have also updated the webserver.conf file to point to where the certificates are located.
webserver: {
    access-log-config: /etc/puppetlabs/puppetserver/request-logging.xml
    client-auth: want
    ssl-host: 0.0.0.0
    ssl-port: 8140
    ssl-cert: /etc/puppetlabs/puppet/ssl/certs/server.altserver.example.com.puppetserver.pem
    ssl-key: /etc/puppetlabs/puppet/ssl/private_keys/server.altserver.example.com.puppetserver.pem
    ssl-ca-cert: /etc/puppetlabs/puppet/ssl/certs/ca.pem
}

The certificates are located at /etc/puppetlabs/puppet/ssl/
When running a tree on the directory this looks like:
/etc/puppetlabs/puppet/ssl/
├── certificate_requests
├── certs
│   ├── ca.pem
│   ├── server.altserver.example.com.pem
│   └── server.altserver.example.com.puppetserver.pem
├── crl.pem
├── private
├── private_keys
│   ├── puppet.altserver.example.com.pem
│   ├── server.altserver.example.com.pem
│   └── server.altserver.example.com.puppetserver.pem
└── public_keys

Any help on this issue would be greatly appreciated, If you need any more information please ask.
Thank you.
I am running this on a Ubuntu 22.04 server, and the puppet version is 7.28.0.
Comment: Puppet documents the [requirements and procedure for using an external CA](https://www.puppet.com/docs/puppet/8/config_ssl_external_ca.html).  You appear to be looking for option 2, "Single CA".  Note well that if you disable the puppet server's CA, which indeed you do need to do for this configuration, then you cannot expect to use any of the `puppetserver ca` subcommands.
Answer: If the agent is issuing a CSR, then that means it doesn't think it has a valid certificate yet.  As described in the Puppet documentation, you shouldn't need to change the agent's configuration file, but you do need to store in the appropriate locations: the agent's cert, the corresponding private key, the cert for the CA that signed it (which must be the same for agent and server), and the CA's CRL (or at least a CRL for the CA).
I can't tell you whether the names and locations in which you've stored the necessary files are correct for your installation, but Puppet can:

puppet config print hostcert --section agent
puppet config print hostprivkey --section agent
puppet config print localcacert --section agent
puppet config print hostcrl --section agent

If you change --section agent to --section server in those commands then Puppet will tell you where the puppetserver's documents should reside.  For server and agent on the same host, the CA cert and CRL might be the same location for server and agent.
IMPORTANT NOTE: execute those commands as the appropriate user.  That's root for the agent commands, and the puppetserver user (maybe "puppet") for the server commands.
Do also make sure that the permissions on those files and the directories in the path to them allow the relevant processes to access them.  The agent ordinarily runs as root, so there is probably no issue on that side, but the server ordinarily runs as an unprivileged user.
Comment: Running the commands shows that the files are correct for the installation, and paths are correct. If we forget about the puppetserver CA commend as that wont work. Then I am still facing the issue with the CSR the agent is sending. I can't seem to work out why it is doing this. As the Certificate is valid but it does not think it is. And the relevant files are stored in the correct location(s).
Comment: @CallumMcCrorie, do note that whereas you can and should forget about the puppetserver CA, you *cannot* ignore setting up the server's cert / key / cacert / crl.  It might be that on the same machine, agent and server share some of these, but not necessarily.  And they have nothing directly to do with puppetserver's built-in CA functionality.
Comment: If indeed all the files are set up correctly, then I can only speculate about why the agent keeps trying to issue a CSR.  It might just be that once it generated a CSR, it insists on trying to get it signed, despite subsequent reconfiguration mooting that.  There might also be an issue with the user as whom the agent is running.  Different users have their own, independent Puppet metadata.  Effectively, the agent running as me is a logically distinct endpoint from the agent running as root on the same machine.
Comment: The agent and server are both running as root user. This should mean that they have the correct permissions they need for this to work.


If $x^3+y^3+(x+y)^3+33 xy=2662$, $x,y\in \Bbb R$, find $S=x+y$.

Question:
If $x^3+y^3+(x+y)^3+33 xy=2662$ and $\{x,y\}\subset \Bbb R$, find $S=x+y$.

This question from an olympiad contest. Answer stated: $S=x+y=11$
Tried to develop $(x+y)^3$ to find something useful for the situation, but without success.
Comment: $$2662=2\cdot11^3$$
Comment: ... and if $x+y=11$ then $33xy=3x^2y+3xy^2$.
Comment: Any plotter functions given as the graph of this curve  the straight line $x + y = 11$ which could result in  dishonest answers.
Answer: Rewrite our equation in the following form.
$$(x^3+y^3-11^3+3xy)+(x+y)^3-11^3=0$$
Now, we can use $a^3+b^3+c^3-3abc=(a+b+c)(a^2+b^2+c^2-ab-ac-bc).$
Thus, we obtain:
$$(x+y-11)(x^2+y^2+11^2-xy+11x+11y+(x+y)^2+11(x+y)+11^2)=0$$ or
$$(x+y-11)(2x^2+2y^2+xy+22x+22y+242)=0$$
and since
$$2x^2+2y^2+xy+22x+22y+242=(x+11)^2+(y+11)^2+x^2+xy+y^2>0,$$
we obtain $$x+y=11$$
Done!
Answer: $$ (x+y)^3 + (x+y)(x^2-xy+y^2)+33xy=2662 $$
$$ S^3 + S(x^2+y^2-xy) + 33xy=2662 $$
$$ S^3 + S(S^2 - 3xy) + 33xy=2662 $$
$$ 2S^3 + 3xy(11 - S) = 2662 $$
$$ \frac{3}{2}xy(11-S)=11^3 - S^3$$
if $S \ne 11$:
$$ \frac{3}{2}xy = 121 + 11S + S^2 $$
Now try to write down roots of this equation on $S$, add condition of their existence ($D \ge 0$, cause roots are real) and remember that $S = x + y$. Hope this will lead to contradiction.
Comment: Where did $(x+y)^3$ go in the first line?
Comment: @Ennar, thanks, fixed.
Answer: Let $x+y=S$
$$S^3+(S-x)^3+33 x (S-x)+x^3$$
has a derivation
$$ \frac{d}{dx}(x^3+(S-x)^3+S^3+33 x (S-x) )= -3 (-11 + S) (S - 2 x) $$
So, sollution $ \frac{d}{dx}=0$ leads to $S=11$ or $ S=2x$, i.e. $x=y$
For $x=y$,  $x^3+33 x y+(x+y)^3+y^3=10x^3+33x^2=2662$ has a unique real solution $x(=y)=11/2$
For $y=c-x$, function is a ploynomial $2 S^3 + (33 S - 3 S^2) x + (-33 + 3 S) x^2$ with determinant
$$ -351384 + 31944 S + 1089 S^2 + 66 S^3 - 15 S^4 $$
which is negative except $S=11$


How to post a value to a webpage in a datalist

Question: i want to post the Prd_id to the webpage Products.aspx as in the code
<asp:DataList ID="DataList1" runat="server"
         DataKeyField="Prd_id" DataSourceID="AccessDataSource1">
         <ItemTemplate>
            <a href='Products.aspx?prdid=<%# Eval("Prd_id") %>'>Add to Cart
         </ItemTemplate>
</asp:DataList>

Answer: Try to use a hidden field to store the selected product id:
HTML:

    <asp:DataList ID="DataList1" runat="server" DataKeyField="Prd_id" DataSourceID="AccessDataSource1">
        <ItemTemplate>
            <asp:LinkButton ID="btnAdd" runat="server" OnClick="btnAdd_Click" OnClientClick="<%# "addProduct('" + Eval("Prd_id") + "');" %>" ></asp:LinkButton>
        </ItemTemplate>
    </asp:DataList>

    <asp:HiddenField ID="hidProductId" runat="server" />

Code behind:
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        var productId = hidProductId.Value;
    }

Comment: You can try to use a button with PostbackURL property
Comment: i dont want to have to use javascript


Pass the value in a field into a colorbox popup

Question: Is it possible to dynamically change a link on a colorbox popup a specific field value?
I have a view displaying a list of external links that have been added using a custom content type. And what I would like to do is be able to have a colorbox popup when you click on one of those links that explains that you are about to go to an external site.
I have the colorbox popup working with a button to go to that link, but I need the link of the colorbox button to change depending on which node they click on in the view.
My field is "field_conf_presentation_link"
Can I pass that value in anyway to the link that the popup would have?
Here is my view displaying the link they would click on:

Here is the code I have on my page template file that creates the content for the popup:

  <?php print '
' . t('You are now being redirected to view this live session.') . '
'; ?>
  <?php print l('Watch Now ›', '**LINK HERE**', array('attributes' => array('class' => array('btn-small')) ) ); ?>

I've been looking around and see that there is a module called Colorbox Node that might be able to give me what I want, but I am hoping I can get around that for something like this.
Answer: Using the Drupal Colorbox module you should be able to accomplish this.
You just need to add the class colorbox-load to your link and then to modify the colorbox settings per link append something like ?width=500&height=500 to the end of the path.
Colorbox Documentation

Check the "Enable Colorbox load" option in Colorbox settings.
This enables custom links that can open content in a Colorbox. Add the
  class "colorbox-load" to the link and build the url like this
  "[path]?width=500&height=500&iframe=true" or
  "[path]?width=500&height=500" if you don't want an iframe.
If you want to pass the width and height of the Colorbox as a
  percentage (useful for responsive designs), you can format the link
  like this "[path]?width=90%25&height=90%25&iframe=true" or
  "[path]?width=90%25&height=90%25", where the "%25" is the HTML entity
  for "%".
Other modules may activate this for easy Colorbox integration.
Load inline content in a Colorbox
Check the "Enable Colorbox inline" option in Colorbox settings.
This enables custom links that can open inline content in a Colorbox.
  Inline in this context means some part/tag of the current page, e.g. a
  div. Replace "id-of-content" with the id of the tag you want to open.
Add the class "colorbox-inline" to the link and build the url like
  this "?width=500&height=500&inline=true#id-of-content".
It could e.g. look like this.
Link to
  click  What
  ever content you want to display in a Colorbox.
  Alternatively instead of style="display: none;" you could use
  class="element-hidden".
Other modules may activate this for easy Colorbox integration.
Answer: With the help of @Citricguy I was able to find a solution to this. Turns out the feature needed is not the load, but the inline feature.
It's not the cleanest solution but using views I was able to create a custom text field that created a DIV using tokens. I then passed that DIV into the colorbox-inline. With that I was able to generate the dynamic link in my colorbox that I needed.


Como enviar um json de uma Activity para um Fragment?

Question: Tenho uma activity que é adicionado um dado no JsonObjetct. E como visto no código a seguir, eu o levo como string, mas, minha dúvida, como eu pelo este JsonObject no fragmento para que possa trabalhar com ele, como Json?
Segue código da Activity:
.........
    objectJson = SharedPreferenceHelper.getScheduling(this);
    inicializeSetting(savedInstanceState);

    btn_1 = (ToggleButton)findViewById(R.id.tglSearch1);
    btn_1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            btn_1.setChecked(true);
            btn_2.setChecked(false);
            objectJson.addProperty("type", 0);

        }
    });
    btn_2 = (ToggleButton)findViewById(R.id.tglSearch2);
    btn_2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            btn_1.setChecked(false);
            btn_2.setChecked(true);
            objectJson.addProperty("type", 1);
        }
    });

    btnContinuar = (Button)findViewById(R.id.btnGoSearch);
    btnContinuar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SearchAskListFragment fragment = new SearchAskListFragment();

            Bundle bundle = new Bundle();
            bundle.putString("json", objectJson.toString());
            fragment.setArguments(bundle);

            getSupportFragmentManager().beginTransaction()
                    .add(R.id.containerLinear, fragment)
                    .commit();
            getSupportFragmentManager().executePendingTransactions();
           // Routes.open(getApplicationContext(),URIs.SearchAskFragment());
        }
    });

Answer: Está é a maneira mais indicada de se fazer, pois a sua activity não vai precisar conhecer as chaves que seu fragment precisa e vc obriga que ele instancie com os parâmetros corretos.
No caso do seu ObjectJson talvez você precise converter ele em String para colocar no bundle e no fragment recuperado da String pro Object. Eu aconselho você já criar um objeto e converter o json nele para transitar facilmente por activities e fragments.
public static MyFragment newInstance(String param) {
    MyFragment myFragment = new MyFragment();

    Bundle args = new Bundle();
    args.putString("someString", param);
    myFragment.setArguments(args);

    return myFragment;
}

Você conseguira recuperar os objetos salvos desta forma:
getArguments().getString("someString", 0);


Show that rank($AQ$) = rank($A$)

Question:
Let $A$ be an $m × n$ matrix. If $P$ and $Q$ are invertible $m×m$ and $n×n$ matrices, respectively, then
  (a) rank($AQ$) = rank($A$),
  (b) rank($PA$) = rank($A$), and therefore, (c) rank($PAQ$) = rank($A$).

The rank of the matrix is defined to be the rank of the linear transformation $L_A: F_n \to F_m$, where $L_A(x) = Ax$ and $R$ is the range.
Proof. First observe that
$R(L_{AQ})=R(L_AL_Q)=L_AL_Q(F_n)=L_A(L_Q(F_n)) = L_A(F_n)=R(L_A)$,
Can you explain to me why is the $L_Q(F_n) = F_n$?
As I think about $L_Q(F_n)$ it must map to $F_m$ because for any vector $v \in F_n$ $L_Q(v) = Qv \in F_m$ by definition.
Answer: $Q$ is an invertible matrix, which means that it, for every $b\in F^n$, the equation $Qx=b$ has a solution (i.e., $x=Q^{-1} b$), which means that $L_Q$ must be surjective.
$L_Q$ is a mapping from $F_n$ to $F_n$, which means that $L_Q(F_n)$ is equal to the entire codomain of $L_Q$, which is $F_n$.
Comment: But $L_Q$ is a mapping from $F_n$ to $F_m$ so being surjective must mean that just for any $w \in F_m \exists x \in F_n$ such that $Q(x) = w$ as you have written. How does that imply that $L_Q(F_n)=F_n$ if it maps to $F_m$?
Comment: @SargisIskandaryan Why do you think $L_Q$ is a mapping to $F_m$?
Comment: I don't know)) Since Q is an $n$ by $n$ then by definition given in my book it is a mapping $L_Q: F_n \to F_n$. Now I see it. Thank you!
Answer: Think of the interpretation of matrices in terms of linear maps: $A$ is the matrix of a linear map $f_A:F^n\longrightarrow F^m$; $P$ the matrix of a linear map $u_P:F^m \longrightarrow F^m$ and $Q$  the matrix of a linear map $u_Q:F^n \longrightarrow F^n$.
The invertibility of $P$ and $Q$ means $u_P$ and $u_Q$ are isomorphisms, and the rank of a matrix is the dimension of the image of the associated linear map. Now, an isomorphism does not change the dimension of a subspace, so
$$\operatorname{rank}(PA)=\dim\operatorname{Im}(u_P\circ f_A)=\dim\operatorname{Im}( f_A)=\operatorname{rank}(A).$$
Similar proof, mutatis mutandis, for $\operatorname{rank}(AQ)$.

Show that rank($AQ$) = rank($A$)


Keras: AttributeError: 'Adam' object has no attribute '_name'

Question: I want to compile my DQN Agent but I get error:
AttributeError: 'Adam' object has no attribute '_name',
DQN = buildAgent(model, actions)
DQN.compile(Adam(lr=1e-3), metrics=['mae'])

I tried adding fake _name but it doesn't work, I'm following a tutorial and it works on tutor's machine, it's probably some new update change but how to fix this
Here is my full code:
from keras.layers import Dense, Flatten
import gym
from keras.optimizer_v1 import Adam
from rl.agents.dqn import DQNAgent
from rl.policy import BoltzmannQPolicy
from rl.memory import SequentialMemory

env = gym.make('CartPole-v0')
states = env.observation_space.shape[0]
actions = env.action_space.n

episodes = 10

def buildModel(statez, actiones):
    model = Sequential()
    model.add(Flatten(input_shape=(1, statez)))
    model.add(Dense(24, activation='relu'))
    model.add(Dense(24, activation='relu'))
    model.add(Dense(actiones, activation='linear'))
    return model

model = buildModel(states, actions)

def buildAgent(modell, actionz):
    policy = BoltzmannQPolicy()
    memory = SequentialMemory(limit=50000, window_length=1)
    dqn = DQNAgent(model=modell, memory=memory, policy=policy, nb_actions=actionz, nb_steps_warmup=10, target_model_update=1e-2)
    return dqn

DQN = buildAgent(model, actions)
DQN.compile(Adam(lr=1e-3), metrics=['mae'])
DQN.fit(env, nb_steps=50000, visualize=False, verbose=1)

Comment: @I'mahdi okay, sorry
Comment: add full code, this code doesn't any error
Answer: My 2 cents: use legacy keras optimizer!
#from tensorflow.keras.optimizers import Adam
from tensorflow.keras.optimizers.legacy import Adam

it works in my case.
Answer: Your error came from importing Adam with from keras.optimizer_v1 import Adam, You can solve your problem with tf.keras.optimizers.Adam from TensorFlow >= v2 like below:
(The lr argument is deprecated, it's better to use learning_rate instead.)
# !pip install keras-rl2
import tensorflow as tf
from keras.layers import Dense, Flatten
import gym
from rl.agents.dqn import DQNAgent
from rl.policy import BoltzmannQPolicy
from rl.memory import SequentialMemory

env = gym.make('CartPole-v0')
states = env.observation_space.shape[0]
actions = env.action_space.n
episodes = 10

def buildModel(statez, actiones):
    model = tf.keras.Sequential()
    model.add(Flatten(input_shape=(1, statez)))
    model.add(Dense(24, activation='relu'))
    model.add(Dense(24, activation='relu'))
    model.add(Dense(actiones, activation='linear'))
    return model

def buildAgent(modell, actionz):
    policy = BoltzmannQPolicy()
    memory = SequentialMemory(limit=50000, window_length=1)
    dqn = DQNAgent(model=modell, memory=memory, policy=policy,
                   nb_actions=actionz, nb_steps_warmup=10,
                   target_model_update=1e-2)
    return dqn

model = buildModel(states, actions)
DQN = buildAgent(model, actions)
DQN.compile(tf.keras.optimizers.Adam(learning_rate=1e-3), metrics=['mae'])
DQN.fit(env, nb_steps=50000, visualize=False, verbose=1)

Answer: #pip install keras==2.11.0
#pip install tensorflow==2.11.0
dqn.compile(tf.keras.optimizers.legacy.Adam(learning_rate=1e-3), metrics=['mae'])


Sum of three probability density functions.

Question: If $A_1,A_2$ and $A_3$ are independent and have pdf $f(t)=\lambda e^{-\lambda t}$ when $t \geq 0$ and $0$ when $t<0$. What is the pdf of the sum $A_1+A_2+A_3$.
So the first step is the  pdf of sum $A_1+A_2$ which is the convolution
\begin{align}
f(z)&=\int\limits_{-\infty}^{\infty} f(z-t)f(t) dt \\
&=\int\limits_{0}^{z} \lambda e^{-\lambda z+\lambda t} \lambda e^{-\lambda t} dt \\
&=\lambda^2 \int\limits_{0}^{z} e^{-\lambda z} dt \\
&=\lambda^2 e^{-\lambda z} \int\limits_{0}^{z} 1 dt \\
&=\lambda^2 e^{-\lambda z} z
\end{align}
when $z \geq 0$ and $0$ when $z<0$.
So isn't the pdf of the sum $A_1+A_2+A_3$ convolution $f(z) \star f(t)$
\begin{align}
f(\tau)&=\int\limits_{-\infty}^{\infty} f(\tau-z)f(z) dz \\
&=\int\limits_{0}^{\tau} \lambda e^{-\lambda\tau+\lambda z}\cdot \lambda^2 e^{-\lambda z} z \;  dz \\
&=\lambda^3 e^{-\lambda \tau} \int\limits_{0}^{\tau} z \;dz \\
&=\frac{\lambda^3 e^{-\lambda \tau} \tau^2}{2}
\end{align}
Is this correct or are the limits of the integral wrong?
Answer: Yes you are right. Another way to do it is to notice that
$P(A_1 + A_2 + A_3  \leq t) = P(X \geq 3)$
where $X$ is a Poisson variable with parameter $\lambda t$, so
$P(A_1 + A_2 + A_3  \leq t) = P(X \geq 3) = 1- e^{-\lambda t} -\lambda t e^{-\lambda t} - \dfrac{\lambda^2 t^2}{2}e^{-\lambda t}$,
Then take derivative with respect to $t$ to refind the same result
Comment: Hmm that is nice observation. But I don't get the same result..Should you get $\frac{\lambda^3 e^{-\lambda \tau} \tau^2}{2}$ if you derivate that ($t=\tau$)?
Comment: @ELEC Yes, I've done the computation, the result is the same
Comment: Okey. I guess I was just too lazy to simplify the result.
Comment: Oh and thank you alot!
Comment: @ELEC You are welcome!


Can we always find a complex polynomial which (together with its derivatives) satisfies given points?

Question: Let $C=\{ c_1,…,c_m\}$ be a finite subset of $\mathbb{C}$. I wonder if we can always find a polynomial $p$ with complex coefficients that satisfies a group of equations as follows:
$p(c_1)=k_{11},p(c_2)=k_{12},…,p(c_m)=k_{1m}$
$p'(c_1)=k_{21},p'(c_2)=k_{22},…,p'(c_m)=k_{2m}$
.
.
.
$p^{(n)}(c_1)=k_{n1},p^{(n)}(c_2)=k_{n2},…,p^{(n)}(c_m)=k_{nm}$
where $n$ is an arbitrary number.
Comment: You can search for [Hermite's interpolation](https://en.wikipedia.org/wiki/Hermite_interpolation)
Comment: If $n+1=m$ this gives a triangular and regular system for the coefficients of $p$.
Comment: The $c_i$ must be all different. Otherwise if $c_1=c_2$ and we want $P(c_1)=0, P(c_2)=0, P'(c_1) \ne 0$, this is impossible.
Answer: This is a fairly bullet-headed approach to show we can always solve this. Certainly nothing like a useful algorithm.
The trick is to first solve for when all but one column of values are all zeros. Then we combine the the resulting polynomials.
This is similar to the approach to showing there is a solution in the $n=0$ case, where you get (when $m=3$):
$$p(x)=a_1(x-c_2)(x-c_3)+a_2(x-c_1)(x-c_3)+a_3(x-c_1)(x-c_2)$$ and solve for $a_1,a_2,a_3.$ But with $n=2,$ say, you get:
$$p(x)=q_1(x)(x-c_2)^3(x-c_3)^3+q_2(x)(x-c_1)^3(x-c_3)^3+q_3(x)(x-c_1)^3(x-c_2)^3$$ where the $q_i$ are polynomials of degree $2.$

Let $f(x)=(x-c_1)\cdots (x-c_m).$ Let $f_i(x)=\frac{f(x)}{x-c_i}.$ Note, $f_i$ is a polynomial - we are just removing one of the roots of $f.$
Let $g_i(x)=f_i^{n+1}(x).$
Then $g_i(c_i)\neq 0.$ When $i\neq j,$ and $k=0,\dots,n$ $g_{i}^{(k)}(c_j)=0.$
We will find a polynomial $q_i(x)$ so that $p_i(x)=q_i(x)g_i(x)$ satisfies $p_{i}^{(j)}(c_i)=k_{ji}.$. Implicitly, $p_i^{(k)}(c_j)=0$ when $i\neq j$ and $0\leq k\leq n.$
To find $q_i(x),$ first note we need $q_i(c_i)=k_{0i}g_{i}(c_i)^{-1}.$
Then we need $q_i'(c_i)g_i(c_i)+q_i(c_i)g_i'(c_i)= k_{1i}.$ We again use $g_i(c_i)\neq 0$ is invertible to get a value for $g_i'(c_j).$
We work inductively.
Knowing $q_i^{(j)}(c_i)$ to $j=0,1,\dots,j',$ we can compute what $q_i^{(j'+1)}(c_i)$ must be.
Once we've got all those values, we can write:
$$q_i(x)=\sum_{j=0}^n \frac{q_i^{(j)}(c_i)}{j!}(x-c_i)^j$$
Then your final polynomial is: $$p(x)=\sum_{i=1}^m q_i(x)g_i(x)$$
Since each $g_i$ is of degree $(n+1)(m-1)$ and $q_i$ is of degree at most $n,$ the result is a polynomial of degree at most $(n+1)m-1.$
Comment: How do we know that $g_i(c_i)$ is nonzero for if $n$ is too big, then $f^{n+1}_i$ is the zero function.
Comment: No, $f_i(c_i)\neq 0$ means $f_i^{n+1}(c_i)$ is not zero, no matter if $n$ is $1000$ or $1000000.$ It can be very small, but it is not zero. And it is definitely not the zero function. @boyler


A report about complex numbers

Question: I was told to make a report for mathematics, and I could choose my own subject. I chose complex numbers, because I really think they are interesting. However, my teacher says that there isn't a lot of information to find about complex numbers.
Now I have found some things to write about complex numbers:

What are complex numbers?
History of complex numbers
Application of complex numbers
Elementary operations

The problem is, I can't think of anything else to write about. I was maybe thinking about Euler's formula $e^{ix}=\cos x + i \sin x$, and then Euler's identity. But this is not enough. I was hoping if you have any ideas for this report.
Comment: Your teacher makes a strange claim.  There is in fact an incredible number of interesting things you can say about $\mathbb C$.  The complex numbers are deep and wide and full of surprises.  I think you should write the report and show your teacher he/she is wrong.
Comment: There's an entire area of mathematics called complex analysis,
Comment: Have a look at Gaussian integers, the subset of complex numbers whose real and complex parts are whole numbers.
Comment: The equation $e^{\pi i}=-1$ is considered one of the coolest equations in math, it relates four fundamental numbers, $e$, $\pi$, $i$, and $1$.  When this was first discovered it made a big impact.
Comment: You can also try reporting on the fundamental theorem of algebra.
Comment: Solving geometry in complex coordinates
Comment: Its got a very interesting bit of history too. https://www.youtube.com/watch?v=_qvp9a1x2UM
Comment: @GregoryGrant, haha I was also shocked when he said that.
Comment: Somebody mentioned the Gaussian integers.  Those are an excellent thing to look into.  You can generalize the concept of primes and factorization and that is really touching on something really deep.  In fact you still have unique factorization in the Gaussian integers, but that's really an exception to the rule.
Comment: If you do try to write a comprehensive report on complex number which encompasses everything, it's going to take you years. Complex numbers penetrate the deepest area of physics and maths and we have done exceptional amount of work with them.
Answer: Complex numbers are an extension of the real numbers. Every complex number, $z$, can be expressed as $$z=x+iy$$ where $x$ and $y$ are real numbers and $i$ is a number for which $i^2 = -1$. In particular, the complex numbers can be viewed as a plane.
The imaginary number is a root of the equation $x^2+1=0$. We know that this equation cannot have any real roots, because when we graph it, it does not intersect the $x$-axis. Therefore, the solution to $x^2+1=0$ cannot be "real", and so it earned the infamous qualification "imaginary".
Imaginary numbers first appeared in the work of Hero of Alexandria. And there they appeared as the square root of a negative number. By then it was known  that any real number squared must be positive, and Hero of Alexandria flipped the sign of the number insider the square root without mention.
It wasn't until much later before complex numbers appeared again. This time it was in the context of solving cubic equations by Cardano (who lived roughly between 1500 and 1570). However, he still considered complex numbers extraneous and not proper mathematics.
It wasn't until the time of Euler before complex numbers became more accepted, in equations like $$e^{i\pi}+1=0.$$ More serious consideration of complex numbers began in the 1800s.
The subsequent development of complex numbers in the context of calculus occurred mostly in the 1800s. The goal was to resolve questions like the Prime Number Theorem. It also is used to answer questions in Physics, Approximation Theory, and has many other applications.
A quick list of important topics in complex analysis are the following:
Liouville's Theorem
Cauchy's Theorem
Picard's Theorem
Riemann Hypothesis
Riemann Sphere
Mobius Transformations (See: https://www.youtube.com/watch?v=JX3VmDgiFnY )
Entire Functions
Analytic Functions
Euler's Formula $e^{i\theta} = \cos(\theta) + i \sin(\theta)$.
Analytic Number Theory (Prime Number Theorem, Dirichlet Series, Dirichlet's Theorem on Arithmetic Progressions, etc.)
Honestly, the field of Complex Analysis is a huge area of study. This is just a taste of what goes on there.

You might find the following book useful as primary source material:
"An imaginary tale: The story of $\sqrt{-1}$" by Paul Nahin
Comment: I am honestly trying to give you a bunch of keywords that you can follow up on. If you want me to expand on anything in particular, I would be happy to do so.
Comment: Haha, thank you very much. This is really helpful!
Comment: I thought it was the cubic equations that were troubling people and eventually led to the acceptance of complex numbers. These equations might have real solutions but require complex numbers to solve yhem algebraically.
Comment: You can easly write an entire report solely on complex integration
Comment: You are probably right about the cubic equations. I was simplifying things a bit for this answer. The fact is that complex numbers first arose in the study of roots of polynomials @andreysokolov
Comment: Following up, imaginary numbers were first discovered by Hero of Alexandria when he was trying to compute the volume of a pyramid. Much later, Cardano used complex numbers in order to resolve the cubic equation, as you pointed out. Both mathematicians thought of imaginary numbers as being frivolous (and the former also considered negative numbers frivolous). Their acceptance didn't take root until the 1700s in the time of Euler. This was about 200 years after Cardano. It's more likely $e^{i\pi}+1=0$ and other formulas led to the acceptance of the complex numbers as real objects.@andreysokolov
Comment: Where "real objects" is interpreted loosely, lol
Answer: You'll probably find some inspiration in Needham's Visual Complex Analysis.

A report about complex numbers


Delaying munin notifications

Question: I have a few servers that are monitored by munin, and fairly frequently one of a selection of units has a transient failure to read data.  That gets me two emails, one telling me that all the values are unknown and the second five minutes later letting me know that everything's OK after all.
As far as I can tell, munin is functioning as designed here, but I'd like to know if there's any way to delay sending the initial 'unknown' alert for one update cycle, so transient unknowns aren't reported?  All my current setup is achieving is training me to ignore the warning mails.
Failing that, is there any way to disable sending the 'unknown' alerts and their corresponding recovery alerts altogether?
Answer: I don't really use Munin but as I see an unknown_limit setting can be set for items/plugins which defines how many consecutive unsuccessful readings should occur before setting a value to "unknown".
Based on the Munin::LimitsOld module it defaults to 3, I think you should try to set or increase this number.
I have checked this on Munin 1.4.5.
Answer: I achieve this by having munin notify, not directly to end-users, but into NAGIOS via NSCA, and having NAGIOS handle the notifications.  This means I can use NAGIOS' (much more sophisticated) controls on notification delay, frequency, escalations and so on.  Yes, NAGIOS is quite heavyweight just to be a notification engine, but you can then use it for qualititive (rather than quantitative) monitoring as well.
Answer: Remember that one of the big benefits of using open source tools is that you can look at the source to see exactly what they do (and  change the behaviour if you don't like it). A quick scan of LimitsOld.pm shows that Gábor's suggestion is the right approach - unknown_limit can be set on a per-service basis or globally and appeared around Munin 1.4.4 (see http://munin-monitoring.org/ticket/828).

Delaying munin notifications


Use of ffprobe in kivy 'File not Found'

Question: i am trying to convert audio from webm to mp3 using pudub module in android using kivy. I've included pydub,ffprobe-python,ffmpeg-python in buildozer.spec file but when i run the app i get the following error !
<code>FileNotFoundError: [Errno 2] No such file or directory: 'ffprobe'
</code>
Answer: You will need to embed ffmpeg suite binaries. ffprobe-python and ffmpeg-python are only connectors to call the binaries.
Comment: how to do this please help !

Use of ffprobe in kivy 'File not Found'


simple tools to extract Re,Im,Abs... of any complex function

Question: I've developped my own set of simple yet powerful tools to work on complex functions. I would like to know if these simple tools are currently used in complex analysis.
Let's $z = x + i y = |z| e^{i\theta}$ and it's complex conjuguate $z^* = x - i y = |z| e^{-i\theta}$, where $\theta = \text{Arctan}(y/x)$, we can write:
$
\frac{1}{2i}\text{Log}\left( \frac{z}{z^*} \right) =\text{  }\frac{1}{2i}\text{Log}\left( \frac{|z|e^{i \theta }}{|z|e^{-i \theta }} \right) = \theta =\arg(z)
$
$
\sqrt{z z^*}=\sqrt{ |z|e^{i \theta }|z|e^{-i \theta }}=|z|=\text{Abs}(z)
$
$
\frac{1}{2}( z + z^*)=|z|\frac{(e^{i \theta }+e^{-i \theta })}{2}= \mathfrak{Re}(z)
$
$
\frac{1}{2}( \frac{z + z^*}{|z|})=\frac{(e^{i \theta }+e^{-i \theta })}{2}=\text{Cos}(\theta )
$
$
\frac{1}{2i}( z - z^*)=|z|\frac{(e^{i \theta }-e^{-i \theta })}{2i}=\mathfrak{Im}(z)
$
$
\frac{1}{2i}( \frac{z - z^*}{|z|})=\frac{(e^{i \theta }-e^{-i \theta })}{2i}=\text{Sin}(\theta )
$
Let's now $f(z)$ be any complex function or composition of functions $g(...f(z))$, the same results hold when plugging  $f(z)$ and  $f(z^*)$ instead of $z$ and $z^*$, giving the tools set:
$
\frac{1}{2i}\text{Log}\left( \frac{f(z) }{f(z^*)} \right) =\text{  }\frac{1}{2i}\text{Log}\left( \frac{|f(z)|e^{i \theta }}{|f(z)|e^{-i \theta }} \right) = \theta =\arg(f(z))
$
$
\sqrt{f(z) f(z^*)}=\sqrt{ |f(z)|e^{i \theta }|f(z)|e^{-i \theta }}=|f(z)|=\text{Abs}(f(z))
$
$
\frac{1}{2}\left( f(z)+f(z^*) \right)=|f(z)|\frac{\left(e^{i \theta }+e^{-i \theta }\right)}{2}= \mathfrak{Re}(f(z))
$
$
\frac{1}{2}\left( \frac{f(z)+f(z^*)}{|f(z)|}\right)=\frac{\left(e^{i \theta }+e^{-i \theta }\right)}{2}=\text{Cos}(\theta )
$
$
\frac{1}{2i}\left( f(z)-f(z^*)\right)=|f(z)|\frac{\left(e^{i \theta }-e^{-i \theta }\right)}{2i}=\mathfrak{Im}(f(z))
$
$
\frac{1}{2i}\left( \frac{f(z)-f( z^*)}{|f(z)|}\right)=\frac{\left(e^{i \theta }-e^{-i \theta }\right)}{2i}=\text{Sin}(\theta )
$
So, are these simple formulas using $f(z)$ and $f(z^*)$ to extract the complex components of functions known? Is there in complex analysis any litterature about?
EDIT: after comments, may be we should consider $f(z)^*$ instead of $f(z^*)$ ...?
Here are some examples showing their use.
Using the formula for the Zeta function $\zeta (\mathit{z})=\prod_{k=1}^{\infty } \frac{1}{1-p_k{}^{-\mathit{z}}}$ for $z>1$, where $p_k$ is the $k^{th}$ prime number, we can quite easily find:
$$
\sqrt{\zeta (z) \zeta(z^*)}=|\zeta (\mathit{z})|=\prod_{k=1}^{\infty } \sqrt{\frac{p_k{}^{2x}}{p_k{}^{2x}-2p_k{}^x\cos \left(y \log \left(p_k\right)\right)+1}}
$$
$$
\frac{1}{2i}\text{Log}\left( \frac{\zeta(z) }{\zeta( z^*)} \right) = \arg( \zeta (z) )=-\sum_ {k = 1}^{\infty}\sum _ {q = 1}^{\infty}\frac {1} {k p_q^{k x}}\text {Sin}( k y \text{ Log}(p_q ) )
$$
Comment: What exactly are you asking? The formulas for real part and imaginary part are pretty standard, your formulas for sine and cosine follow directly from Euler's formula. The formula using the logarithm is one particular definition of the logarithm. The formulas for the functions you gave below are not quite correct, since you omit the $z$ dependence of $\theta$ and $f(z)^* \ne f(z^*)$ in general.
Comment: A simple concrete example to illustrate @filmor's point: Let $f(z) = z+i$. Then $f(i) = 2i$, but $f(-i) = 0$, so neither $\arg f(z^*) = -\arg f(z)$ nor $|f(z)|=|f(z^*)|$ holds in general for holomorphic functions.
Comment: @Eddy, what do you mean by "complex transformation"? What do you mean by "preserve angles"? The first set of equations is very well known and used all the time while the second set relies on a property ($f(z)^* = f(z^*)$) that you neither define nor show for the function you apply it to.
Comment: @Eddy, if $f(z) = z+i$ then $f(z^*) = z^* + i$ though.
Comment: The formula for $\sin \theta$ is also incorrect. (There's an $i$ missing in the denominator.)
Comment: @filmor, the formulas, in my concern, are correct every time i use them. The fact seems to be that complex transformations preserve angles.
Comment: thanks you, @mfr - corrected!
Comment: @filmor, no, I mean that if $arg(f(z))=teta$, then $arg(f(z^*))=-teta$, but that's right: i don't demonstrate anything, just say that it seems to work any time.
Comment: You are not only using $\arg(f(z)) = \theta \Leftrightarrow \arg(f(z^*)) = -\theta$ but also $|f(z)| = |f(z^*)|$ which is together (if I'm not mistaken) equivalent to $f(z)^* = f(z^*)$.
Comment: The identity $f(z)^* = f(z^*)$ holds if $f$ is entire and all of its Maclaurin coefficients are real, for instance.
Comment: @mfr, may be you should consider the following funtions: $f(z)=z+i$ and $f(z^*)=z^*-i$, so you get, for $abs(f(z))$ something like this: [plot on wolfram|alpha](http://www.wolframalpha.com/input/?i=plot+%28+%7Babs+%28+x+%2B+I*y+%2B+I+%29%2Csqrt+%28%28+x+%2B+I*y+%2B+I%29*%28+x+-+I*y-+I%29%29%7D++%2C+%7Bx%2C+-1%2C+1%7D%2C+%7By%2C+-2%2C+2%7D+%29)
Comment: yes, right @antonio. I suppose that the formulas work correctly for real-values coefficients of z...
Comment: No, they don't. The coefficients Antonio was talking about are a property of the function, not the parameter (the Maclaurin coefficients are the Taylor coefficients at zero, i.e. $a_n = \frac{\partial^n f(0)}{n!}$). This is quite a special set of functions, essentially all real analytic functions extended to the complex plane.
Comment: Eddy, what is your question? It would be great if you edited your post in a way we could quickly see what exactly you want in an answer.
Comment: @Ian, I would like to know if the set of formulas making use of $f(z)$ and $f(z^*)$ to extract complex components of functions are used in complex analysis, if there's any litterature or reference about their use.
Answer:
So, are these simple formulas using $f(z)$ and $f(z^*)$ to extract the
  complex components of functions known? Is there in complex analysis
  any litterature (sic) about?

Yes. When you have provided correct formulas, they are standard identities that can be found in introductory texts about complex numbers. You have written them in a form applicable to functions instead of complex numbers, and I believe you are asking if this is a heretofore unknown way of writing formulas for complex functions. However, I think you should note that note that for a fixed $z\in \mathbb{C}$, $f(z)$ is just another number in $\mathbb{C}$. If a formula holds for an arbitrary complex number $z$, then since $f(z)$ is also a complex number, the formula will hold for that number too. You have applied known identities to about complex numbers to complex functions, but $f$ maps $\mathbb C$ to itself, so you're still talking about known identities on $\mathbb C$.
To see this, think of defining a new complex variable, $y=f(z)$. Now rewrite all the functional identities you presented in this new variable (i.e. replace $f(z)$ with $y$ wherever you see it), and you've recovered the original, known identities, except you've replaced $z$ with $y$. What's the fundamental difference between $y$ and $z$? They both represent arbitrary numbers in the complex plane. The point is that since $f(z)\in\mathbb C$, $y\in\mathbb C$, and $z\in\mathbb C$, you can write the identities, which are properties of any numbers in $\mathbb C$, in terms of any of these you like. All these representations are valid. Sets of formulas in terms of complex functions may not appear explicitly in the literature, but because complex functions are complex numbers for all their arguments, you can freely replace $z$ by $f(z)$ in the formulas. They both represent arbitrary numbers in $\mathbb C$ and the formulas naturally still hold.
Comment: Eddy, I read through some of your posts, and commend you for discovering so much about complex analysis with little formal training. If you want to delve deeper, I could suggest you look into any introductory textbook about complex numbers or complex analysis. I like this one for free: http://people.math.gatech.edu/~cain/winter99/complex.html
Comment: thanks you for the link! Indeed, i'm a graphist, not a mathematician...
Comment: but I use the formulas, and as so far, it works well. But I think that the problem is that one should prove that if $\arg(f(z))=\theta$ then $\arg(f(z^*))=-\theta$, and as many comments point out, this may only be true for real-valued fonctions (or series). but choosing $f(z)^*$ instead of $f(z^*)$ should work fine?
Comment: Yes $f(z)^*$ in place of $f(z^*)$ in your formulas is the most general form. This follows directly from formally substituting $z\rightarrow f(z)$. For real valued functions, you have $f(z^*)=f(z)^*=f(z)=\Re(f(z))$, which gives the formulas you provided.
Answer: You will, in fact, need to use $f(z)^*,$ instead, as pointed out in the comments, since (in general) $f(z^*)$ need not be identically equal to $f(z)^*$.
In point of fact, if $f:\Bbb C\to\Bbb C,$ then one necessary condition to have $f(z^*)=f(z)^*$ is that $f$ be a real-valued function when restricted to the reals. Indeed, if there is some real $r$ such that $f(r)=w$ for some $w\in\Bbb C\setminus\Bbb R,$ then $$f(r^*)=f(r)=w\ne w^*=f(r)^*.$$
Antonio Vargas points out that an entire function with all Maclaurin coefficients real satisfies the desired property, but there are other functions that do the trick and aren't even holomorphic, such as $f(z)=\frac12(z+z^*).$


If voltage only affects the volume of the sound wave on an analog signal, what represents the actual sound?

Question: Suppose I were to light up a small LED using a potentiometer. It would range from completely off to a maximum voltage or brightness or "loudness".
Guitars works similar. An analog signal carries a certain voltage, but to my understanding voltage on its own only represents the guitars loudness.
What then, is used to represent the actual frequencies of the sound being produced, seeing how voltage appears to only relate to "loudness"?
Comment: "What then, is used to represent the actual frequencies": well, the [frequency](https://en.wikipedia.org/wiki/Frequency) of the electric signal ;).
Comment: Be careful about confusing voltage, which is amplitude, with power, which is related to voltage-squared.
Comment: Related, you might enjoy reading Wait But Why's article about what sound (pressure waves) actually is: https://waitbutwhy.com/2016/03/sound.html
Answer: While the average RMS voltage represents the average volume, what we hear is our brain's interpretation of the spectral content of the signal. What is that? Let's take a look.
I fired up Audacity, and recorded myself playing an F major triad on a recorder. What do we see when we do that?

Right away, we can see 4 notes F4, A4, C5, F5, of varying volume. The last note has a larger height, as it required a bit more air and so it was louder. So the thickness of those blobs represents the volume, and if I was pumping this signal out to a speaker, would be proportional to the average voltage. But let's zoom in a bit more on that last note and see what's happening:

We can see that F5 isn't just a solid blob, but the signal actually cycles back and forth the whole time. Let's zoom in just a little bit more:

This graph essentially shows the movement of air molecules over time. Back and forth, vibrating. It looks a lot like a sine wave. If we measure how many times that peak to peak repetition occurs per second, we'll find out the fundamental frequency. That fundamental frequency is the pitch we hear. In the case of this recording, it's about 697 Hz. F5 for an A440 tuning is 698.46 Hz, so I'm playing just a hair flat.
But, there is more to what we hear than just 697 Hz, after all, we can tell the difference between different instruments. Earlier I said it looks like a sin wave, but it in fact isn't. Or at least, it isn't just a single sine wave. To illustrate, let's see what happens if I pluck a guitar string instead of playing the recorder:

What we can see here, is a dramatically different shape to the repeating signal. We can hear that difference in the waveform's shape, because it has a different spectral content.
Mathematically, every repeating signal can be represented by the sum of an infinite number of perfect sine waves, with varying amplitude at each frequency. This is the spectral content that I mentioned at the beginning of my answer. When we play a note on an instrument, the fundamental frequency will have the largest amplitude, and we'll see large amplitudes at several harmonics, or multiples of the fundamental, and we'll usually see a bit of non-harmonic content as well. The distribution and proportion of that spectral content is what we hear as timbre*. Your brain does this when it interprets the signals from your cochlea. When a sound has a lot of high-frequency components, we hear that as tinny or metallic sounding. Drum sounds often have a much flatter harmonic response with significant non-harmonic components. Electrified instruments can have bizarre spectral profiles which makes distorted guitars and other unique sounds possible that aren't possible with purely acoustic, physical devices. Let's look at some of these in particular.
First the recorder:

And the guitar:

Looking at the guitar spectral analysis, we can see significantly more high-frequency components than the recorder, reflective of the metallic sound of its steel strings. The recorder has a much different overtone profile of odd-numbered harmonics, which leads to its "pure" sound. Every instrument will have a different profile on these frequency analysis graphs. Some instruments, the profile will also change from low notes to high notes, in ways beyond just sliding left or right on the horizontal scale, while others will stay relatively consistent.
Lastly, just for fun, let's look at what happens when I play a C Maj chord on the guitar:

What is that? That looks pretty bad. How are we supposed to make sense out of that, where is the the fundamental? Well, the isn't really one, as I'm playing a chord. We have 3 notes speaking, and so we have three of those waveforms piled on top of each other. When some notes are tying to move up, others are moving down, and back and forth, and different frequencies, making that chaotic shape. However, our brains are able to make sense of that and can parse out the frequency components. Let's look at the spectral content:

We can see three fundamentals at 264, 330, and 393 for just about C4, E4, and G4 respectively. The overall profile is pretty similar to the single note as well, but we have groups of three for each harmonic, because of each string vibrating.
*So, timber represents the qualitative aspect of the sounds, some of which is shown here by its volume, its pitch, and the spectral content. But there is more to what makes a sound a sound. I was looking at these signals from a steady state perspective, during a sustained note. But the full experience includes the beginning, middle, and end. The sound you hear varies with time after the note is played, (e.g. the sound of the guitar pluck vs the sustain), how quickly the sound dies off, sometimes it changes pitch while sounding out, such as vibrato. There are a lot of aspects that can be modeled, but I think my answer here covers the main aspects.
Comment: Absolutely correct!   But perhaps a little overwhelming for the level of the question?
Comment: Perhaps, but as someone who is a scientist (even though a computer scientist) and degreed engineer, I strongly appreciated the detail!
Comment: As a physics and mathematics nerd I totally enjoyed reading this. My only gripe is the lack of rectangular and sawtooth waves.
Answer:
supposed I were to light up a small LED using a potentiometer, it would range from completely off to a maximum voltage or brightness or "loudness".

Loudness of a sound doesn't relate to how big the voltage is, but across what range the voltage is changing.
Let me put that another way: A very big constant voltage won't relate to 'very loud' - it will represent silence. Sound is all about vibrations and waveforms - pressures (in air) or voltages (in a circuit) that change over time.
Any real physical object that makes a sound does so by vibrating. If we want to represent that vibration in an electric circuit, then the voltage will represent where the object is at a given point in time. A moment later, the voltage will have changed according to where the object has moved to.
So the instantaneous voltage in a circuit does not relate to loudness. However, the range of voltage over a period of time usually does correspond to loudness.
Comment: Well, this is correct, but let me add a bit about constant voltage.  The *power* delivered goes as  voltage-squared.  It's only when we dump current into an electromagnet or other inductive (or capacitative) device that  a **changing** voltage is required to implement motion, said motion leading to a variation in air pressure.  I agree that sound is dependent on delta-pressure, so your answer is correct in that sense.  A DC current would be more like going into a hyperbaric chamber.
Answer: Yes, at any given instant an audio signal will have a certain voltage.   That voltage would push the cone of a loudspeaker out just SO much.   And if that voltage persisted, the cone would stay in that same position and there would be no sound.
But an audio signal exists in time.    At THIS instant it has THIS voltage.  At the next instant, a different voltage.  The speaker cone moves from one position to another, following the ever-changing voltage.  Keep changing voltage at short time intervals, it vibrates.  And that's sound!
Answer: A changing momentaneous voltage can perfectly well represent an (monaural) acoustic signal, just like the changing momentaneous position of a speaker cone (which tends to follow the voltage at the speaker in a certain manner) can represent/reproduce an acoustic signal.
Comment: @CarlWitthoft https://www.merriam-webster.com/dictionary/momentaneous
Comment: @BenMiller-RememberMonica I stand corrected!  And amazing: been in use since the 15th century and all this time I never noticed.
Comment: ummm.. "momentaneous" ?  no such word


uiactionsheet height

Question: I've a simple question on UIActionSheet! how do I set the height of UIActionsheet? I've tried setFrame and setBounds but nothing is working. I'm using following action sheet:
NSString *title = UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation) ? @"\n\n\n\n\n\n\n\n\n" : @"\n\n\n\n\n\n\n\n\n\n\n\n" ;
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:[NSString stringWithFormat:@"%@%@", title, NSLocalizedString(@"", @"")]
                                  delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Button1",@"Button2", nil];
    [actionSheet setTag: 1];
    //[actionSheet setBounds:CGRectMake(0,0,320,150)];
    //[actionSheet showFromRect:CGRectMake(0,0,100,50) inView: self.parentViewController.tabBarController.view animated:YES];
   // [actionSheet setFrame:CGRectMake(0, 30, 320, 30)];
    actionSheet.actionSheetStyle = UIActionSheetStyleAutomatic;
    [actionSheet showInView:self.parentViewController.tabBarController.view];
     actionSheet = nil;

my problem here is action sheet height is equal to current view's height. I would like to auto adjust the height based on the contents of the UIActionSheet.
Thanks in advance,
Answer: UIActionSheet's default behavior is to auto-adjust to its content size. You shouldn't ever set the frame directly.
You're seeing the action sheet take up so much room because you're inserting a bunch of newline characters into the title, forcing the title label to take up more vertical space than it should. If you don't want the action sheet to be that tall, don't hack the title like that.
Comment: @RamaBoya, no problem. At least you included the newlines in the question... Otherwise it would have been impossible to answer.

uiactionsheet height


how to duplicate a form action programatically

Question: when a form action takes place, it posts the fields and also redirects to that page, right?  I need to make a custom form do the same, I have successfully made it post the fields in my drupal 8 custom module , using an http request with guzzle, but how do i make it redirect simultaneously as well?
Comment: I'm voting to close this question as off-topic because it is about code the OP wrote but that isn't shown. For questions about code, we expect the question to show the code.
Answer: In your submit handler:
$form_state->setRedirect($route_name, $parameters, $options);

Or if you have a URL object:
$form_state->setRedirectUrl($url);

Reference:

FormState::setRedirect
FormState::setRedirectUrl
Comment: Something like `$url = \Drupal\Core\Url::fromUri('http://google.com');`
Comment: Hi thanks, if I just have the URL as a string, what parameters and options do I have to put in?
Comment: I gott this error Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it.
Comment: Oh yeah, I forgot about the unwilling API. See this comment: https://www.drupal.org/node/2599342#comment-10484496 for a code example, but read the rest of the issue for context too
Comment: I tried this but my response is a guzzle object, so it doesnt like it $form_state->setResponse($response);
Comment: TypeError: Argument 1 passed to Drupal\Core\Form\FormState::setResponse() must be an instance of Symfony\Component\HttpFoundation\Response, instance of GuzzleHttp\Psr7\Response given,
Comment: Don't use the guzzle response, create a new response per the examples in the linked issue
Comment: But I need a guzzle response to get the form fields over there.  how can I do both?
Comment: Sorry I don't understand the question. The guzzle request/response is not related to the Drupal response, they're completely separate
Comment: Oh ok so I can do both ?
Comment: Yes, see the comments above
Comment: I'm having trouble understanding what the example code you are referring to is, is it this ?   if (!$form_state->getResponse() && $redirect = $this->redirectForm($form_state)) {
      $form_state->setResponse($redirect);
    }


ESMTP Postfix Server - prevent overriding Message-ID

Question: in our CRM-System I have to identify every incoming E-Mail by the Message-ID, with that ID I can check if I already have a related E-Mail in the System.
Now, it seems that my Postfix Server every time overrides my generated Message-ID.
Is there any configuration to prevent the server overriding the Message-ID ?
I tested it with a google Account and the Google Server is not overriding the ID.
Answer: By default, Postfix ONLY adds a message-id header when there's none.
Without seeing
<code>postconf -n
</code>
output it's hard to tell.
There might be a header_checks entry that strips the Message-Id using a regular expression, but one wouldn't usually forget such a thing.


Showing that this set is closed or open in $\mathbb{R^d}$

Question: Show that the set is closed or open in $\mathbb{R^d}$
(a) d=3 S={${(x,y,z) \in \mathbb{R^3} | -1/2 \leq cos(yz) }$}
Ways to prove this in my toolkit:
Proof by showing a function is continuous iff for every closed set $K \subseteq \mathbb{R^n} $, $f^{-1}(K)$ is also closed.
Proof by showing that a closed set must contain all of its limit points (I'm fuzzy as to how to do this)
So trivially I can't prove this by the continuity property, so I must instead rely on the limit point property.
So I was thinking that since R is dense, the limit points of cos(yz) are all points on the range of the function [-1,1] so S cannot be closed since it does not contain all limit points. I don't know how I'd prove this though? If someone could suggest a book or series to learn proof methods and how to make proving things in general more intuitive that would be really nice.
Answer: The best way to prove that the set is closed is to note that the function $f(x,y,z)=\cos (yz)$ is continuous (becasue composition of continuous maps is continuous) and the given set is nothing but $f^{-1} [-\frac 1 2 ,\infty)$.
Answer: Take a sequence $a_n=(x_n,y_n,z_n) \in \S$ such that $a_n \to (x,y,z)$ in $\Bbb{R}^3$ with the usual metric.
We have then that $$x_n \to x$$ $$y_n \to y$$ $$z_n \to z$$
Then $z_ny_n \to zy$
Use  continuity of $\cos{x}$  and then you will have the conclusion


I have to export the path everytime I return to mac terminal?

Question: I am using expo-cli and when i close my terminal and return back everytime I have to type command export PATH="/usr/local/Cellar/node/8.9.2/bin:$PATH".Path is where my expo-cli is installed. I have also added the path at the bottom of the file that opens on ~/.bash_profile.
Answer: The expo-cli requires node and it is not on your default PATH. Homebrew links binaries to /usr/local/bin from the Cellar by default.

Check brew --prefix to be certain Homebrew is rooted @ /usr/local.

Your best options are:

Modify the PATH environment variable, like you are doing, in your ~/.bash_profile or another bash startup file (e.g. /etc/profile).
Since you are on a Mac, you can modify your PATH globally by adding /usr/local/bin to /etc/paths or by adding /usr/local/bin to an arbitrary file inside /etc/paths.d.


Is there any way to get exact match in elasticsearch

Question: match_phrase in query parameter is matching the string partially.
eg: if my match_phrase query for 'Status' is 'rejected' then it is also matching the 'rejected-qc'. like this:
<code>{
  "query": {
    "bool": {
      "should": [
         {
            "match_phrase": {
               "Status": "rejected"
            }
         }
      ],
      "minimun_should_match":1
    }
  }
}
</code>
and the response I get for above query is two value with status as 'rejected' and 'rejected-qc', but I only want 'rejected' one - the exact match.
if I'm trying to use 'FILTER' instead it is throwing an error as following:
<code>"root_cause": [
   {
     "type": "parsing_exception",
     "reason": "unknown query [filter]",
     "line": 1,
     "col": 272
   }
],
</code>
my payload for above error is:
<code>{
  "query": {
    "bool": {
      "should": [
         {
            "filter": {
                "term": {
                   "Status": "rejected"
                }
            }
         }
      ]
    }
  }
}
</code>
can anybody suggest a solution for this, that how can I match the exact string?
Thank you :)
Answer: You're almost there, simply like this:
<code>{
  "query": {
    "bool": {
      "minimum_should_match": 1,
      "should": [
            {
                "term": {
                   "Status1": "rejected"
                }
            },
            {
                "term": {
                   "Status2": "rejected"
                }
            },
            {
                "term": {
                   "Status3": "rejected"
                }
            }
      ]
    }
  }
}
</code>
Comment: You need to change the field names to match yours of course, it's just an example if you need several matches where at least one should match
Comment: please share your mapping and a sample document you'd like to match
Comment: Yep, hence why I was asking for your mapping ;-) Glad you figured it out
Comment: Just like 'minimum_should_match' for 'should', is there any field for filter?? If yes then please share it. I must use something like that. because there will be multiple status and i will have to match one of them.
Comment: It is giving me no data at all.
Comment: Yes i know that, but after adding 'term' key as you described it is fetching no data.
Comment: Thank you for you help! I found the solution, all I had to do was use 'Status.keyword' instead of 'Status'
Answer: All I had to do to match the exact string is to append '.keyword' after the 'status'. like this:
<code>{
  "query": {
    "bool": {
      "should": [
         {
            "match_phrase": {
               "Status.keyword": "rejected"
            }
         }
      ],
      "minimun_should_match":1
    }
  }
}
</code>
And it will match the string exactly and not partially!


Problem with db_select not returning records sometimes

Question: Works:
<code>$rows = db_select('notification_queue', 'nq')
    fields('nq', array('created_time', 'uid', 'notification_type', 'delivery_method','latest_time', 'earliest_time'))
    ->groupBy('uid')
    ->groupBy('notification_type')
    ->groupBy('delivery_method')
    ->addExpression('COUNT(*)', 'count')
    ->execute();
</code>
Does not work:
<code>$rows = db_select('notification_queue', 'nq');
$rows->fields('nq', array('created_time', 'uid', 'notification_type', 'delivery_method', 'latest_time', 'earliest_time'));
$rows->groupBy('uid');
$rows->groupBy('notification_type');
$rows->groupBy('delivery_method');
$rows->execute();
</code>
I'm testing that something is returned with a simple foreach loop:
<code>foreach($rows as $row) {
    msg($row); //msg is a simple wrapper for drupal set message
}
</code>
The reason I need to do things the second way is that I have to use addExpression and it won't work if try and use it in the first way.
I've tried this:
<code>$rows = db_select('notification_queue', 'nq');
$rows->fields('nq', array('created_time', 'uid', 'notification_type', 'delivery_method', 'latest_time', 'earliest_time'));
$rows->groupBy('uid');
$rows->groupBy('notification_type');
$rows->groupBy('delivery_method');
$rows->addExpression('COUNT(*)', 'count');
$rows->execute();
</code>
And I've checked that the resulting query is correct (it is, I've tried using it with MySQL directly and it does exactly what I want). However, I can't get access to the rows using Drupal.
What am I doing wrong?
Answer: Turns out addExpression does not return the object, just the alias of the expression. Solution:
<code>$query = db_select('notification_queue', 'nq')
    ->fields('nq', array('created_time', 'uid', 'notification_type', 'delivery_method', 'latest_time', 'earliest_time'))
    ->groupBy('uid')
    ->groupBy('notification_type')
    ->groupBy('delivery_method');

$query->addExpression('COUNT(*)', 'num');
$rows = $query->execute();
</code>
Comment: ...answering your own question? NOOB! Do you even know what DRUPAL stands for?
Comment: `$rows = $query->execute();` is the key there


Time Series Forecast - Evaluating accuracy

Question: I am very new to R and the forecast package authored by Rob Hyndman.
I am working on a time series with 24 samples per hour. I trained a random forest regressor to forecast 6 hour ahead values and am using MAPE(Mean Absolute Percentage Error) on a held out duration as the accuracy metric.
I want to compare its accuracy with standard time series methods like ARMA and ARIMA models.
Time Series Sample

Here is what I have currently. data.csv has 576*16(16 days worth) samples and I wish to measure forecast accuracy on last 3 days.
library(forecast)
pv_data = read.csv("data.csv", header=FALSE)
pv_ts <- ts(pv_data$V2)
train_ts <- window(pv_ts, end=576*13)
test_ts <- window(pv_ts, start=576*13+1)
fit <- auto.arima(train_ts)
accuracy(forecast(fit, h=576*3), test_ts)

This gives me MAPE  which is average of h = 1 to 576*3 samples ahead point forecast absolute errors.
Question: How to find the average of h=144 ahead forecast absolute percent error of the estimates of samples in test_ts? Specifically, how to calculate $ \frac {\sum\limits_{T=576*13-h}^{576*16-h} \left\lvert \tfrac{\hat{e}_{T+h}}{y_{T+h}}\right\rvert }{576*3}$ with h=144 where  $\hat{e}_{T+h}=\hat{y}_{T+h | T}-y_{T+h}$?
Comment: Post the data...
Comment: @TomReilly Created a gist. Please see the update.
Comment: What is your question?
Comment: @RichardHardy updated the question.
Answer: I'm not really sure what you're trying to achieve here. The forecast at h=144 is just a point estimate whereas the MAPE is a measure of average accuracy over a selection of point forecasts.
As in your case, the sequence of point forcasts from h=1 to h=576*3is used to calculate the MAPE in your current example. If you want to evaluate the accuracy of your 6-hour ahead forecast, why not just look at the forecast error? I.e. $\hat{e}_{T+h}=\hat{y}_{T+h | T}-y_{T+h}$
EDIT: Added a rough outline to a solution of what I think is your problem. You mention calculating the "average" for h=144 but the average is equal to the point estimate because you only have one forecast at this particular horizon.
library(forecast)
pv_data = read.csv("data.csv", header=FALSE)
pv_ts <- ts(pv_data$V2)
train_ts <- window(pv_ts, end=576*13)
test_ts <- window(pv_ts, start=576*13+1)
fit <- auto.arima(train_ts)

#Store point forecasts
fc <- forecast(fit, h=576*3)$mean

# Store actual outcome
y <- window(pv_ts, start=576*13+144, end=576*13+144)

# Store point forecast for h=144
y_hat <- fc[144]

# Calculate ape at h=144
ape <- abs((y_hat-y)/y)

Comment: I want to average `h=144` ahead forecast absolute percent error of the estimates of samples in `test_ts`. Specifically calculate $ \frac {\sum\limits_{T=576*13-h}^{576*16-h} APE(\hat{e}_{T+h})}{576*3}$ with `h=144`. I am not sure how to do that cleanly in R.
Comment: I updated the question to make it clear. Please take a look.
Comment: So you want to calculate the MAPE from  `h=1` to `h=144` ? Or do you want to calculate $\left|\frac{(\hat{y}_{T+144 | T}-y_{T+144})}{y_{T+144}}\right|$? I'm still not sure what you're trying to achieve.
Comment: I want to calculate MAPE only for `h=144` which is the average of $\left|\frac{(\hat{y}_{T+144 | T}-y_{T+144})}{y_{T+144}}\right|$
Comment: Updated answer to what I think you want to do. However, like I mention, calculating the average of $\left|\frac{(\hat{y}_{T+144 | T}-y_{T+144})}{y_{T+144}}\right|$ doesn't make any sense because this is just one number.
Comment: Once we fit an ARIMA model, we get the coefficients and the number of times to difference. Using these we can get 144 steps ahead forecasts for all samples in test_ts. For example use only true samples till T=576*13-144 to get a estimate(forecast) for T=576*13 sample. Use true samples till T=576*13-143 to get an estimate for T=576*13+1 sample and so on. Once we have such h=144 steps ahead forecast estimates for all samples in test_ts using coefficients of our arima model, I want to calculate the MAPE of those estimates. I think the equation in the question matches my description here.
Comment: Okay, so what you really want to do is "rolling/recursive window estimation" and calculate the MAPE for the sequence of `h=144`forecasts from the different windows? This is significantly more complicated and probably more suited for stack overflow. I can point you to a [function](https://github.com/MathiasModin/Econometrics/blob/master/RollingWindow.R) I have written for this purpose. Have a look at the function `r.arima()` in there. It might do what you want. Let me know if you want a brief explanation of how it works.


Vue how to override css styles for element-ui

Question: I'm trying to override the background color on the input box from element-ui
but never worked
<template>
<el-input v-model="form.text" type="text" clearable></el-input>
</template

base on the information I gathered from google
chrome dev tool snapshot
Comment: Try without the `scoped` attribute
Comment: as @PierreSaid , scoped does some magic to your css to scope it to the component, but you don't want that, you are wanting to style it without the scoping
Comment: Thanks guys, this has been bothering me for hours! @KeithNicholas
Comment: This changes the elementUI input globally for the entire application, not just in your component though. If that's intended I'd prefer to put those changes in a separate main.css file instead of hiding them away in a component style tag. If it's intended to change this inputbox only for this component, you'll have to leave `scoped` in and override the specificity of the original `.el-input__inner` class, for example by `!important!` or doubling (`.el-input__inner.el-input__inner`).
Comment: If you want to use scoped styling the most proper way to do this us using deep selectors: https://stackoverflow.com/a/57704482/575468
Answer: First option:
Try to override
.el-input__inner {
    background-color: #f4f4f4 !important;
}

Second option:
Create a seperate css file which is loaded in after the element-ui does.
Answer:
Open element.js in the plugins folder.
Add import your styles after element-plus, like this:

import ElementPlus from "element-plus";
import "../element-variables.scss";
import "../assets/styles/global.scss"; // our custom styles

export default (app) => {
  app.use(ElementPlus);
};


detail: "CSRF Failed: CSRF token missing or incorrect."

Question: I have used window.CSRF_TOKEN = "{{ csrf_token }}" inside script tag in restaurant_detail.html where my react page for posting review is rendered. I am getting an error, though. In my onSubmit function i have consoled to check if csrf token is passed or not and yes it is.
my axios code for posting review is
onSubmit(props){
        console.log('csrf',CSRF_TOKEN);
        axios({
            method:'POST',
            url:'/api/review/create/',
            headers:{
                'X-CSRF-Token':CSRF_TOKEN,
                //'Access-Control-Allow-Origin':'*',
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            data:{
                review:props.review
            }
        })
        .then(response => {
            console.log('success');
        })
        .catch(error => {
            throw("Error: ",error);
        });
    }

api/Views.py
class ReviewCreateAPIView(CreateAPIView):
    queryset = Review.objects.all()
    # permisssion_classes = [IsAuthenticated]

    def get_serializer_class(self):
        model_type = self.request.GET.get('type')
        slug = self.request.GET.get('slug')
        parent_id = self.request.GET.get('parent_id')
        return create_review_serializer(model_type=model_type, slug=slug, parent_id=parent_id, reviewer=self.request.user)

serializers.py
def create_review_serializer(model_type='restaurant',slug=None, parent_id=None, reviewer=None):
    class ReviewCreateSerializer(ModelSerializer):
        class Meta:
            model = Review
            fields = ('id','review','created',)

        def __init__(self, *args, **kwargs):
            self.model_type = model_type
            self.slug = slug
            self.parent_obj = None
            if parent_id:
                parent_qs = Review.objects.filter(id=parent_id)
                if parent_qs.exists() and parent_qs.count() == 1:
                    self.parent_obj = parent_qs.first()
            return super(ReviewCreateSerializer, self).__init__(*args, **kwargs)

        def validate(self, data):
            model_type = self.model_type
            model_qs = ContentType.objects.filter(model=model_type)
            if not model_qs.exists() or model_qs.count() != 1:
                raise ValidationError('This is not a valid content type')
            SomeModel = model_qs.first().model_class()
            obj_qs = SomeModel.objects.filter(slug=self.slug) # Restaurant.objects.filter(slug=self.slug)
            if not obj_qs.exists() or obj_qs.count() != 1:
                raise ValidationError('This is not a slug for this content type')
            return data

        def create(self, validated_data):
            review = validated_data.get('review')
            print('review',review)
            if reviewer:
                main_reviewer = reviewer
            else:
                main_reviewer = User.objects.all().first()
            model_type = self.model_type
            slug = self.slug
            parent_obj = self.parent_obj
            review = Review.objects.create_for_model_type(model_type, slug, review, main_reviewer, parent_obj=parent_obj)
            return review

    return ReviewCreateSerializer

urls.py
url(r'^create/$', ReviewCreateAPIView.as_view(), name="reviewcreateapiview"),

restaurant_detail.html

How can i resolve this?
Answer: You have done a simple error. There is a typo. Do replace

'X-CSRF-Token'

to

'X-CSRFToken'

if you have code correctly, then it should post your data.
Comment: Oh yes! It really solved the issue. Thanks for the answer.
Answer: you have to set the header in ajax call with cookie values.
$.ajaxSetup({
 beforeSend: function(xhr, settings) {
     function getCookie(name) {
         var cookieValue = null;
         if (document.cookie && document.cookie != '') {
             var cookies = document.cookie.split(';');
             for (var i = 0; i < cookies.length; i++) {
                 var cookie = jQuery.trim(cookies[i]);
                 // Does this cookie string begin with the name we want?
                 if (cookie.substring(0, name.length + 1) == (name + '=')) {
                     cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                     break;
                 }
             }
         }
         return cookieValue;
     }
     if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
         // Only send the token to relative URLs i.e. locally.
         xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
     }
 }
});

Comment: But i am using axios. Do i have to do the same for axios?
Answer: I'm not familiar with axios,but I solved a similar problem use the blow code with JQuery:
  $.ajaxSetup({
    data : {
        csrfmiddlewaretoken : '{{ csrf_token }}'
    },
});


$\frac{1}{e^x-1}$, $\Gamma(s)$, $\zeta(s)$, and $x^{s-1}$

Question: Just to give a few examples, we have that
$$\eqalign{
  & \int\limits_0^\infty  {\frac{{{x^{s - 1}}}}{{{e^x} - 1}}dx}  = \Gamma \left( s \right)\zeta \left( s \right)  \cr
  & \int\limits_0^\infty  {\frac{{{x^{s - 1}}}}{{{e^x} + 1}}dx}  = \left( {1 - {2^{1 - s}}} \right)\Gamma \left( s \right)\zeta \left( s \right) =\eta(s)\Gamma(s) \cr
  & \int\limits_0^\infty  {\frac{{{x^{s - 1}}}}{{{e^x}\left( {{e^x} - 1} \right)}}dx}  = \Gamma \left( s \right)\left( {\zeta \left( s \right) - 1} \right)  \cr
  & \int\limits_0^\infty  {\frac{{{x^{s-1}}{e^x}}}{{{{\left( {{e^x} - 1} \right)}^2}}}dx}  = \Gamma \left( {s } \right)\zeta \left( s-1 \right)\cr
& \int\limits_0^\infty  {\frac{{{e^x}{x^{s - 1}}}}{{{{\left( {1 + {e^x}} \right)}^2}}}}  = \Gamma \left( s \right)\eta \left( s-1 \right) \cr} $$
Is there any theory that enables us to state that any integral of the form
$$\int\limits_0^\infty  {F\left( {\frac{1}{{{e^x} - 1}},{e^x},{x^s}} \right)dx} $$
will necessarily be evaluated in terms of $\zeta$ and $\Gamma$?
Comment: How about the integral representation of Dirichlet L-functions?
Comment: @sos440 I'm not really into that theory, but if you want to give an answer in terms of that, I guess I can manage. I will only need you to think that it is absolutely new theory for me.
Comment: What about $\int_0^\infty \frac{\sqrt{x}\exp(-x)}{\sqrt[3]{\exp(x)-1}}\mathrm dx$?
Comment: I'm also unfamiliar to Dirichlet $L$-functions; All my relevant knowledge on this subject just amounts a one-semester-course lecture on analytic number theory. So I cannot explain a possible deep linkage between the integral representation and the corresponding number-theoretic facts. As I remember, these integrals can be generalized to represent the Dirichlet series of (completely) multiplicative arithmetic functions.
Comment: @J.M. What about it?
Comment: Peter: it looks to me that the integral I gave doesn't readily admit a representation like the one described in the OP.
Comment: @J.M. I see.The integral is around 0.79
Comment: @J.M. Just to be clear, I meant integral of $\exp x\pm 1$.
Answer: I can offer the following observation. Consider the following identities
\begin{align}
\frac{1}{e^{x} - 1} = \sum_{k \geqslant 0} e^{-kx}, \quad \frac{1}{e^{x} + 1} = \sum_{k \geqslant 1} (-1)^{k + 1} e^{-kx} \quad \text{and} \quad \int_{0}^{\infty} x^{s} e^{kx} \ d^{\times} x = \Gamma(s) \, k^{-s},
\end{align}
where $d^{\times} x = \frac{dx}{x}$ is the Haar invariant measure on $\mathbb{R}$. For $\mathsf{Re}(s) > 1$, $\mathsf{Re}(a) < 1$ and $a \not \in \mathbb{Z}$, one has
\begin{align}
\int_{0}^{\infty} \frac{x^{s} e^{a x}}{e^{x} - 1} \ d^{\times} x & = \int_{0}^{\infty} \sum_{k \geqslant 1} x^{s} e^{(a - k) x} \ d^{\times} x \\ & = \Gamma(s) \sum_{k \geqslant 1} (k - a)^{-s} \\ & = \Gamma(s) \zeta(s,1-a),
\end{align}
where $\zeta(s,1-a)$ denotes Hurwitz zeta function. Similarly, one has
\begin{align}
\int_{0}^{\infty} \frac{x^{s} e^{a x}}{e^{x} + 1} \ d^{\times} x & = \int_{0}^{\infty} \sum_{k \geqslant 1} (-1)^{k+1} x^{s} e^{(a - k) x} \ d^{\times} x \\ & = \Gamma(s) \sum_{k \geqslant 1} (-1)^{k+1} (k - a)^{-s} \\ & = \Gamma(s) 2^{-s} \left( \zeta(s,\tfrac{1-a}{2}) - \zeta(s,1 - \tfrac{a}{2}) \right).
\end{align}
The interchange of the summations and the integral sign is allowable since the summations are absolutely and uniformly convergent on their domains. These two formulas generalize the first two of your quoted formulas. The third one follows by splitting the integral into two using partial fractions and the integral formula of the Gamma function.
Comment: Thank you. This is good. If you can, try considering powers of $(e^x \pm 1)^{-1}$.


How to update or modify property file in web application

Question: I am able to load property file using InputStream but after modifying not able to update .
FileOutputStream output =
            new FileOutputStream("/src/main/resources/test.properties");
props.store(output, "Last Time the file have been modified at:");

How to update ? any suggestion...
Comment: Before continuing to post incomplete, unhelpful and overly generic answers (e.g. "Use Commons Configuration, blah blah" *without* explaining in any way how exactly it helps OP's concrete problem) in an attempt to collect some easy reputation, please be aware that OP is developing a Java EE web application and that the OP is essentially attempting to manipulate files in the deploy space (which he currently incorrectly assumes to be the IDE's project folder).
Comment: Its already asked just go through this you will have an idea http://stackoverflow.com/questions/7202765/how-to-update-a-property-file
Comment: Here is the sample for updating the property file http://www.drdobbs.com/jvm/readwrite-properties-files-in-java/231000005
Comment: Can this help : `FileOutputStream fos = new FileOutputStream (getServletContext().getRealPath("actual path under WEB-INF"));`   ?
Comment: You'd best not place the properties file inside the deployment archive if it needs to be updated.
Answer: It is difficult to be sure what you actually mean here, but it looks to me like you want your webapp to update a properties file that it read using getResource or getResourceAsStream.  This could be difficult to impossible, and it is definitely a bad idea.
The best idea would be to store the properties in tables in the webapp's database.  But if you don't have a database, then you could store the properties file somewhere in the file system ... provided this is allowed.
The only file system that is guaranteed to exist and to be writable to a webapp is its temporary filespace:  https://stackoverflow.com/a/2663250/139985.  But of course if you get to choose and configure the web container and / or the host operating system, you could find other (container / OS specific) places to store state that is less temporary.  The catch is that your solution is liable to be non-portable.
Comment: I didn't say it was bad to use `getResourceAsStream`.  I said it was a bad idea to try to update it.  And that's because the place (file, JAR, whatever) it is being read from is possibly read only ... and your webapp has no way of knowing.
Comment: Could you elaborate why is it a bad idea to use `getResourceAsStream`? Is it a bad idea due to its read-only capability?


Toggle CCK field visibility with CCK radio buttons

Question: I have a content type with three cck fields
1 radio button, 1 text field, and 1 integer field.
What I am trying to do is by default have the text field and integer field hidden, and only show them dependent on the state of the radio button.
Example:
Two radio buttons, one which says text and one which says integer.  When the text radio box is checked, then the text box shows and the integer box is hidden and vice versa.
Answer: There is a contrib module written for just this: Conditional Fields. Here is a quote about it (from the module's project page):

... allows you to manage sets of dependencies between fields. When a field is "dependent", it will only be available for editing and displayed if the state of the "dependee" field matches the right condition.
When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
You can, for example, define a custom "Article teaser" field that is shown only if a "Has teaser" checkbox is checked.
Comment: it work for me :) thanx
Answer: You can use client-side javascript for this. For example, the jQuery show/hide functions can be used to expose your text and integer fields depending on the value of the radio button.
Comment: any example site
Answer: If you're happy doing a very small amount of coding, then this can be achieved in a way that is far more lightweight than using the conditional fields module.
In a custom module you can implement hook_form_alter() or hook_form_FORM_ID_alter() and use the states api to add the visibility rules.  You don't actually need to program the logic for hiding / displaying the fields, just define which values to use:
<code>/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULENAME_form_CONTENTTYPENAME_node_form_alter(&$form, &$form_state) {
  $form['text_field']['#states'] = array(
    'visible' => array(
      ':input[name="radio_field"]' => array('value' => 'value_of_textfield_option'),
    ),
  );

  $form['integar_field']['#states'] = array(
    'visible' => array(
      ':input[name="radio_field"]' => array('value' => 'value_of_integarfield_option'),
    ),
  );
}
</code>


Populate a field based from value of body class value

Question: I am trying to populate a field in a form with a class from the body element, which starts "pageid-" and then has a number after it. I would like to find this number, and add it as the form value which enables me to use the same form on every page but identify which page the form was submitted on.
I am still learning Java/JQuery so apologies on not knowing how to return the value here. It's coming in as [object Object] - This is what I have currently:
HTML

<input type="text" id="test1" value="">

Javascript
var thisid = $('[class^="pageid-"]');

$(document).ready(function () {
    $("#test1").val( thisid );
});

http://jsfiddle.net/Gg6AG/44/
Comment: may be  $("#test1").val( thisid.className );
Comment: I would recommend to add the value as a data attribute instead of parsing it from the class (that is what this attributes are made for). the body would look like . This way you can have other classes in it. and you can retrieve object data with thisid.data("id")
Comment: @valarauko Sensible suggest dude yeah, hadn't thought of that either but I know data attribute is used more and more now and is very versatile.
Answer: I'd suggest:
$(document).ready(function(){
    // converts the classList - an Array-like list of class-names - of
    // of the  element/node into an Array; and then filters that
    // Array of class-names using Array.filter.prototype(), to retain
    // only those classes for which the inner comparison return true:
    var classValue = Array.from( document.body.classList ).filter(function(c){
        // 'c' (the first argument of the method) is the
        // array-element of the Array over which we're iterating
        // and is supplied by the Array method.

          // here we return only those class-names that have
          // a string of numbers ('\d+') before the end of
          // string ('$'), using RegExp.test() to return
          // a Boolean, true: the string matches the regexp,
          //            false: the string does not match:
                    return /\d+$/.test(c);

                // here we assume only one matching class-name,
                // and user Array.prototype.join('') to convert
                // that single-element array into a String
                // and split that class-name on the '-' character:
                }).join('').split('-')
                // and use Array.prototype.pop() to retrieve
                // the last element of the returned Array:
                .pop();

    // finding the element with the id 'test1' and setting
    // its value property to the found-value:
    document.getElementById('test1').value = classValue;
});

JS Fiddle demo.
Incidentally the reason that this:
$("#test1").val( thisid );

couldn't work is because thisid is a jQuery Object, and when you try to set a string value by passing an Object (an Object, not an object-property) the JavaScript engine will try to coerce that Object to a String representation, which will generate a value of [object Object], this can be verified with:
console.log({}.toString());

var obj = {};

document.querySelector('input').value = obj;

console.log(obj.toString());

<input />

or for a more comparative demonstration:
console.log($('body'));

var obj = $('body');

document.querySelector('input').value = obj;

console.log(obj.toString());

<input />
Comment: Thanks David, interesting way of doing it slightly differently. Looks fine on paper there but testing it seems to return no value for me. Perhaps I am missing something though :)
Comment: Sorry didn't see your comments, was too hasty with my reply. Will retest.
Comment: Created a fiddle with it David, not seeing anything returned still oddly http://jsfiddle.net/Gg6AG/505/
Comment: The problem was I rather foolishly used a reserved-word ('class') for a variable *and* I forgot to convert the Array to a String before calling `split()`. Belatedly corrected just now.
Comment: Thanks David, well documented. As the first answer is also correct I think it's fair to stick with it, but this is also a great and thorough alternative solution tested and working great.
Answer: Try this:
var thisid = $('[class^="pageid-"]');

$(document).ready(function () {
    var num = $(thisid).attr("class").split("-").pop(); // it will extract the number from class
    $("#test1").val( num ); // set that number to input field
});

Comment: Very nicely done dude, thank you so much. Will choose as answered when I am allowed - hopefully this will be of use to somebody else also! Interesting that you used `.pop()` and `.split()` would never have thought of that :)


Develop an app based on VSO API - Where can I find the database schema?

Question: I started to work in an app which displays data coming via VSO API. It seems I have to use lots of custom query following this method.
The only issue I faced so far is the lack of available database schema. Do you know where can I find it? I have googled around and people says that there is a reason why it is not published. I should not access it directly. I do not want it. But, it seems this is the only way I have to get the data structure I need.
At the moment, I'm installing a TFS on my local machine in order to dump out the schema and write my queries.
Comment: If you're using VS Team Services, you're not going to be able to access the database anyway. What are you actually trying to do?
Comment: Ahh, after install I realized that I might mixed up the database schema with the object model. I'll investigate a bit more the situation and I'll update my question with the result.
Answer: Ok, I do not need the database schema. The fact I can run a query (WIQL) a bit confused me, I thought it is direct access to database. But, after I have spent more time to investigate what I want and how TFS works, I realized that database schema is not needed.
Basically, I was looking for the information can be found here and here.


Prolog - Max value in recursion

Question: Hello I doing a work for school and I'm trying to get the max number that is returning by a recursion.
Let me explain better with examples:
I have this predicate:
li(_, []).
li(NAME, [H|T]) :-
   find(NAME, H, Occur),
   li(NAME, T).

li(NAME) :-
   findall(T, pri(name(T), _, _, _), Info),
   li(NAME, Info).

The predicate in line 2 (find), what it does is, by giving a name and some other information it will return to me a number (Occur). What I'm trying to do is to know what is the highets number (Occur) in the whole recursion.
Bellow I tried to do some comparations but it is not working, it says that Highest is not defined, I know that is becouse it don't have any value associated with it but I have not idea how to do this.
li(_, [], 0).
li(NAME, [H|T], Highest) :-
   find(NAME, H, Occur),
   li(NAME, T, Temp),
   Temp is Occur,
   Highest < Temp,
   Highest is Temp.

li(NAME) :-
   findall(T, pri(name(T), _, _, _), Info),
   li(NAME, Info, Return),
   write(Return).

The goal is to write the number in the end of line 3.
Does anyone know what I can do to fix this? Thank you.
EDIT
I gave another try and done this:
li(_, [], 0).
li(NAME, [H|T], Highest) :-
   find(NAME, H, Occur),
   li(NAME, T, Temp),
   Temp < Occur,
   Temp is Occur,
   Highest is Temp.

li(NAME) :-
   findall(T, pri(name(T), _, _, _), Info),
   li(NAME, Info, Return),
   write(Return).

It doens't trigger any errors but nothing happens, a false is returned and nothing is printed.
EDIT2
Thank to @David Tonhofer, I now can get the highst number. But what I realy want is the name that is associated with that hight number.
li(NAME, [H|T], Highest, X) :-
   find(NAME, H, Occur),
   li(NAME, T, Temp),
   Highest is max(Temp,Occur), X = ??.

I was going step by step and first trying to get the highest number then get the name, but with the MAX now I don't think I can know that.
At first I thought something like this:
li(_, [], 0).
li(NAME, [H|T], Highest, X) :-
   find(NAME, H, Occur),
   li(NAME, T, Temp),
   Temp < Occur,
   Temp is Occur,
   Highest is Temp, X is NAME.

li(NAME) :-
   findall(T, pri(name(T), _, _, _), Info),
   li(NAME, Info, Return, X),
   write(Return), write(X).

Answer: Here is a problem:
li(NAME, [H|T], Highest) :-
   find(NAME, H, Occur),
   li(NAME, T, Temp),
   Temp < Occur,
   Temp is Occur,
   Highest is Temp.

This means:

Make sure that Temp < Occur, backtrack to try something else if not.
Then unify the numeric values Occur and Temp. As Temp already contains some value, this is the same as testing whether Occur and Temp are the same value, and backtrack to try something else if not.
Then unify the numeric values Highest and Temp.

You seem to want Highest to take on the value of max(Occur,Temp).
In that case:
li(NAME, [H|T], Highest) :-
   find(NAME, H, Occur),
   li(NAME, T, Temp),
   Highest is max(Temp,Occur).

This

Computes the max(Temp,Occur) (works only if the values of Temp and Occur .are known at that point)
Unifies the result with Highest. If Highest is still a fresh variable, this is similar to assignment. Otherwise, if Highest already contains something, it is similar to comparison.

Addendum
To get the "Name" that is associated with the maximum value obtained, you proceed the same way:
li(Name_max, [H|T], Temp_max) :-
   find(Name_from_Head, H, Temp_from_Head),
   li(Name_from_Tail, T, Temp_from_Tail),
   % let's just print what we have right now:
   format("From the Head, we get: Name = ~w, Temp = ~w", [Name_from_Head,Temp_from_Head]),
   format("From the Tail, we get: Name = ~w, Temp = ~w", [Name_from_Tail,Temp_from_Tail]),
   % now a little "helper predicate" can be used for clarity
   % we pass it the 4 logical variables containing names and temps
   % and the 2 logical variables that have been given to "li/3"
   % to fill in with the best data:
   select_max(Name_from_Tail, Temp_from_Tail,
              Name_from_Head, Temp_from_Head,
              Name_max, Temp_max),
    % and we are done; just a printing before returning for fun
   format("Our current max: Name = ~w, Temp = ~w", [Name_max,Temp_max]).

% The helper predicate has two clauses for the two
% mutually exclusive alternatives
% (the "=:=" case is in the first clause, arbitrarily)

select_max(Name_from_Tail, Temp_from_Tail,
           Name_from_Head, Temp_from_Head,
           Name_from_Tail, Temp_from_Tail) :-
   Temp_from_Tail >= Temp_from_Head.

select_max(Name_from_Tail, Temp_from_Tail,
           Name_from_Head, Temp_from_Head,
           Name_from_Head, Temp_from_Head) :-
   Temp_from_Tail < Temp_from_Head.

For the helper predicate you could also write, perhaps more clearly:
select_max(Name_from_Tail, Temp_from_Tail,
           Name_from_Head, Temp_from_Head,
           Name_max, Temp_max) :-
   Temp_from_Tail >= Temp_from_Head, % Guard
   Name_max = Name_from_Tail,        % Constrain variables to be equal!
   Temp_max = Temp_from_Tail.

select_max(Name_from_Tail, Temp_from_Tail,
           Name_from_Head, Temp_from_Head,
           Name_max, Temp_max) :-
   Temp_from_Tail < Temp_from_Head,  % Guard
   Name_max = Name_from_Head,        % Constrain variables to be equal!
   Temp_max = Temp_from_Head.

Comment: hello, thank you for your replay, is working, didn't know that was possible like this. I tought only by comparing the values. I have the Highest but do you know how I can return the NAME that is associated with that number? I tought when comparing the numbers, when I get a bigger number I would change some variavle to the new name and in the end return it. I know that right know I dont have  a variable. But now using the max I can not see how to know wich NAME is associated. I'll edit the aswer.
Comment: @Rafael Updated! Please do  not forget to mark the question as answered if all is clear,
Comment: Hello, thank you for all your help. Realy nice explanation as well.
Answer: In SWI-Prolog, library(aggregate) is meant to provide an SQL-like solution for your problem:
?- L=[a:1, b:2, c:3], aggregate(max(V,N),member(N:V,L),Max).
L = [a:1, b:2, c:3],
Max = max(3, c).

Comment: @DavidTonhofer: your answer is so much instructive. I'm not enough fluent in English to explain like you're able to do. My answer could indeed be OT, since it doesn't mention recursion...

Prolog - Max value in recursion