Finding the least squares estimates of $β1$ and $β2$

Question: I am having trouble beginning the below question.
Suppose that $Y_1, Y_2, Y_3$ are uncorrelated random variables with common variance $σ^2$ and expected values $2β_1 + 2β_2$, $β_1 −2β_2$, and $2β_1 −β_2$, respectively. let $y_1,y_2,$ and $y_3$ be the realisations of $y_1, y_2, y_3$.
b) Find the least squares estimates of $β_1$ and $β_2$.
I am unsure as to begin this as a simple linear regression problem or a multiple linear regression problem.
Do I start with $Y_i = β_1 + β_2X_i + e_i$
Or $Y_i = β_0 + β_1X_i + β_2X_i + e_i$
Answer: I think you should list your model as $Y_i = β_1X_{i1} + β_2X_{i2} + e_i$ without a intercept. Your equations will look like:
$\begin{pmatrix}
Y_1\\
Y_2\\
Y_3
\end{pmatrix}=\begin{pmatrix}
2 & 2\\
1 & -2 \\
2 & -1
\end{pmatrix}\begin{pmatrix}
\beta_1\\
\beta_2
\end{pmatrix}+\begin{pmatrix}
e_1 \\
e_2\\
e_3
\end{pmatrix}$
You have your design matrix without intercept, otherwise you need a column of 1s then your expected values of $Y_i$ will have the formats $1*\beta_1+a*\beta_2$, $a$ can be different values.
The least square estimation of $\beta_1,\beta_2$ will be$(X'X)^{-1}X'Y$
Suppose you realization of $y_1, y_2, y_3$ is$(4,5,6)$
Then use the following R code you can calculate the least square estimate $\beta_1, \beta_2$
<code>X<-matrix(c(2,2,1,-2,2,-1),nrow=3,ncol=2)
Y<-matrix(c(4,5,6),nrow=3,ncol=1)
solve((t(X)%*%X))%*%t(X)%*%Y

 #       [,1]
 #  [1,]  2.65
 #  [2,] -0.15
</code>
Note I suppose your $e$ has a $N(0,\sigma^2)$ distribution.


Determine if $\|f\|=|\int_{0}^1 f(x) \ dx |$ defines a norm in $C([0,1]).$

Question:
Determine if $$\|f\|=|\int_{0}^1 f(x) \ dx |$$ defines a norm in $C([0,1]).$

Let $f,g \in C([0,1])$ such that $f\geqslant g$. Now $$\int_{0}^{1}f(x) \ dx \geqslant \int_{0}^{1}g(x) \ dx \Longrightarrow  |\int_{0}^{1}f(x) \ dx| \geqslant |\int_{0}^{1}g(x) \ dx| \geqslant 0$$ which gives positivity. Now take again $f,g \in C([0,1])$ $$\|f+g\| = |\int_{0}^1f(x)+g(x)  \ dx| \leqslant |\int_{0}^{1}f(x) \ dx| + |\int_{0}^{1}g(x) \ dx| = \|f\| +\|g\|.$$
is this enough to prove the result or am I missing some properties?
Comment: $\|f\|=0$ does not imply that $f=0$.
Comment: There is a lot of difference between $|\int_0^{1} f(x)dx|$ and $\int_0^{1} |f(x)| dx$.
Comment: If $\|f\|_p = (\int_{a}^{b} |f(x)|^p\,\mathrm{d}x)^{\frac{1}{p}}$ defines a norm on $C([a,b])$ how come this doesn't work? Isn't this just $p=1$? This should be defined for $p \geqslant 1$.
Comment: Please [don't use `\frac` in exponents or limits of integrals](//math.meta.stackexchange.com/a/5057/290189). It looks bad and confusing, and it rarely appears in professional mathematics typesetting.
Answer: No.  Take $f:x \mapsto x - 0.5$ as an example.  $\int_0^1 f = 0$, but $f \not\equiv 0$.


How to call a function in a Twig file

Question: Let's say I create a function in a module file:
function _get_test() {
  return 'test';
}

How can I call this in any Twig file? For example *.html.twig, page.html.twig, node.html.twig etc.
OR
How can I pass a variable from PHP to Twig and display in any Twig file.
For example *.html.twig, page.html.twig, node.html.twig etc.
Answer: You can define your own custom Twig functions in a custom module (but not in a theme). To find an example for how to do this, see this example in core/modules/system/tests/modules/twig_extension_test/src/TwigExtension/TestExtension.php.

Also see this blog post: Create Twig extensions for Drupal 8.

In this example, we will build an extension to display a Drupal block
  directly in a Twig template:
{{ display_block('my_block_id') }}

src/MyTwigExtension.php
<?php

namespace Drupal\MyTwigModule;

/**
 * Class DefaultService.
 *
 * @package Drupal\MyTwigModule
 */
class MyTwigExtension extends \Twig_Extension {

  /**
   * {@inheritdoc}
   * This function must return the name of the extension. It must be unique.
   */
  public function getName() {
    return 'block_display';
  }

  /**
   * In this function we can declare the extension function
   */
  public function getFunctions() {
    return array(
      new \Twig_SimpleFunction('display_block',
        array($this, 'display_block'),
        array('is_safe' => array('html')
      )),
  }

  /**
   * The php function to load a given block
   */
  public function display_block($block_id) {
    $block = \Drupal\block\Entity\Block::load($block_id);
    return \Drupal::entityManager()->getViewBuilder('block')->view($block);
  }

}

src/MyTwigModule.services.yml
services:
  MyTwigModule.twig.MyTwigExtension:
    class: Drupal\MyTwigModule\MyTwigExtension
    tags:
      - { name: twig.extension }

Answer: You do not call PHP functions in Twig. You can either create a custom Twig extension (see answer from leymannx) or use the global preprocess
function MYTHEME_preprocess(array &$variables, $hook) {
  //this is a global hook, its variables are available in any template file
  $variables['foo'] = 'bar';
}

{{ foo }} will then render bar, but this global preprocess might run into caching problems though
Comment: @leymannx I'm explicitly using the one without _HOOK suffix as *global* preprocess, the ones with a specfic _HOOK suffix aren't global
Comment: It should better be [`hook_preprocess_HOOK`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook_preprocess_HOOK/8.2.x) to target a specific template.

How to call a function in a Twig file


Use drush instead of vendor/bin/drush

Question: I try to get drush to run by calling just 'drush' and not 'vendor/bin/drush', I'm working with OSX Sierra. This doesn't work out as I want hope someone can help me with this.
When i follow the instructions here:
http://docs.drush.org/en/master/install/
When at point 3:
If you want the convenience of calling drush instead of ../vendor/bin/drush, copy the examples/drush.wrapper file to your Drupal root and modify to taste.
I get stuck. I copy the drush.wrapper file to my root and rename it to drush . Then I edit the path to:
cd "`dirname $0`"
vendor/bin/drush.launcher --local "$@"

Because I'm in the root I removed the ../ before vendor. When I save all I stil get:

bash: drush: command not found

When I try going to: vendor/bin/drush.launcher it runs perfectly. What am I doing wrong?
Comment: Which OS you are using?
Comment: I'm working on OSX Sierra
Comment: A bit of a workaround... but have you considered just pointing drush to that folder form within your drushrc file? Or even just making a bash alias?http://docs.drush.org/en/7.x/configure/
Answer: This isn't really a Drupal or Drush question, but a Bash/shell question: How to run a script in the current directory?

The script must be executable: chmod u+x drush
The script must be in the (executable) path. Since it's not recommended to have the current directory in the path (for very good security reasons), the solutions is to call Drush as ./drush instead of just drush.

Use drush instead of vendor/bin/drush


Show two functions having nonzero Wronskian implies they are solution to some differential equation

Question: Suppose there exists $y_1,y_2 \in C^2$ defined on an interval I such that the Wronskian : $$ y_1y_2'-y_1'y_2$$ has no zeros in I.
Show that this implies there exists continuous functions $f, g$ such that $y_1, y_2$ are solutions to the differentiable equation: $$y''(x)+y'(x)f(x)+y(x)g(x)=0$$
I'm really at a loss here.
Answer: Hint: Consider
$$ \eqalign{y_1''(x) + y_1'(x) f(x) + y_1(x) g(x) &= 0\cr
y_2''(x) + y_2'(x) f(x) + y_2(x) g(x) &= 0\cr}$$
as a system of two linear equations in the unknowns $f(x)$ and $g(x)$.
Comment: Ah, that's embarrassingly simple.


MySQL Apelidos no Inner Join

Question: Tentei fazer esta junção interna no SQL para ligar duas tabelas no meu relatório.
O que eu estaria fazendo de errado, por que esta dando "Coluna ffccf desconhecida", mesmo eu apelidando a coluna?
Segue o código:
SELECT finafim.ccf as ffccf, finafim.impcaixa, finafim.numcup, finafim.vlfina, finafim.descfina,
       tabc470.ccf as t4ccf, tabc470.NSerie, tabc470.numcupom
FROM finafim
INNER JOIN tabc470
ON (finafim.numcup = tabc470.numcupom)
AND (finafim.ccf = tabc470.ccf)
AND (finafim.impcaixa = tabc470.NSerie)
WHERE ffccf= :ppccf AND numcup= :ppcoo AND impcaixa= :ppecf //Detalhes de parâmetros para igualar valores.
AND dtcomp BETWEEN "2014/03/01" AND "2014/05/01"

Answer: Só pode usar referenciar colunas pelos seus apelidos (alias) nas seguintes cláusulas:

GROUP BY
ORDER BY
HAVING

(Documentação MySQL)
Portanto no seu caso a sua query teria de referenciar as colunas directamente no WHERE em vez de usar os apelidos.
Comment: count, sum, avg também
Comment: @EnzoTiezzi pode dar `apelidos` aos resultados das funções de agregação, mas não pode referenciar colunas pelos seus `apelidos` dentro das funções.
Comment: mas caso você de um select count(tabela), você vai precisar apelidar para conseguir retirar o valor, no caso é válido então também.
Comment: @EnzoTiezzi não precisa de apelidar o `count(...)` para retirar o valor (nesta caso o resultado iria aparecer count(...)) ([sqlfiddle](http://sqlfiddle.com/#!2/a2581/25641))
Answer: SELECT DISTINCT ff.ccf AS ffccf, ff.numcup, ff.impcaixa, t46.ccf AS t46ccf, t46.numcupom, t46.NSerie
FROM finafim AS ff INNER JOIN tabc470 AS t46
ON (ff.numcup = t46.numcupom) AND (ff.ccf = t46.ccf) AND (ff.impcaixa = t46.NSerie)
WHERE ff.ccf= :ppccf AND numcup= :ppcoo AND impcaixa= :ppecf //Detalhes de parâmetros para igualar valores.
AND dtcomp BETWEEN "2014/03/01" AND "2014/05/01"

Segue o código correto...
Ele apenas aponta para a coluna exatamente como disse o Omni, nessas 3 condições.
Eu estava apontando ele dentro do Where, aonde não é viável, e nem permitido.
Desculpem-me a falta de organização, é que minha empresa bloqueou vários sites de fóruns, e não estou conseguindo  organizar meu post direito.
Comment: De fato eu consegui resolver o problema com isso, eu apenas removi algumas colunas que que eu não necessitava. E resolveu o problema, ou seja, eu apenas selecionei o que eu iria utilizar.

MySQL Apelidos no Inner Join


An Unexpected Circle...

Question: I played around with
$$z=\frac{-1+e^{it}}{\phantom{-}2+e^{it}}$$
and found that, when I  draw the real against the imaginary of $z$, it pretty much looks like a circle.

But neither ${\frak{R}} z $, nor ${\frak I} z$ look like $\cos $ or $\sin$. Is it due to a kind of transformed argument of $\cos $ and $\sin$? Something like $\cos(f(t))$?
Comment: Baggins! We hates it forever!
Comment: *My precious,* @Will "Gollum" Jagy. Thanks for the pun...
Comment: I see. They subtitled the movie An Unexpected Journey, i thought you meant that in the first place. http://www.imdb.com/title/tt0903624/
Comment: Why do you want the old title? I think the suggested one is more descriptive.
Comment: @Ooker a matter of taste and style about my own stuff...
Answer: Let $a,b,c,d$ be complex numbers and suppose c,d are not both 0 and a is not 0 ${}\ \ ad-bc\ne0$.
Let $f(z) = \dfrac{az+b}{cz+d}$.  Functions of this kind are called "linear fractional transformations".  Then if $z$ moves around a circle in the complex plane, then $f(z)$ follows either a circle, although usually it's not the same circle, or a straight line.  It will be a straight line if and only if $z$ passes through some point that makes the denominator $0$.  Except when $c=0$, you'll find that it doesn't move at the same angular rate, i.e. when $z$ goes through a quarter of a circle, then $f(z)$ might go through a half circle.
In your example, $a=1$, $b=-1$, $c=1$, and $d=2$.
Google the terms "linear fractional transformation" and "Riemann sphere".
PS: It is also the case that if $z$ moves along a straight line then $f(z)$ moves along either a straight line or a circle.
Comment: I changed it to say "If $z$ moves around a circle in the complex plane".  That would mean my "$z$" is your "$e^{it}$" and my "$f(z)$" is your "$z$".
Comment: Do you want to let $z$ be complex as well? Or did you mean my $z$?
Comment: @Michael thanks...
Comment: By hindsight I'm surprised that I said $a$ should not be $0$.  All of this works if $a=0$, unless $ad-bc=0$.

An Unexpected Circle...


Calculating the correlation between subsequent values in a stream of numbers

Question: I have a stream of integer values being generated $V_1,\cdots, V_n$ and want to calculate how the value of $V_{n+1}$ is correlated to $V_n.$ I would also like to calculate this at run time as additional values arrive. How do I do this?
I am implementing a local search algorithm and the values I am trying to correlate are the cost weightings of consecutive local optimum. I do not know how these are related but am trying to find out! That said .. I know the values will not have a zero mean. As the quality of the final solution I get is dependent on quickly evaluating lots of solutions on the way I need these stats to be generated efficiently.
Also it is worth mentioning that the frequency with which I need to read the correlation is less than the frequency with which new data points arrive, so if there is an efficiency to be gained in leaving parts of the calculation to when I really need to know the value then this is relevant.
I am separately calculating the Standard Deviation of the values at run time so can use this to convert from covariance to correlation.
Best Regards
Comment: Is there any distribution about the number?
Comment: How would you calculate it from the full sequence?
Answer: Assuming the sequence is stationary and zero mean:
You want to estimate
$$ r_1 = E(v_n v_{n+1})$$
The usual way (though the normalizing factor can also be $M$) is simply an average $$\hat{r}_1 = \frac{1}{M-1}\sum_{n=1}^{M-1} v_n \; v_{n+1} $$
If you want to compute it iteratively, it's straigforward. For any sequence $x_n$ its iterative average $m_n$ is trivially $$m_n = \frac{(n-1) \; m_{n-1} + x_n}{n} $$
You just plug that into the above formula (i.e. replace $x_n$ by $v_n v_{n-1}$). This is exact, but can have numerical problems for large $n$; if that's a problem you can choose a memory factor $\alpha \lesssim 1 $ and compute instead $$m_n = \alpha \; m_{n-1} + (1-\alpha) \, x_n $$
Added: This also has the advantage of being able to adapt to non-stationary sequences, if the statistics vary slowly. You then must make a compromise on the election of $\alpha$: too small (little memory) corresponds to an effective average of few past values, and hence the estimator will have high variance; too big values will remember too much of the past, and will not adapt to the non-stationary. You could adopt  some "characteristic time" $M$, an order-of-magnitude value of how many past values you want to keep, and use $\alpha = -1/\log(M)$
Comment: The number you get out of this won't necessarily be between -1 and 1; if you double all the $v_i$, you multiply $r_1$ by 4; it's not clear to me how you interpret your answer as a correlation.
Comment: @Gerry: I'm not computing a correlation coefficient (between -1 and 1) but a plain correlation (= covariance). If you want the correlation coefficient, you can also estimate the variance of the process by an analagous formula, and divide. Always assumming that the sequence is stationary.
Comment: it's not what I want that matters, it's what OP wants. You've made your guess as to what that is, I've made mine, now we sit back and wait for OP to return to enlighten us.
Comment: @leon: Thanks for your answer, my values do not have a zero mean but I guess I could do something like correlate Vn - Vn+1 which would have a zero mean? How does this affect your equation?
Comment: @Howard: If the process does not have zero mean, but it's constant (stationary sequence) you can estimate it by a similar procedure, and subtract it from the sequence values.
Answer: Do you know how to calculate the correlation of two data sets $\lbrace x_1,x_2,\dots,x_n\rbrace$ and $\lbrace y_1,y_2,\dots,y_n\rbrace$? Why not do that with the second set being $\lbrace x_2,x_3,\dots,x_{n+1}\rbrace$?
Comment: The issue here is with the fact that they are [streams](http://en.wikipedia.org/wiki/Streaming_algorithm). You need an "online" algorithm. The typical methods aren't really designed with streams in mind, so it needs some thought.
Comment: @Shreevasta, the methods I'm familiar with for calculating the correlation coefficient of the $x_i$ and the $y_i$ rely on knowing $\sum x_i$, $\sum x_i^2$, $\sum y_i$, $\sum y_i^2$, and $\sum x_iy_i$, all of which are suitable for streams. What am I missing?
Comment: @Gerry: Thanks for your response, is there any efficiency to be had because Xn == Yn+1?
Comment: @Howard, I guess it means that you don't have to update both $\sum x_i$ and $\sum y_i$, you can just update the latter and use its previous value as the new value of the former. Similarly for the sums of the squares.


Find a graph with a unique perfect matching and minimum degree $k$

Question: Given  $ k \gt 0 $ , how can i prove the existence of a simple graph $\mathbf G$ that satisfies the following:
$\bullet$ $\delta (G) \ge k.$ ($\delta$ := the the minimum degree of a vertex in G).
$\bullet$ $\mathbf G$ have a unique perfect matching.
i do know that $|G|, \delta(G) \ge 2k-1\Rightarrow \nu(G) \ge k $. ($\nu$ :=size of the maximum matching),
and i also know that a graph with a unique matching must has a cut edge.
but i cant figure out how to prove the statement above.
Comment: Hint: by induction. Suppose that you have a graph of minimum degree $k-1$ with a unique perfect matching, and then build an instance of minimum degree $k$ from it (or from several copies of it).
Answer: We can build it by induction on $\delta$.  For base cases, $G_1$ is $K_2$, a single edge between two vertices.  Here is an example $G_2$ with $\delta=2$.

Now assume we have a graph $G_k$ meeting the definition with $\delta=k$ for some positive integer $k$.  We shall create a graph $G_{k+1}$.  Start with a single edge, which will be our cut edge.  Then, for each end of the vertex, create a copy of $G$ and attach the end of the cut edge to every vertex of $G$.  That graph has $\delta=k+1$ and, by the induction hypothesis, has a unique matching.
In fact, $G_2$ is an example of using this algorithm from $G_1$.  Here is what $G_3$ would look like.
Comment: thanks. that's very helpful


Prove that if $f \in C^r(T)$, then $\hat{f}(n) = o(\frac{1}{|n|^r} )$ as $n \rightarrow ±∞$

Question: I searched through everything that came up when I searched this question, but didn't come with anything. I'm used to typing in latex, so please excuse any formatting errors.
Answer: $$\begin{align}
\widehat f(n)&=\int_{\mathbb{T}}f(x)\,e^{-inx}\,dx\\
&=\int_{\mathbb{T}}f\Bigl(x+\frac{\pi}{n}\Bigr)\,e^{-in\bigl(x+\tfrac{\pi}{n}\bigr)}\,dx\\
&=-\int_{\mathbb{T}}f\Bigl(x+\frac{\pi}{n}\Bigr)\,e^{-inx}\,dx.
\end{align}$$
Averaging the two expressions for $\widehat f(n)$ we get
$$
|\widehat f(n)|\le\frac12\int_{\mathbb{T}}\Bigl|f(x)-f\Bigl(x+\frac{\pi}{n}\Bigr)\Bigr|\,dx\le\frac{C\,\pi^r}{2\,n^r}\,2\,\pi.
$$


Old speakers not working when attached to a RCA output device with an adapter

Question: I have a pair of old Pioneer S-P170 speakers that I'm trying to hook up to various RCA output devices with the use of an adapter I recently purchased. I know the speakers work and have the positive and negative wires correctly identified, but I am not getting any sound. My only guesses right now are that these adapters I'm using are either completely worthless, or there is something I am fundamentally not understanding. I'm inclined to think I am doing something wrong, but do not have any idea what the problem might be. What might be a cause of the lack of sound when the speakers are attached with the adapter to an RCA output device such as a TV or a Bose Wave Radio?
RCA Cable Audio Adapter, Phono RCA Male Plug to AV Screw Terminal Audio/Video Speaker Wire connectors Solderless Adapter(RCA Male-2pack)
https://smile.amazon.com/gp/product/B07HBJMHVV/ref=ask_ql_qh_dp_hza
Answer: Keep in mind that speakers require power and a specific type of connection, a speaker output, the type you would find on the back of an amplifier or a powered receiver. There are speakers which are powered (contain built-in amplifiers) and have to be individually plugged in to an outlet and switched on but I don't believe yours are.
I think that you might be connecting your speakers to a simple audio output (Bose devices and TV's generally do not have speaker outputs) which is designed to send the signal to another device with its own power source. Is the Bose or the TV output specifically labeled "speaker output"? If it says audio output or output then it is sending a line level signal only and is not designed for speakers.
In order to hear your speakers they need to be powered by some type of amplifier. The amplifier can receive the signal from the output on your TV or Bose unit and amplify and send it to the speakers vía the speaker outputs. Hope this helps.
Comment: It's rare to find RCA sockets ('phono') as speaker outlets - although some equipment from the 60s did use them. Far, far more common to find them as line level ports.
Comment: @Tim I've seen RCA Speaker connections on a few things, usually less expensive stereos but you're right, RCA is almost exclusively for line level signals. The majority of stereo equipment I've seen uses terminals for attaching bare wire or banana plugs for speaker connections.
Comment: Don't know why, but I've never used banana plugs, ever! Bare wire, XLR, DIN speaker plugs (one flat, one round pin) jacks, and now Speakon. Maybe banana sounds like it's not really for the job?
Comment: I've seen binding post/ banana jack connections mainly on older commercial sound theater type speaker systems. Also most of the power amps used them because of their high current capacity.


How can webapps within Apache Tomcat use SSL/TLS client-certificate authentication as clients?

Question: I am using Apache Tomcat webapp as a client (java) to an IIS hosted webservice.
I need to use SSL with client authentication.
What kind of matching criteria is used by the client to send a client certificate to the Server as part of the CertificateRequest which is part of the ServerHello.
I installed the client cert in IE and access the WSDL then it prompts for the client cert and I choose the one that I installed and it works.
I can send the debug ssl dump if needed.
Answer: Ultimately, the certificate will be sent using the mechanism in the X509KeyManager used in the SSLContext used by the SSLSocket/SSLEngine used by the client.
The default SSLContext initialises its key manager using the javax.net.ssl.keyStore* system properties. (See this SO answer for the difference between "key store" and "trust store": both use the "keystore" API/storage format.)
The simplest is to configure the JVM running Tomcat, within which your client/webapp is running, with these javax.net.ssl.keyStore* properties. The default SSLContext will pick it up, and it's used by default for HTTPS connections (even 3rd-parties HTTPS libraries would tend to use it).
If you need something more specific for particular requests, you may need to alter the webapp code, so as to use a specific keystore (or at least choose a specific certificate) within a given SSLContext for that request.
How you configure the JVM running Tomcat will depend on the launching script. If under Windows, this question should help, otherwise, I suspect there's a line somewhere in catalina.sh where you could set system properties.
If you do configure the global javax.net.ssl.keyStore* for this, this will affect the entire VM, including the connectors. To prevent your Tomcat connectors using that keystore, make sure that the <Connector /> configuration does specify its own keyStore* attributes (so as not to use the values from the system properties).
If there are multiple certificates (with private key) in your keystore, the choice should be made automatically according to the CA list send by the server within its CertificateRequest message. By default, the key manager will pick up the first certificate it finds in the configured keystore that is issued by a CA in that list (or an intermediate CA). If you need something more specific (in particular if there are multiple valid candidates in your keystore), you'll need to implement your own X509KeyManager, put the logic in chooseClientAlias, initialise an SSLContext with it, and make whatever API making those requests use it.


$\mathrm{Ei}(x)$, the exponential function, some question.

Question: I have a question involving with $\mathrm{Ei}(x)$, define as $\int_{-x}^{\infty}e^u \cdot u^{-1} \mathrm{d}u$.
My question is, when I have a expression say $\exp(x) \cdot \mathrm{Ei}(x)+1$.
I want to optimize this function in terms of $x$. Now, the question is how do I suppose to with this $\mathrm{Ei}(x)$ function?
Comment: The definition of the function is currently not right. You need $e^{-u}$.
Comment: Specifically: $\operatorname{Ei}(x) = {-}\int\limits_{-x}^\infty \frac{e^{-u}}{u}\;\mathrm{d}u$
Comment: What do you mean when you say that you "want to optimize this function in terms of $x$" ?
Answer: It may be helpful to note that
$$\frac{d}{dt}\int^{\infty}_{t}f(u)du=-f(t)$$


Can I prove this inequality algebraically?

Question: With $x+y\ge z$ $(x,y,z\ge0)$, prove that: $$\frac{x}{1+x}+\frac{y}{1+y}\ge\frac{z}{1+z}$$
I'm aware that using analytic view this is easy since $f(x)=\frac{x}{1+x}$ is concave in $[0,\infty)$. However I want to prove it using merely algebraic techniques. Is that possible?
Comment: Write $\frac{w}{1+w}=1-\frac{1}{1+w}$ for $w=x,y,z$ and then you need to show $\frac{1}{1+x}+\frac{1}{1+y}\leq 1 + \frac{1}{z+1}$. Proving this is fairly direct algebraically.
Comment: @ThomasAndrews: Thanks for your advice but IMHO that makes it even more difficult to prove.
Comment: What have you tried either this way or your own?  What is the most obvious thing you can do for an "algebraic" proof?
Comment: Related : https://math.stackexchange.com/questions/309198/if-dx-y-is-a-metric-then-fracdx-y1-dx-y-is-also-a-metric
Answer: The conditions certainly give  $xyz + 2xy + x + y \ge z$
which is a simplification of  $x(1 + y)(1 + z) + (1 + x)y(1 + z)  \ge  (1 + x)(1 + y)z$.
Now just divide all that by  $(1 + x)(1 + y)(1 + z)$.
Comment: @Voldemort: I certainly hope not. That is no way to greet a newcomer. Instead of downvoting, or at least in addition to downvoting, suggest the use of $\LaTeX$.
Comment: Why the downvotes?
Comment: Probably 'cause he didn't use $\LaTeX$.
Comment: This looks fine to me. So I ask, too: why the downvotes?
Comment: @robjohn: I agree. That's why I gave him upvote and a suggestion.
Comment: Ken, Welcome. You might want to look at [this helpful introduction to $\LaTeX$](http://meta.math.stackexchange.com/questions/5020/tex-latex-mathjax-basic-tutorial-and-quick-reference)
Answer: How about this? As Thomas Andrews observed, write $\frac{w}{1+w}=1−\frac{1}{1+w}$ for $w=x,y,z$ and then you need to show $\frac{1}{1+x} + \frac{1}{1+y} \le 1 + \frac{1}{z+1}$.
Now, $$1 + \frac{1}{z+1} \ge 1 + \frac{1}{x+y+1} = \frac{x+y+2}{x+y+1} \ge \frac{(x+1)+(y+1)}{1+x+y+xy} = \frac{1}{1+x} + \frac{1}{1+y}$$ and we're done. Equality holds when one of $x,y$ is $0$, and $z=x+y$.
Comment: (so equality holds when one of $x$ or $y$ is zero and the other is equal to $z$)
Answer: Since $f(x)=\frac{x}{x+1}=1-\frac1{x+1}$ is increasing we can consider the case $a,b< c$ then
$$\frac{c}{c+1}< \frac{a+b}{c+1}=\frac{a}{c+1}+\frac{b}{c+1}<\frac{a}{a+1}+\frac{b}{b+1}$$


How can I perform ansible error-handling at playbook level?

Question: I have a main playbook which imports other playbooks to perform actions in several machines.
machine1 is a hub where test results are collected, after being executed on other machines:
<code>- name: clear state
  import_playbook: playbook-clear-machines-state.yml

- name: prepare run
  hosts: machine1
  roles:
    - prepare_test_run

- name: run_tests_in_machine2
  import_playbook: playbook-run-tests-machine2.yml
  ignore_error: yes

  ...
</code>
What I would like to guarantee is that only an instance is running at a time (i.e. no one is able to run tests if an user is already doing so).
I thought of using a lock file in machine1 as a way of preventing that, in the following manner:
<code>- name: check temp file
  hosts: machine1
  tasks:
    - name: get stats of lock file
      stat:
        path: ./ansible.lock
      register: st
    - fail:
        msg: "tests already running"
      when:
        - st.stat.isreg is defined and st.stat.isreg
    - name: create lock file
      file:
        path: ./ansible.lock
        state: touch

- name: run all tests
  import_playbook: playbook-main.yml
  ignore_errors: yes

- name: delete lock file
  hosts: machine1
  tasks:
    - name: delete ansible.lock file
      file:
        path: ./ansible.lock
        state: absent
</code>
The problem here is that I need to make sure the lock file is always deleted in the end - even if there was an error at an earlier play.
How could I accomplish this? I tried to look into blocks and handlers but they don't seem appropriate to use at this level. Can anybody point me to a strategy/way to accomplish this?
Many thanks, José.
Answer: For this needs, you have rescue and always mechanism that must corresponding to your use case.
You have more details here.
So with your example code, this must looks like this :
<code>- name: check temp file
  hosts: machine1
  tasks:
    - name: get stats of lock file
      stat:
        path: ./ansible.lock
      register: st
    - fail:
        msg: "tests already running"
      when:
        - st.stat.isreg is defined and st.stat.isreg
    - name: run all tests
      block:
        - name: create lock file
          file:
            path: ./ansible.lock
            state: touch
        - name: 'playbook-main.yml'
          # import_playbook: playbook-main.yml
          # Paste the content of this playbook here
          ignore_errors: yes
      always:
        - name: delete lock file
          file:
            path: ./ansible.lock
            state: absent
</code>
In a context really close to you, you have this reponse to.
Comment: After refactoring my code as per your answer, I'm getting the following error: ERROR! this task 'import_playbook' has extra params, which is only allowed in the following modules: ansible.builtin.include_role, ansible.builtin.win_shell, ansible.builtin.set_fact, script, ansible.legacy.command, ansible.legacy.group_by (...). Could it be because the imported playbook makes references to the other hosts?
Comment: Yes currently, my answer does't work cause by limitation of import_playbook in doc it's illustrate. I advise to pu the content of this playbook in the block if it's possible or to package a dedicated role to this


Adding target blank to hyperlink

Question: i am having problem in adding the target=_blank to links. My link is coming in a variable from the database.
buy it:<?php echo $abc ?>

If i use firebud then it looks like:
 buy it: Amazon

please let me know how will i add target=_blank to this link.
Comment: $abc contains the link, edit that
Comment: Try `target="_blank"` instead.
Comment: What is your $abc string? Also your starting bracket is not a php <?php so this would not work at all
Comment: @Dagon can you please let me know how to edit this. i do not want to use databse. i want to use something like javascript.
Comment: @Dagon $abc is having link amazon.
Comment: yessss but $abc is defined somewhere, somehow, that's where the *target blank* should be added
Answer: You can add the tag base to the head of your document, which will change the target of all your links.

    <base target="_blank">

Specifying a different target on an anchor tag will override this default option which is good for if you have other links that you don't want the target to be blank.
Comment: The best solution. I say. But what if he doesn't wana add it to other links??
Comment: Edited my answer to include this scenario.
Comment: Well all you know, hes too lazy to add it to all links. I was just saying..... I agreed and +1d long ago.
Answer: If your links are in the database you could do something like str_replace("<a ", "<a target='_blank' ", $var):
Comment: Didn't work for me, but `preg_replace('/(/is','\\1 target="_blank">',$var);` did
Answer: Well it's really better if you do this kind of job on the client side.
Use javascript
document.getElementsByTagName('a')[0].target="_blank";

Adding target blank to hyperlink


Executable jar file is not responding and not running

Question: I wanted to convert .java file to executable jar file,i did so in the command prompt. But everytime i double click (open) it nothing happens.
jar cf Calculate.jar Calculator.java

This is what i typed in the cmd. How to get an executable file? I use windows
Comment: Is the callss containing the `main`-method specified in the Manifest?
Answer: That's not how it works, that way you are creating a jar archive with that .java file in it.
If you want to create the jar manually (if you want to do it one time, instead of using a build tool like ant or maven, it could have some educational value), you have to compile your .java file to a .class with javac, add it to the jar and then modify the META-INF/MANIFEST.MF manifest file to specify Calculator as value for the Main-Class attribute.
See this old guide from Sun.


Select all entries with no duplicates?

Question: I have the table productos:
nombre  Precio  Tienda   Departamento

  A      23      Belén     Hogar
  B      12      Belén     Hogar
  C      56      Belén     Hogar
  C      32      Terra     Hogar
  D      10      Belén     Hogar
  E      8       Belén     Hogar
  E      9       Terra     Hogar

And I need to select all entries on table productos, however on products with multiple entries I want the one with the highest price, regardless it being on the same tienda or not.
Comment: Hope the translation fits all your description and welcome to SO.
Comment: Which database do you use?
Answer: select p.*
  from productos p
  join (select nombre, max(precio) as max_precio
          from productos
         group by nombre) v
    on p.nombre = v.nombre
   and p.precio = v.max_precio

The following would eliminate ties in Oracle or SQL Server or PostgreSQL (please specify the database you're using if you're not using Oracle or SQL Server):
select *
  from (select nombre,
               precio,
               tienda,
               departamento,
               row_number() over(partition by nombre order by nombre, precio desc, tienda, departamento) as rn
          from productos) x
 where rn = 1

Fiddle example with a tie being eliminated:
http://sqlfiddle.com/#!6/6b40d/4/0
Comment: Brian if the table have 1 product double with the same highest price, how I do to select only one. whichever
Comment: Are the tienda/department fields different on those rows at least? Also what database are you using (Oracle, sql server, mysql, postgresql, etc.)?
Comment: @rbklc I added a way to eliminate ties in Oracle, SQL Server, or PostgreSQL. If you're not using any of those databases, please specify the database that you are using. The solution depends on the database.
Comment: I use postgresql, and could be different or equal.
Comment: @rbklc should work in postgresql, see http://sqlfiddle.com/#!15/6b40d/1/0 , notice how A is listed only once

Select all entries with no duplicates?


std::vector reserve being more costly than expected

Question: So I need to manually handle the memory allocated by an std::vector for efficiency purposes. And I noticed that my program was slower than expected, so I added this idiom everywhere in my code base:
const uint new_edges_capacity = mesh.edges.size() + 6;
if(new_edges_capacity > mesh.edges.capacity())
    mesh.edges.reserve(new_edges_capacity * 2);

Originally I was simply doing:
const uint new_edges_capacity = mesh.edges.size() + 6;
mesh.edges.reserve(new_edges_capacity * 2);

Well, that first snippet is orders of magnitude faster than the second.
I don't understand, the official documentation seems to suggest that reserve should already be doing the same check I am. However, perf definitely marks std::reserve as the most expensive operation in my code, and indeed the modification shows that not calling reserve and relying on it to check for allocation is faster.
An example of a function where I am using this pattern:
template<typename V>
void HMesh<V>::SplitFace(uint face_id, HMesh<V>& mesh)
{
    mesh.vertex_data.push_back({});
    mesh.verts.push_back({&mesh});
    HMesh<V>::MVert& c = mesh.verts.back();

    const uint new_edges_capacity = mesh.edges.size() + 6;
    if(new_edges_capacity > mesh.edges.capacity())
        mesh.edges.reserve(new_edges_capacity * 2);
    mesh.edges.push_back({&mesh});
    HMesh<V>::MEdge& n00 = mesh.edges.back();
    mesh.edges.push_back({&mesh});
    HMesh<V>::MEdge& n01 = mesh.edges.back();
    mesh.edges.push_back({&mesh});
    HMesh<V>::MEdge& n10 = mesh.edges.back();
    mesh.edges.push_back({&mesh});
    HMesh<V>::MEdge& n11 = mesh.edges.back();
    mesh.edges.push_back({&mesh});
    HMesh<V>::MEdge& n20 = mesh.edges.back();
    mesh.edges.push_back({&mesh});
    HMesh<V>::MEdge& n21 = mesh.edges.back();

    const uint new_faces_capacity = mesh.faces.size() + 2;
    if(new_faces_capacity > mesh.faces.capacity())
        mesh.faces.reserve(new_faces_capacity * 2);
    mesh.faces.push_back({&mesh});
    HMesh<V>::MFace& f1 = mesh.faces.back();
    mesh.faces.push_back({&mesh});
    HMesh<V>::MFace& f2 = mesh.faces.back();

    auto& face = mesh.faces[face_id];

    HMesh<V>::MFace& f0 = face;

    HMesh<V>::MEdge& e0 = face.EdgeD();
    HMesh<V>::MEdge& e1 = face.EdgeD().NextD();
    HMesh<V>::MEdge& e2 = face.EdgeD().PrevD();

    HMesh<V>::MVert& v0 = e0.VertD();
    HMesh<V>::MVert& v1 = e1.VertD();
    HMesh<V>::MVert& v2 = e2.VertD();

    ConnectFace(f0, n00, e0, n10);
    ConnectFace(f1, n11, e1, n21);
    ConnectFace(f2, n20, e2, n01);

    Pair(n00, n01);
    Pair(n10, n11);
    Pair(n20, n21);

    AttachVertices(n00, c, v0);
    AttachVertices(n11, c, v1);
    AttachVertices(n20, c, v2);

    c.Data({
        (v0.Data().position + v1.Data().position + v2.Data().position) / 3.0,
        (v0.Data().uv + v1.Data().uv + v2.Data().uv) / 3.0,
        {0,0,1}
    });
}

Comment: `reserve` checks if `new_edges_capacity * 2 > capacity()`, but you are checking `new_edges_capacity > capacity()`. Also timings with no optimisations are meaningless
Comment: Gcc with no optimizations (because of debugging reasons)
Comment: Your first one doubles the size when it's full. Your second one potentially adds 2 elements every time it runs. Your second one does a lot more reserving.
Comment: Timings with linear operations over thousands of data points are not meaningless. Point in case, this change makes the code orders of magnitude faster.
Comment: But I also think your comment was my problem.
Comment: "So I need to manually handle the memory allocated by an std::vector for efficiency purposes." plus "no optimizations (because of debugging reasons)" are directly at odds
Comment: I will enable the optimizations, obviously, right now they are disabled because it makes debugging simpler when I have to step down on GDB. Most of my problems are of numeric nature and it helps not having to worry about the compiler changing the order of my math operations.
Answer: You're not reimplementing reserve, you're reimplementing the resize operation when capacity is exhausted. Problem is, if you do this every time you insert an item, you're resizing every time, making every operation O(n) (as it has to move all the items from the original backing storage to the new, larger, storage). If you ran this every time, building from an empty vector, you'd see a pattern of:
Size  Capacity  Reallocation needed?
1     14        Yes
2     16        Yes (16 > 14)
3     18        Yes (18 > 16)
4     20        Yes (20 > 18)
... reallocations continue forever ...

and each of those resizes would cause a new allocation, a move of all existing elements, and clean up of the old allocation (with destructors of the moved-from objects firing). You haven't saved anything, because you force new allocations every time, in an effort to avoid unnecessary allocations (which is clearly unhelpful).
In the case with the if test, since you test against a value half of what you reserve if the test fails, it reallocates much less frequently:
Size  Capacity  Reallocation needed?
1     14        Yes
2     14        No  (2 + 6 <= 14)
3     14        No  (3 + 6 <= 14)
4     14        No  (4 + 6 <= 14)
5     14        No  (5 + 6 <= 14)
6     14        No  (6 + 6 <= 14)
7     14        No  (7 + 6 <= 14)
8     14        No  (8 + 6 <= 14)
9     30        Yes  (9 + 6 > 14)
... very rare reallocations ...

As you can see, your test means far less resizing activity.
If you're just trying to guess at how much space you need, don't; let vector resize automatically on demand (doubling every time it's necessary might save you a little time over the default amortized growth schedule, but it also wastes a lot of memory). reserve is for when you know how much space you need; using it over and over is expensive.
Comment: But the documentation says:
`
If n is greater than the current vector capacity, the function causes the container to reallocate its storage increasing its capacity to n (or greater).

In all other cases, the function call does not cause a reallocation and the vector capacity is not affected.`

It says no allocation should occur if the capacity does not exceed the limit
Comment: @Makogan: Is the container ever changing size? Without a [MCVE], my assumption is that you're running this before or after insertions into the `vector`, which would mean the new requested capacity is always a little bit larger than the last requested capacity.
Comment: @Makogan: Remember, your test is asking if the new capacity it greater than the current capacity, but it resizes to *twice* that new capacity. The documentation is saying "If you ask for capacity *at all* greater than the current, we have to resize", but your test ensures you only ask for greater capacities when it's *much* greater, dramatically reducing the number of times you need to resize the backing storage.
Comment: @Makogan And look at the "Capacity" in the answer's chart. Every time you are telling it to make a bigger capacity, so every time it has to resize. 16 is bigger than 14. 18 is bigger than 16.
Comment: Yes both in all cases I was reserving twice the amount asked.
Comment: @Makogan: I added tables for with and without the test to make it clear what the difference is, and made it explicit when reallocation was needed, and why.
Comment: Yes you are correct. I should have thought about what I was doing a little bit more.
Answer: You don't need to reserve at all. Just use indices.
template<typename V>
void HMesh<V>::SplitFace(uint face_id, HMesh<V>& mesh)
{
    mesh.vertex_data.push_back({});
    mesh.verts.push_back({&mesh});
    HMesh<V>::MVert& c = mesh.verts.back();

    const uint n = mesh.edges.size();
    mesh.edges.push_back({&mesh});
    mesh.edges.push_back({&mesh});
    mesh.edges.push_back({&mesh});
    mesh.edges.push_back({&mesh});
    mesh.edges.push_back({&mesh});
    mesh.edges.push_back({&mesh});

    auto & n00 = mesh.edges[n + 0];
    auto & n01 = mesh.edges[n + 1];
    auto & n10 = mesh.edges[n + 2];
    auto & n11 = mesh.edges[n + 3];
    auto & n20 = mesh.edges[n + 4];
    auto & n21 = mesh.edges[n + 5];

    const uint f = mesh.faces.size();
    mesh.faces.push_back({&mesh});
    mesh.faces.push_back({&mesh});

    auto& f0 = mesh.faces[face_id];
    auto& f1 = mesh.faces[f + 0];
    auto& f2 = mesh.faces[f + 1];

    auto& e0 = f0.EdgeD();
    auto& e1 = f0.EdgeD().NextD();
    auto& e2 = f0.EdgeD().PrevD();

    auto& v0 = e0.VertD();
    auto& v1 = e1.VertD();
    auto& v2 = e2.VertD();

    ConnectFace(f0, n00, e0, n10);
    ConnectFace(f1, n11, e1, n21);
    ConnectFace(f2, n20, e2, n01);

    Pair(n00, n01);
    Pair(n10, n11);
    Pair(n20, n21);

    AttachVertices(n00, c, v0);
    AttachVertices(n11, c, v1);
    AttachVertices(n20, c, v2);

    c.Data({
        (v0.Data().position + v1.Data().position + v2.Data().position) / 3.0,
        (v0.Data().uv + v1.Data().uv + v2.Data().uv) / 3.0,
        {0,0,1}
    });
}


Debian Jessie Qemu KVM GPU Passthrough to Windows Virtual Machine guest Virt-Manager error Bus PCI not found

Question: I'm having problems with Virt-Manager not wanting to boot a VM and giving error:
Error starting domain: internal error: process exited while connecting to monitor: char device redirected to /dev/pts/3 (label charserial0)
qemu-system-x86_64: -device ioh3420,bus=pci,addr=1c.0,multifunction=on,port=1,chassis=1,id=root.1: Bus 'pci' not found

If I click Details here's the full error:
Traceback (most recent call last):
File "/usr/share/virt-manager/virtManager/asyncjob.py", line 96, in cb_wrapper
callback(asyncjob, *args, **kwargs)
File "/usr/share/virt-manager/virtManager/asyncjob.py", line 117, in tmpcb
callback(*args, **kwargs)
File "/usr/share/virt-manager/virtManager/domain.py", line 1160, in startup
self._backend.create()
File "/usr/lib/python2.7/dist-packages/libvirt.py", line 917, in create
if ret == -1: raise libvirtError ('virDomainCreate() failed', dom=self)
libvirtError: internal error: process exited while connecting to monitor: char device redirected to /dev/pts/3 (label charserial0)

qemu-system-x86_64: -device  ioh3420,bus=pci,addr=1c.0,multifunction=on,port=1,chassis=1,id=root.1: Bus 'pci' not found
I manually added some commandline things with virsh edit to the xml config for the VM because virt-manager didn't have those options ie for GPU BIOS file etc. Here are the qemu commandline tags:
<qemu:commandline>
<qemu:arg value='-device'/>
<qemu:arg value='ioh3420,bus=pci,addr=1c.0,multifunction=on,port=1,chassis=1,id=root.1'/>
<qemu:arg value='-device'/>
<qemu:arg value='vfio-pci,host=04:00.0,bus=root.1,addr=00.0,multifunction=on,x-vga=on,romfile=/home/me/Downloads/Sapphire.R9280X.3072.131127_2.rom'/>
<qemu:arg value='-device'/>
<qemu:arg value='vfio-pci,host=04:00.1,bus=root.1'/>
<qemu:arg value='-bios'/>
<qemu:arg value='/usr/share/seabios/bios.bin'/>
<qemu:arg value='-cpu'/>
<qemu:arg value='host,kvm=off'/>
</qemu:commandline>

uname -a
Linux vmserver 3.16.0-customvmkernel #1 SMP Sun Sep 28 00:34:42 PDT 2014 x86_64 GNU/Linux

kvm --version
QEMU emulator version 2.1.0 (Debian 2.1+dfsg-4), Copyright (c) 2003-2008 Fabrice Bellard

Answer: I changed bus=pcie.0 or bus=pci to bus=pci.0  apparently the way its names depends on architecture used in xml file. Mine used
instead of the more popular machine q35 definitions which would default to pcie.0
It boots without that error now.
Comment: If this is resolved, please mark it as such by ticking the check mark. It still shows up as an unanswered question.
Comment: Yes, I had a very similar issue when using q35 for the first time, as it's much more strict about the virtual architecture.


Catch keyboard 'Done' for NumberPicker

Question: I have an AlertDialog with just some text, a NumberPicker, an OK, and a Cancel.
package org.dyndns.schep.example;
import android.os.Bundler;
import android.view.View;
import android.widget.NumberPicker;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;

public class FooFragment extends DialogFragment {
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mParent = (MainActivity) activity;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setPositiveButton(android.R.string.ok,
                new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                mParent.setFoo(foo());
            }
        })
        .setNegativeButton(android.R.string.cancel, null);

        View view = getActivity().getLayoutInflater.inflate(
                R.layout.dialog_foo, null);
        mPicker = (NumberPicker) view.findViewById(R.id.numberPicker1);
        mPicker.setValue(mParent.getFoo());
        builder.setView(view);
        return builder.create();
    }

    public int foo() {
        return mPicker.getValue();
    }

    private MainActivity mParent;
    private NumberPicker mPicker;
}

(This dialog doesn't yet do the things it should to preserve state on Pause and Resume, I know.)
I would like the "Done" action on the soft keyboard or other IME to dismiss the dialog as though "OK" were pressed, since there's only the one widget to edit.
It looks like the best way to deal with an IME "Done" is usually to setOnEditorActionListener on a TextView.  But I don't have any TextView variable, and NumberPicker doesn't obviously expose any TextView, or similar editor callbacks.  (Maybe NumberPicker contains a TextView with a constant ID I could search for using findViewById?)
NumberPicker.setOnValueChangedListener does get triggered on the "Done" action, but it also fires when tapping or flicking the list of numbers, which definitely should not dismiss the dialog.
Based on this question, I tried checking out setOnKeyListener, but that interface didn't trigger at all when using the soft keyboard.  Not a total surprise, since the KeyEvent documentation suggests it's meant more for hardware events, and in recent APIs the soft keyboard won't send them at all.
How can I connect the IME "Done" to my dialog's "OK" action?
Edit: From the looks of the source, a NumberPicker layout does contain a EditText, but its id is id/numberpicker_input in package com.android.internal.  Using that would not be easy, and is obviously discouraged.  But it seems like there might only be hack ways to get the behavior I want.
Comment: Have you tried any custom number picker which are compatible with older Android versions. I am sure you will have access to their `EditText` id. You can check this: https://github.com/SimonVT/android-numberpicker
Answer:
How can I connect the IME "Done" to my dialog's "OK" action?

The problem is that you can't pass the IME's events if you don't have a listener set on the TextView widget which currently works with the IME. One way to do what you want is to hook our own logic to the NumberPicker's child which works with the IME(like you already talked in the last part of your question). To avoid using certain ids or other layout tricks(which can be problematic) to get a hold of that widget, you could use a greedy tactic, setting the listener to any widget from the NumberPicker which could trigger the desired event(TextViews or any subclass of TextView). Something like this:
    private AlertDialog mCurrentDialog;
    private List<TextView> mTargets = new ArrayList<TextView>();
    private OnEditorActionListener mListener = new OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId,
                KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                // if a child of NumberPicker triggers the DONE editor event
                // get a reference to the positive button(which you use in your
                // code) and click it
               mCurrentDialog.getButton(Dialog.BUTTON_POSITIVE).performClick();
            }
            return false;
        }
    };

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
     // ...
     mPicker = (NumberPicker) view.findViewById(R.id.numberPicker1);
        mPicker.setValue(mParent.getFoo());
        // clear any previous targets
        mTargets.clear();
        // find possible targets in the NumberPicker
        findTextViews(mPicker);
        // setup those possible targets with our own logic
        setupEditorListener();
        builder.setView(view);
        // get a reference to the current showed dialog
        mCurrentDialog = builder.create();
        return mCurrentDialog;
    }

Where the methods are:
private void findTextViews(ViewGroup parent) {
        final int count = parent.getChildCount();
        for (int i = 0; i < count; i++) {
            final View child = parent.getChildAt(i);
            if (child instanceof ViewGroup) {
                findTextViews((ViewGroup) child);
            } else if (child instanceof TextView) {
                mTargets.add((TextView) child);
            }
        }
    }

    private void setupEditorListener() {
        final int count = mTargets.size();
        for (int i = 0; i < count; i++) {
            final TextView target = mTargets.get(i);
            target.setOnEditorActionListener(mListener);
        }
    }

The other possible(and reasonable) solution(like Naveen already mentioned in his comment) is to use one of the ports of the NumberPicker class(or modify the one from the SDK) out there and insert your own widget ids(which will make getting a reference to the widget a simple task). This would be easier to implement now but inconvenient to maintain on the long run.
Comment: Do you think it's worth the trouble to use a list of TextViews rather than just breaking the search loop when one is found?
Comment: @aschepler It's worth the trouble(just to be safe). I'm not sure if this is allowed(by the android alliance) but a device manufacturer could make its own `NumberPicker` widget having one or many additional `TextViews/EditTexts`(why not a header?, for example) besides the normal input `EditText`. Also, having that list doesn't reduce performance(that recursive method will parse a small view hierarchy) or memory consumption(as the widgets are already in the layout, you're just storing references to them).
Comment: Isn't it better to create custom `NumberPicker` and do the same? Code will be much cleaner
Comment: @Jin35 If you're referring to moving the code from my answer in a custom `NumberPicker` class instead of having it separated, you're right it's cleaner(as clean as it can be considering that the NumberPicker must have a reference to the dialog). My answer was just a simple example.
Answer: My search and experimentation has also turned out empty handed. That said I wouldn't encourage this kind of behavior as it doesn't make much sense.
If you need a NumberPicker it is because you want the feature of scrolling to the value that you need, not entering it (though it is possible). If you want to enter the value you'd use an EditText and you would be able to implement what you need without problems.
Alternatively you have to copy NumberPicker implementation from the source and then change it according to your needs (fx by adding ime options).

Catch keyboard 'Done' for NumberPicker


save and generate pdfs nodes with options

Question: I have a view that list a content type A with few fields,
For PDFs generation I choose views_pdf it works perfectly and it can generate for me pdfs with the desired fields.
Im behind two problems now that I don't know how to solve them :

I want to save the PDF in my server first, so when the user click on pdf link inside the view, it save the PDF first then download it.
The PDF should be generated following options chosen by user : "download a short version", "Download a long version", ...
( inside the view I thought to make different links and for each option I create its own view. is it the best idea, or I can pass arguements to the pdf ? )

What's your advice, should I continue with views_pdf or I must switch to pdf for example...
Thanks in advance for your suggessions.
Answer: Part 1: Rules should allow you to save a PDF to the server. Step 4 on this page explains how to do so using Webforms (and Webform Rules), but it should work for node-generated PDFs: http://areatype.com/blog/create-email-pdf-files-drupal-webforms
Part 2: You can absolutely pass arguments to a Views PDF. Aren't you already doing that with the NID?


User Defined Function to get longest word in a string in SQL Server

Question: I've trying to create a UDF in SQL to return the longest word in a string. I've created the following but I cant get it to work properly. Any suggestions?
CREATE FUNCTION [dbo].[ufn_Longestword] (@input varchar(255))

RETURNS varchar(100)
AS
BEGIN

    declare @pos int
    declare @pos2 int
    declare @wordpos int
    declare @longestword varchar(100)
    declare @Letter1 varchar (1)
    declare @Letter2 varchar (1)
    declare @twords table (
                            words varchar(100))

    SET @pos = 1
    WHILE @pos <= len(@input)
    BEGIN
        SET @Letter1 = substring(@input, @pos, 1)
        IF @Letter1 = ' '
        BEGIN
            SET @pos2 = @pos
            WHILE @pos2 <= len(@input)
            BEGIN
                SET @Letter2 = substring(@input, @pos2, 1)
                if @letter2 = ' '
                    BEGIN
                        insert into @twords
                        select SUBSTRING(@input, @pos,@pos2 - @pos)
                    END
            SET @pos2 = @pos2 + 1
            END

        END
        SET @pos = @pos + 1
    END

    SET @longestword = (select top 1 words from @twords
                        ORDER BY len(words)desc)

    delete from @twords

RETURN @longestword
END

I#m trying to get the different between the 2 spaces and insert that word into a temp table but it doesnt work.
Answer: Instead you can use this.
DECLARE @str VARCHAR(5000)='aaaa bbbbb cccccccc'

SELECT TOP 1 Split.a.value('.', 'VARCHAR(100)') as longest_Word
FROM   (SELECT Cast ('<M>' + Replace(@str, ' ', '</M><M>') + '</M>' AS XML) AS Data) AS A
       CROSS APPLY Data.nodes ('/M') AS Split(a)
ORDER  BY Len(Split.a.value('.', 'VARCHAR(100)')) DESC

Result : cccccccc
Answer: i found this as solution :
click Here
CREATE FUNCTION FN_ex06(@str varchar(8000) )

RETURNS @T TABLE

( position int IDENTITY PRIMARY KEY,
value varchar(8000) ,
length smallint null
)

AS

BEGIN

DECLARE @i int
SET @i = -1
WHILE (LEN(@str) > 0)
BEGIN
SET @i = CHARINDEX(' ' , @str) /* here i used space as delimiter*/
IF (@i = 0) AND (LEN(@str) > 0)
BEGIN
INSERT INTO @T (value, length) VALUES (@str, LEN(@str))
BREAK
END
IF (@i > 1)
BEGIN
INSERT INTO @T (value, length) VALUES (LEFT(@str, @i - 1),
LEN(LEFT(@str, @i - 1)))
SET @str = RIGHT(@str, (LEN(@str) - @i))
END
ELSE
SET @str = RIGHT(@str, (LEN(@str) - @i))
END
RETURN

END

to run this  function you treat it as table because return is a table
  select max(value) from  FN_ex06('karim pentester')

result is : pentester
of course you select all other columns in return table
Comment: You should add more details to the answer rather than just a link because it may be unavailable later.


Installation of angular material in angular 5 in ubuntu 16.4.5 (ERROR : Type 'ElementRef' is not generic.)

Question: Installation of angular material in angular 5 in ubuntu 16.4.5 :-
I've followed these steps: (https://v5.material.angular.io/guide/getting-started)

npm install --save @angular/material @angular/cdk
npm install --save angular/material2-builds angular/cdk-builds
npm install --save @angular/animations

reference from link further steps
but this gives me the following errors:
ERROR in node_modules/@angular/material/button-toggle/typings/button-toggle.d.ts(136,20): error TS2315: Type 'ElementRef' is not generic.
node_modules/@angular/material/button-toggle/typings/button-toggle.d.ts(154,104): error TS2315: Type 'ElementRef' is not generic.
node_modules/@angular/material/slide-toggle/typings/button-toggle.d.ts(53,15): error TS2315: Type 'ElementRef' is not generic.
node_modules/@angular/material/slide-toggle/typings/button-toggle.d.ts(55,18): error TS2315: Type 'ElementRef' is not generic.

How could I resolve this error?
Comment: Yes, i got the same issue. I solved that in my previous project. But, my new project have the same error. I forgot how to solve it.
Comment: Still i try to figure it out. If i got the solution, I'll inform to you
Comment: I think it's some version mismatch problem. Try to install angular material version 5.2.5
Answer: Try this one
npm install --save @email@example.com
npm install --save @firstname.lastname@example.com


Twig template for two different instances of the system branding block

Question: On the block layout page, I added the "Site Branding" block twice, once for normal use (all nodes except content type landing page) and once for landing page use (all nodes of content type landing page).
I themed the block using the twig template block--system-branding-block.html.twig, but this modifies both blocks.
Is there a way to get more specific and create a twig template for each block, or should I re-create the landing page block some other way so that I can use a different template?
EDIT: My goal is to actually change the HTML of the block, so I can't use a pure CSS approach.
Answer: There's a few things you can do. Here's three.

Consider using a pure CSS approach. If you look at the body element for your page there may well be different classes you can use to make different selectors for styling the block. Modern CSS, particularly with the availability of :before and :after pseudo selectors, is incredibly powerful and you very often don't need custom HTML to adjust styling for different cases.
You can also implement hook_theme_suggestions_alter in your theme (in the file mytheme.theme) to supply alternative template suggestions based on the current path, for example.

Following this example, your code might look like:
function THEME_NAME_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);

  $path_alias = trim($result, '/');
  $path_alias = str_replace('/', '-', $path_alias);
  $path_alias = str_replace('-', '_', $path_alias);
  $id = $variables['id'];

  $suggestions[] = 'block__path_alias__'.$path_alias;
  $suggestions[] = 'block__' . $id . '__path_alias__'.$path_alias;
}

Another option would be to create a second variant of the site branding block then use the option in Drupal's block system which lets you turn blocks on or off by content type.
Comment: I'm actually changing the HTML in the block (hard-coding a couple links) so I can't go with a pure CSS approach.
Comment: @PatrickKenny I have added some (untested) sample code for you.
Comment: As you want this to vary by content type, as long as there's a common path alias structure you should be able to grab the common part from the alias and use that in the suggestion.
Comment: @PatrickKenny another possible solution occurred to me, so have added that to my answer as well.
Answer: Try this module Block Content Machine Name
Will provide additional template suggestion like block--block-content--[MACHINE_NAME].html.twig.
Comment: This works for block content (custom blocks made at /admin/structure/block/block-content), but does it work for system blocks (site branding)?
Comment: Yes, this module works also with system blocks for example  machine name of site branding block is `sitebranding` .   you can see it from `admin/structure/block/manage/sitebranding` .


Regex in .htaccess combining two negative conditions

Question: could someone check this regex I wrote, it does what I wanted to achieve, but I'm not sure if it's the correct way to do it and if it's not slowing everything up
That's what it should do:
IF the URL Path is longer than the domain only
AND IF it doesn't contain the strings "/de" or "/en" at the beginning
THEN 301 it to the domain only
That's what I wrote:
RewriteCond %{HTTP_HOST} !^(www\.)?example\.com$
RewriteCond %{HTTP_HOST} ^(?!.*(/de|/en))
RewriteRule .* http://example.com/ [L,R=301]

... is there a better way to achieve that?
Thanks!!
Urs
Comment: `the URL Path is longer than the domain only`. What do you mean by that? Cause mod_rewrite can't check text-length.
Answer: I am assuming that you did a "mindfart" and the second cond should read %{REQUEST_URI} otherwise it makes no sense as HTTP_HOST will never include a /
In runtime it makes very little difference, but it is easier to understand if written as
RewriteCond %{REQUEST_URI} !(/de|/en)

Comment: I've reflected again on what I want to do, it's even simpler than what I sketched above: If REQUEST_URI doesn't start with /de or /en, add /de in front of it. Can you help me do that? (and also maybe point me to a good mod_rewrite tutorial)?
Comment: Use what is called a negative lookahead assertion on the rule pattern, \(described [here](http://www.regular-expressions.info/lookaround.html)\)  E.g. `RewriteRule ^(?!de/)(?!en/).*  - [L]`. (no leading `/` on rule patterns in `.htaccess` files).  Use [this script](http://stackoverflow.com/questions/9153262/tips-for-debugging-htaccess-rewrite-rules/9261963#9261963) to play with rule patterns.  As to tutorials, there's this thing called Google.  I learn't them before Google existed.  LoL.  Enjoy!!


What are valid use cases for -m2 in git revert for a merge commit?

Question: Normally if I fubar a merge into a mainline branch and push it, the go-to command is:
$ git revert -m1 <merge commit SHA1>

However, I know that revert also can work with -m2. However, this does not make sense to me. I can't visualize what this does to the mainline branch, if the revert occurs on the first parent. Does this basically make the first parent now look like the second parent, minus any changes made in the merge commit itself? What does this actually do to the tree? Is there a valid set of use cases for this kind of revert which refers to the second parent?
Second parent will always be the feature / topic branch that was merged in, so I can't imagine you'd want to revert a mainline to that state.
Answer: The most common use case is when someone botches a merge, usually on a git pull. When you do a pull that requires a merge, your local commits are the first parent, and the remote commits are the second. So let's say a developer hasn't pulled for a while, so his local branch is 20 commits behind origin. The developer makes a single commit, pulls, botches the merge somehow, and pushes. If we reverted that botched merge with -m1, we would lose the changes of all 20 of those commits and would have to cherry pick all of them. By using -m2, we just lose the changes from his single commit, and can then just cherry pick that if we wish.
Comment: When you merge in a feature branch, you do so while you are on the main branch, and it is the main branch that moves; that is what makes it the primary parent. When you do a git pull, you are on your local branch, and it is your local branch that moves, so it is the primary parent.
Comment: I'm more amazed that a merge during pull works that way. I would have expected the merge to appear the same way that a feature branch merge would look since they are technically the same thing.


question on listview control (windows forms)

Question: I use a listview control that displays search results over text files.What I want to do is to limit  access to readonly when user clicks.Is there any simple solution to the problem?Thank you.
Comment: Very unclear, readonly *what*?  There's only one kind of editing supported by ListView, you disable it by setting the LabelEdit property to False (the default).
Comment: Isn't there a .readonly property? eg myListView.readonly or something I know it shows up in the Properties panel in the Designer Also, is this C#, or vb or soemthing else .NET
Answer: Check this this or this. You have to make the columns read-only. Check for properties like readonly, labeledit, editable etc. Must be possible. Else the links will help you further. I use DevExpress grids and there it's easily possible (but those components are very customizable and much more advanced than standard Microsoft .NET ui components imho).


NoReverseMatch at / Reverse for 'like_post' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[0-9]+)/like/$']

Question:
NoReverseMatch at /
Reverse for 'like_post' with arguments '('',)' not found. 1 pattern(s)
   tried: ['(?P[0-9]+)/like/$']

I suspect there is some issue with my form but I'm unable to point out exactly whats wrong

views.py
from django.shortcuts import render,get_object_or_404
from django.views.generic import ListView
from .models import Blog

class BlogsList(ListView):
    model=Blog
    template_name='blog/home.html'
    context_object_name='blogs'
    ordering=['-date_posted']

def like_post(request, blog_id):
    post = get_object_or_404(Blog, id=blog_id)
    post.likes.add(request.user)
    return HttpResponseRedirect(Blog.get_absolute_url())

models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse

class Blog(models.Model):
    title=models.CharField(max_length=100)
    content=models.TextField()
    date_posted=models.DateTimeField(default=timezone.now)
    author=models.ForeignKey(User, on_delete=models.CASCADE)
    likes=models.ManyToManyField(User,related_name='likes',blank=True)
    def __str__(self):
        return self.title

urls.py
from django.urls import path
from . import views

urlpatterns=[
path('',views.BlogsList.as_view(),name='blog-home'),
path('<int:blog_id>/like/', views.like_post, name='like_post')
]

html code
{{ user.username }}
{% block content %}
    {% for post in blogs %}

{{ post.author }}

              {{ post.date_posted|date:"F d, Y" }}

{{ post.title }}

{{ post.content }}

            <form action="{% url 'like_post' blog_id %}">
              {% csrf_token %}
              <button type='submit' name='blog_id' value="{{ blog_id}}" class="btn btn-primary">Like</button>
            </form>

{% endfor %}
{% endblock %}

Comment: What do you think `blog_id` is in your template? (`{% url 'like_post' blog_id %}`) Where did you define that variable?
Answer: In your template, blog_id is not define (no contexte provided?).
You should change blog_id to post.id:
<form action="{% url 'like_post' post.id %}">
  {% csrf_token %}
  <button type='submit' name='blog_id' value="{{ post.id }}" class="btn btn-primary">Like</button>
</form>


How to integrate ABAC in a Spring application?

Question: Spring Security offers means for authorization like annotations (@PreAuthorize) and security-specific SpEL expression like hasRole. In principle this expression language could be extended to support ABAC, however that wouldn't really solve the architectural problem where to do it.
The application architecture is inspired by the Clean Architecture (which is in turn inspired by Hexagonal Architecture and the Onion Architecture). The basic building blocks look like this:

Adapter: connects to the outside world, e. g. HTTP endpoints
Application services: transforms to and from DTOs, provide transactions, perform authorization
Domain: describes business data, rules and behaviours

From my point of view the application layer is the only suitable layer to perform authorization. It wouldn't fit into the adapter layer, because there could be multiple adapters for a single application service, so that the authorization would have to be repeated in several places. It wouldn't obviously fit into the domain, because it is a technical aspect that shouldn't be part of the domain logic.
A typical application service method gets some more or less "raw" parameters from the client, converts it and delegate the execution to the domain:
@Transactional
class MyApplicationService {
    fun cancelOrder(id: Long) {
        val orderId = OrderId(orderId)
        val order = orderRepository.findById(orderId)
        order.cancel()
    }
}

In order to be able to perform attribute-based access control (ABAC), the order object must be loaded before, so that the attributes can be extracted in the first place. That does also mean that an annotation like @PreAuthorize above the cancelOrder function wouldn't work, because the order object wouldn't be available there (SpEL would be able to reference function parameters, but the order is not passed as parameter!).
The only remaining possibility, that I can think of, is to call an authorization function explicitly before proceeding with business logic:
    fun cancelOrder(id: Long, principal: Principal) {
        val orderId = OrderId(id)
        val order = orderRepository.findById(orderId)
        checkPolicy(principal, order, Context.Complaint) // ?
        order.cancel()
    }

What concrete ABAC server (like OPA, AuthzForce, etc.) is not yet decided, but the solution at this level should be independent from it.
Is there a common approach for what I outlined as checkPolicy? Is there a typical "Spring approach" to integrate an external policy decision point? Or is there a fundamentally better solution?
Answer: Option 1 - If you can modify the Order class:
You may apply @PreAuthorize on the Order#cancel() method directly, this way you can do like the checkPolicy and access the order object (with #this):
class Order {
 //...
 @PreAuthorize("hasPermission(#this, T(fully.qualified.Context).Complaint)")
 fun cancel() {...}
}

If your Context.Complaint constant is a String, maybe it's more readable to put the string value (e.g. 'complaint' ?) instead of T(...Context).Complaint in the Spel expression above.
Option 2 - If you cannot modify the Order class:
You may use the Proxy pattern, i.e. wrap the call to order.cancel in a intermediate class/function and put the annotation on it:
@Transactional
class MyApplicationService {
 fun cancelOrder(id: Long, principal: Principal) {
  val orderId = OrderId(id)
  // Proxy pattern - new intermediary class
  val order = OrderSecProxy(orderRepository.findById(orderId))
  order.cancel()
 }
}

class OrderSecProxy(val order: Order) {
 @PreAuthorize("hasPermission(#this.order, T(fully.qualified.Context).Complaint)")
 fun cancel() {
  order.cancel()
 }
}

Then you have to implement a custom PermissionEvaluator (Spring Security):
class AbacPermissionEvaluator implements PermissionEvaluator {

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
     log.info("check permission '{}' for user '{}' for target '{}'", permission, authentication.getPrincipal(), targetDomainObject)
     var principal = authentication.getPrincipal()
     // Make the authorization request to the PDP with subject attributes from principal, action attribute from permission and resource attributes from targetDomainObject
     // ...
     // return true if PDP's decision is Permit, else false.
    }
}

More info.
So you should get the order object from the targetDomainObject argument. However, it would be more generic (ABAC style) - less business-specific - to use a Map of attributes instead, by changing the @PreAuthorize expression as follows:
I assume the Order class has at least some id attribute but you can have other attributes.
In case of option 1:
@PreAuthorize("hasPermission(T(java.util.Map).of('resource-id', #this.id), T(fully.qualified.Context).Complaint)")

In case of option 2:
@PreAuthorize("hasPermission(T(java.util.Map).of('resource-id', #this.order.id), T(fully.qualified.Context).Complaint)")

Last, configure the PermissionEvaluator in your application context:
<bean id="abacPermEvaluator" class="fully.qualified.AbacPermissionEvaluator">

</bean>

<security:global-method-security pre-post-annotations="enabled">
 <security:expression-handler>
  <bean class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
    <property name="permissionEvaluator" ref="abacPermEvaluator"/>

  </bean>
 </security:expression-handler>
</security:global-method-security>

You can do the same configuration with annotations as usual.
Comment: Thank you for your effort, however I see the problem that the Order class cannot carry the security annotation because it is not managed by Spring and I'd prefer to perform security checks outside of the domain layer in the application layer.
Comment: OK I edited my answer to show the alternative when the Order class cannot be modified.
Comment: Thanks again. Option 2 wouldn't work, because the annotated method `secured_cancelOrder` would be called on the same instance as `cancelOrder` what means that it [wouldn't go through the proxy object](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop-understanding-aop-proxies) in therefore the annotation wouldn't have any effect.
Comment: I see, my bad.. If we move the annotated method to a separate class like in the Proxy design pattern, would that work? See my updated answer for example.


Usar vetor em funções externas a main

Question: Aprendi a utilizar funções há alguns dias e agora queria usar um vetor nelas. Meu professor ensinou, mas o meu código simplesmente não funciona. Um dos números acaba sendo repetido.Segue o código:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <locale.h>

void crescente(int vetor[],int n);//protótipo função
void decrescente(int vetor[],int n);//protótipo função

int main()
{

    setlocale(NULL,"");
    int vet[10],i,cod=3;

    printf("Digite dez números inteiros (aperte a tecla ENTER ao final de cada número)!\n");
    for(i=0;i<=9;i++)
        scanf("%d%*c",&vet[i]);

    system("cls");

   while(cod!=0)
   {

   printf("Escolha um código :\n1-Organizar em ordem crescente.\n2-Organizar em ordem decrescente.\n0-Finalizar o programa.\n\n");
   cod=getch()-48;

      if(cod==0)
           break;

      else if(cod==1)
           crescente(&vet,10);

      else if(cod==2)
           decrescente(vet,10);

   }
    return 0;
}

void crescente(int vetor[],int n)
{

int aux=0,control,i;

  do{
         control=0;

        for(i=0;i<=n-1;i++)
        {
            if(vetor[i]>vetor[i+1])
            {
                aux=vetor[i];
                vetor[i]=vetor[i+1];
                vetor[i+1]=aux;

                control=1;//controle do bubble sort que vi na internet,melhor q um FOR; kkkkkkk
            }
        }

    }while(control!=0);

    for(i=0;i<=n-1;i++)
        {
            printf("%d. ",*vetor[i]);

        }
     printf("\n\n\n");
}

void decrescente(int vetor[],int n)
{

int aux,control,i;

  do{
        control=0;

        for(i=0;i<=n-1;i++)
        {
            if(vetor[i]<vetor[i+1])
            {
                aux=vetor[i];
                vetor[i]=vetor[i+1];
                vetor[i+1]=aux;

                control=1;//controle do bubble sort que vi na internet,melhor q um FOR; kkkkkkk
            }
        }

    }while(control!=0);

    for(i=0;i<=n-1;i++)
        {
            printf("%d. ",vetor[i]);

        }
     printf("\n\n\n");
}

Answer: Você tem:
crescente(&vet,10);

E:
decrescente(vet,10);

Observe que um está com o & e o outro não. O correto seria nenhum dos dois ter isso. Depois disso, na função crescente você deveria ter:
printf("%d. ", vetor[i]);

Ao invés de:
printf("%d. ",*vetor[i]);

Ou seja, tire aquele *. Observe que a função decrescente está certa neste ponto.
Comment: Obrigado pelo aviso,eu mexi demais no código tentando consertar e esqueci alguns pontos,porém ao consertar o código ele continua não funcionando,gostaria que testasse o código com as correções para que visse o problema(sempre há o número um sobrando).

Usar vetor em funções externas a main


Fit gamma distribution to dataset with R

Question: I have this dataframe below:
structure(list(x = c(0, 1, 2, 3, 8, 0, 1, 0, 1, 2, 48, 49, 50,
51, 52, 53, 54, 55, 56, 1, 2, 3, 4, 5, 13, 14, 15, 16, 17, 0,
71, 72, 73, 74, 75, 37, 38, 39, 40, 41, 20, 21, 22, 23, 24, 12,
13, 14, 15, 16, 4, 5, 6, 7, 80, 81, 82, 83, 84, 85, 86, 1, 2,
3, 4, 5, 6, 88, 89, 90, 91, 26, 27, 28, 14, 15, 16, 5, 6, 7,
7, 8, 9, 10, 11, 1, 3, 29, 30, 0, 1, 20, 21, 22, 2, 3, 0, 1,
2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 1, 2, 1, 2, 97, 98, 99, 100,
101, 102, 103, 104, 105, 106, 83, 16, 18, 19, 86, 87, 91, 92,
93, 20, 21, 99, 100, 102, 103, 9, 10, 14, 0, 1, 2, 3, 4, 5, 6,
9, 10, 11, 12, 13, 14, 79, 80, 81, 82, 83, 0, 1, 2, 3, 4, 5,
7, 11, 21, 63, 64, 65, 66, 3, 18, 19, 20, 21), y = c(1665.05355793238,
2290.46808761358, 2479.44521586597, 1027.63470042497, 2382.83166897297,
599.608228149824, 200.079963575583, 2715.53603386879, 2567.91178971529,
2709.88102674484, 454.382090631872, 2268.14043972082, 2147.62290922552,
2269.1387550775, 2247.31983098201, 1903.39138268307, 2174.78291538358,
2359.51909126411, 2488.39004804939, 212.851575751527, 461.398994384333,
567.150629704352, 781.775113821961, 918.303706148872, 659.580393221229,
1107.37695799186, 1160.80594193377, 1412.61328924168, 1689.48879626486,
650.35140038206, 280.949480787385, 641.231373456365, 412.116433330579,
416.824746264203, 614.763061881065, 415.905685925856, 494.374217984441,
201.745910386788, 486.030122926459, 647.782697262242, 269.898762604455,
469.544556583467, 605.790549736819, 483.045965372879, 668.017897433514,
35.2706101682852, 265.693628564011, 285.116345260642, 291.023782284086,
357.428790589795, 205.920375034591, 229.606221692753, 230.952761338012,
241.641164634028, 494.819531862799, 611.564698476112, 603.238720579422,
524.322001078981, 565.296378873638, 532.431853589369, 597.174114277044,
140.829281608807, 260.737164468854, 306.72700499362, 283.410379620422,
366.813913489692, 387.570173754128, 648.038833109662, 606.075737104722,
686.408686154056, 705.914347674276, 814.318649679422, 720.467501226114,
897.123468788341, 1015.63389401929, 892.041182056069, 1587.7192387376,
469.889315964654, 371.252178900875, 516.214449755847, 223.317826933191,
233.990588575922, 254.111292146219, 388.602676983443, 477.858510450125,
53.9083766029653, 128.198042456082, 521.591475207009, 535.519377609133,
560.44362318865, 396.430340241175, 654.226210802794, 1303.48454248847,
1274.19490102748, 1615.11958998814, 1445.12280311435, 1579.06517848652,
1591.83073895803, 1926.41506405128, 2029.74201928871, 1762.10456025088,
1093.34139243141, 998.179578598123, 980.315594917862, 1016.85559533851,
996.357576390554, 1465.61544544157, 1639.27601695352, 3099.03079020977,
3250.79935610294, 613.15010408836, 794.168323367026, 953.81404011324,
1942.00127470493, 750.459735572338, 875.899619173259, 1166.28903575242,
788.564458085224, 1324.95006324351, 1111.05266567506, 1020.29043261707,
1130.40108603239, 1529.81020075083, 1480.88505926495, 524.398260936374,
512.986586335697, 833.124012635089, 957.75556050241, 220.735156724928,
584.620856728405, 1243.39788535796, 1578.20351953804, 1386.65165398503,
906.813018662913, 798.186995701282, 831.365377249207, 764.519073183124,
672.076289062505, 669.879217186302, 1388.61752325296, 1104.50366285443,
1722.3172301054, 313.881701797247, 1217.21950829029, 1325.65616729856,
2137.73167350888, 1958.17336059175, 2355.88909001648, 2261.16462984681,
2499.84794190526, 908.743901610374, 1927.14038875327, 1880.97180615366,
1977.65100651979, 1714.75837931037, 1265.48484068702, 1193.29000986667,
1156.81486114406, 1199.7373066445, 1116.24029749935, 1141.89299393632,
1545.56326286064, 1401.44881976186, 1346.97588634375, 1640.27575962036,
1458.74134225518, 1102.85304791946, 1617.68811492418, 1380.66626644135,
1614.92309916019, 1590.29306322336, 1516.55950581282, 1616.58492165804,
785.721945669502, 1857.46475183964, 3546.82112717628, 3451.61194658279,
2874.73860728741)), .Names = c("x", "y"), class = "data.frame", row.names = c(186L,
187L, 188L, 189L, 190L, 191L, 192L, 193L, 194L, 195L, 196L, 197L,
198L, 199L, 200L, 201L, 202L, 203L, 204L, 206L, 207L, 208L, 209L,
210L, 211L, 212L, 213L, 214L, 215L, 216L, 217L, 218L, 219L, 220L,
221L, 222L, 223L, 224L, 225L, 226L, 227L, 228L, 229L, 230L, 231L,
232L, 233L, 234L, 235L, 236L, 237L, 238L, 239L, 240L, 241L, 242L,
243L, 244L, 245L, 246L, 247L, 248L, 249L, 250L, 251L, 252L, 253L,
254L, 255L, 256L, 257L, 258L, 259L, 260L, 261L, 262L, 263L, 264L,
265L, 266L, 267L, 268L, 269L, 270L, 271L, 272L, 273L, 274L, 275L,
276L, 277L, 278L, 279L, 280L, 281L, 282L, 283L, 284L, 285L, 286L,
287L, 288L, 289L, 290L, 291L, 292L, 293L, 294L, 295L, 296L, 298L,
299L, 301L, 302L, 303L, 304L, 305L, 306L, 307L, 308L, 309L, 310L,
311L, 312L, 313L, 314L, 315L, 316L, 317L, 318L, 319L, 320L, 321L,
322L, 323L, 324L, 325L, 327L, 328L, 329L, 330L, 334L, 335L, 336L,
337L, 338L, 339L, 340L, 341L, 342L, 343L, 344L, 345L, 346L, 347L,
348L, 349L, 350L, 351L, 352L, 353L, 354L, 355L, 356L, 357L, 358L,
359L, 360L, 361L, 362L, 363L, 364L, 365L, 366L, 367L, 368L, 369L,
370L))

I want to fit a gamma distribution to this dataset. I am trying to use this function rgamma(n=, shape =, scale= ). However I do not quite understand the way to compute the different parameters of the gamma distribution. I am quite a dummy in this and the examples I have seen so far do not really explain how to get the shape and scale values. Can someone give me some insights on it?
Comment: This is a bivariate dataset, whereas a Gamma distribution is univariate only. What, then, do you mean by "fit a gamma distribution" to it?  And why do you want to do that?
Comment: What you are really asking, then, is how to fit a function of the form $y = A x^k\exp(-x)$ to your $(x,y)$ data.  The Gamma distribution appears to have nothing to do with it. What is more relevant is how you need to assess the goodness of fit.  If these points don't exactly line up along one of those curves, why would that occur? What is the source and nature of the variability that could produce such discrepancies?
Comment: I plotted the data.  There is no aspect of the $(x,y)$ data that looks remotely like a Gamma-shaped curve.  The *distribution* of $y$ might possibly have a Gamma shape.  If that's what you want to fit, then it would be best to eliminate the superfluous $x$ variable from your example. In any event, it's essential that you edit this question to clarify what you're trying to do, so that people don't get frustrated trying to figure out what you need.
Comment: A simple `plot(A$x, A$y)` (where `A` is your structure) shows that you may have some left-tail dependance, but nothing about the shape of the bivariate distribution. Yes, the very "uppermost" points in that plot seem to "trace" out the classic shape of a right-skewed density, but that doesn't mean anything; it's an optical illusion. $y$ itself *may* be gamma (see below in the answer and comments). Marginal $x$ certainly is not (it's bimodal).
Comment: +1 to the comment above. Also the rgamma function generates random values from the gamma distribution so that would not be the function you would want to "fit" the data.
Comment: Well if you plot y against x, it looks like the pattern of my data follows a gamma function. So, I am trying to compute the different parameters of the gamma function which could fit my set of data. Do you have a better approach i could do that?
Comment: Non-linear curve fitting is one approach; see the `nls` package in R as an example.
Answer: Please see update section below for clarification based on OP comments made whilst this answer was being posted.
In general, the standard gamma distribution has two parameters, a shape paramemeter and a scale or rate paramemeter, where rate = 1 / scale. R help for rgamma uses shape as the canonical form; using that, with a gamma density defined as:
$$
\large f(x) = \frac{x^{\alpha - 1}e^{-\frac{x}{\theta}}}{\theta^\alpha \Gamma(\alpha)}
$$
$\alpha$ is the shape parameter and $\theta$ is the scale parameter. The mean of the distribution is $\alpha\theta$ and the variance is $\alpha\theta^2$.
The simplest way to fit would be using the Method of Moments. Calculate the mean and variance of your data. Now you have two equations ($\hat{\mu} = \alpha\theta, \hat{\sigma}^2 = \alpha\theta^2$) so you can solve for $\alpha$ and $\theta$.
The other most common technique is tp use maximum likelihood estimation. That would require using a non-linear optimizer (like optim or nloptr) to solve for the parameters which minimimze the negative log-likelihood, which you could get using dgamma with log = TRUE.
You could set up a function like so:
GammaNLL <- function(pars, data){
  alpha <- pars[[1]]
  theta <- pars[[2]]
  return (-sum(dgamma(data, shape = alpha, scale = theta, log = TRUE)))
}

and pass that into nloptr as
Fit <- nloptr(x0 = c(guess1, guess2), eval_f = GammaNLL, lb = c(0,0), data = data,
              opts = list(algorithm = "NLOPT_LN_SBPLX", maxeval = 1e5))

Fit$solution will have your MLE estimates.
In your particular case, however, your observations are pairs, so either you need to fit a multivariate distribution, which is less simple, or you want to fit the gamma to $x$ and $y$ independantly, which can be done using either method above.
Hope that helps.
Update based on clarifications in question.
Plotting $y$ against $x$ looks as such plot(A$x, A$y, pch =16):

The fact that the "top" lookes vaguely like a gamma is irrelevant; this is a scatter plot, not a density.
A kernel-smoothed density estimates of the marginal of $y$ may indicate a gamma (or some other right-skewed distribution) plot(density(A$y, kernel = 'e')):

$x$ is bimodal, so it's marginal is certainly not gamma plot(density(A$x, kernel = 'e')):

So I think you need to re-formulate your question more like "is there a reasonable way to fit a relationship between $x$ and $y$"
Comment: I think some kind of modification would be needed to get the answer to match the question and the data.  It is indeed frustrating to see a question changed while you're writing out an answer.  That's why it's always a good idea to ask for clarification if you're uncertain about the interpretation or to wait for a response after a clarification has been requested. One thing you might do is delete the answer so that people don't downvote it--you can undelete it later if it turns out to be exactly what the OP was looking for.
Comment: This approach is hopeless: because the integral is much greater than $1$, the data do not represent points on a Gamma distribution at all and no Gamma density function comes anywhere close to such a set of values.
Comment: @whuber The marginal $y$ can be fit using either method (MoM gives $\theta \approx 508.9, \alpha \approx 2.17$; MLE: $\theta \approx 546.2, \alpha \approx 2.02$). The $x$ values are clearly  bimodal though, so any fit wouldn't be good, although MoM **will** give an answer, simply due to algebra. I did say the method wouldn't work if there was a need for a multivariate fit.
Comment: For clarification, please read the OP's comments to the question.
Comment: @whuber They must have been added as I was answering, as the question was pristine when I started. Do you suggest deleting this answer?
Comment: Thanks; Instead I added an update section explaining why I think the OP needs to reformulate the question.


Connection reset after partial page load on .net site

Question: We are trying to move a MS SQL vb.net website from one server to another. It works perfectly on the initial server but on the new server, most pages are fine but the home page, which has quite a lot of data using a number of sqldatasources with gridviews, repeaters and an update panel loads two of the three columns but doesn't finish loading, eventually timing out with a connection was reset error message from the browser.
We've tried removing the 3rd column but still get the issue, we've tried removing an update panel from the 2nd column and still get the issue. We have a version working with most stripped out but cannot really identify the problem and because this is working on the original server, and because the other page are working, don't really know what to do next. Tried using fiddler and SQL profiler to understand the problem but don't see anything.
Any suggestions on the approach to troubleshoot greatfully rec'd.
Comment: Could you please edit your question so it is more readable.
Answer: This is likely the HTTP server timing out as it is taking too long to render the page.  Try to create a temporary "test" page and replace the database content with mocked up content (i.e. faking the DB calls) there is probably something on that page that is taking way too much to load.  If this renders fine on initial server, think about the location of the new server, is it doing certain network hops to get to the database?  Is it slower to access the database than the original server?  This is what I would look into from what you describe above.


Is it possible to mock android services under unit tests?

Question: I'm trying to write unit tests for my android application and I want to mock my service class. I want to test some error behaviors in the service, such as connection errors or file not found.
To simplify my question, I started a new Android Project and created an Activity and a Service class:
MyAndroidProjectActivity.java
package br.org.venturus.android;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.TextView;
import br.org.venturus.android.service.MyService;

public class MyAndroidProjectActivity extends Activity {
    private MyService service;
    private ServiceConnection mConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName className, IBinder binder) {
            service = ((MyService.MyBinder) binder).getService();

        }

        public void onServiceDisconnected(ComponentName className) {
            service = null;
        }
    };
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        {
            Intent service = new Intent(this, MyService.class);
            startService(service);

            bindService(service, mConnection, Context.BIND_AUTO_CREATE);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // stop MyService
        {
            Intent svc = new Intent(this, MyService.class);
            stopService(svc);
        }
    }

    public void doChange(View view) {
        TextView tv = (TextView) findViewById(R.id.tvHello);

        tv.setText(service.getNewString());
    }
}

MyService.java
package br.org.venturus.android.service;

import br.org.venturus.android.R;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MyService extends Service {

    private IBinder binder;

    public MyService() {
        this.binder = new MyBinder();
    }
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    public class MyBinder extends Binder {
        public MyService getService() {
            return MyService.this;
        }
    }

    public String getNewString() {
        return getString(R.string.change);
    }

}

And I created a new Android Test Project with this unit class:
MyAndroidProjectActivityTest.java
package br.org.venturus.android.test;

import android.test.ActivityInstrumentationTestCase2;
import android.test.UiThreadTest;
import android.widget.Button;
import android.widget.TextView;
import br.org.venturus.android.MyAndroidProjectActivity;
import br.org.venturus.android.R;

public class MyAndroidProjectActivityTest extends
        ActivityInstrumentationTestCase2<MyAndroidProjectActivity> {

    private MyAndroidProjectActivity mActivity;
    private TextView tvHello;
    private Button btChange;

    public MyAndroidProjectActivityTest() {
        super("br.org.venturus.android", MyAndroidProjectActivity.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        // Get the activity and components
        {
            mActivity = this.getActivity();
            tvHello = (TextView) mActivity
                    .findViewById(br.org.venturus.android.R.id.tvHello);
            btChange = (Button) mActivity
                    .findViewById(br.org.venturus.android.R.id.btChange);
        }

    }

    public void testPreconditions() {
        assertNotNull(tvHello);
        assertNotNull(btChange);
    }

    @UiThreadTest
    public void testChangeButton() {
        assertEquals(tvHello.getText(), getActivity().getString(R.string.hello));
        btChange.performClick();
        assertEquals(tvHello.getText(), getActivity()
                .getString(R.string.change));
    }
}

When I run the unit tests, the pre conditions and the change button tests are fine. What I want to do, for instance, is to create a MyServiceMock and override the MyService.getNewString to return other value, and mock this object in the test.
Something like this:
MyServiceMock.java
package br.org.venturus.android.test.service;

import br.org.venturus.android.service.MyService;

public class MyServiceMock extends MyService {
    @Override
    public String getNewString() {
        return "This is the new value!";
    }
}

Is that possible?
Comment: I was not mocking the unit under test, I wanted to mock other components that are not the scope of my test.
Answer: Yes, it's possible and I think the example of the MyServiceMock.java above is also an alternative.
There are a few mocking frameworks out there that you can use for this.
I have some experience with Mockito.
You can just mock the MyService class and specify that when the getNewString method is called, return a string "This is the new value!".
MyService myServiceMock = Mockito.mock(MyService.class);

Mockito.doReturn("This is the new value!").when(myServiceMock).getNewString();

You can also use the Mockito.doThrow() method to throw an exception when a mock method is called:
Mockito.doThrow(new RuntimeException()).when(mockedList).clear();

//following throws RuntimeException:
mockedList.clear();

Comment: Setting expectations is the easy part, but how do you replace the service declared in the manifest started by the framework and all the binding lifecycle with the mock object you created: `myServiceMock`?
Comment: Exactly... Anybody with tips on how to replace the reular service with mocked service? Maybe by using dependency injection?