Mudar cor do input quando não tiver os dados validos?

Question: Esse código funciona:
this.state = {
      backgroundcolorQuatro: '',
      backgroundcolorSeis:'',
      backgroundcolorDez:'',
      quatro:'',
      seis:'',
      dez:''
    }

 validar = () => {
    if (this.state.quatro !== '4') {
      this.setState({backgroundcolorQuatro: 'red'})
      alert("Correto seria 4");
      return;
    }
    if (this.state.seis !== '6') {
      this.setState({backgroundcolorSeis: 'red'})
      alert("Correto seria 6");
      return;
    }
    if (this.state.dez !== '10') {
      this.setState({backgroundcolorDez: 'red'})
      alert("Correto seria 10");
      return;
    }
    alert("Success !!!");
  }

 clean = () =>{
    this.setState({backgroundcolorQuatro:'',backgroundcolorSeis:'',backgroundcolorDez:''})
  }

render() {
    var inputQuatro = {
      backgroundColor: this.state.backgroundcolorQuatro
    }
    var inputSeis = {
      backgroundColor: this.state.backgroundcolorSeis
    }
    var inputDez = {
      backgroundColor: this.state.backgroundcolorDez
    }
    return (

            2 + 2 =
            <input onClick={this.clean} style={inputQuatro} onChange={(e) => { this.setState({ quatro: e.target.value }) }}></input>

            3 + 3 =
            <input onClick={this.clean}  style={inputSeis} onChange={(e) => { this.setState({ seis: e.target.value }) }}></input>

            5 + 5 =
            <input onClick={this.clean} style={inputDez} onChange={(e) => { this.setState({ dez: e.target.value }) }}></input>

        <button onClick={this.validar}>Validar</button>

    );
  }
}
export default App;

Para uma tela com poucos campos funcionaria, mas se eu tivesse uma tela com 50 campos acredito que ficaria inviável fazer dessa maneira, pois cada INPUT teria um inputStyle e uma variável no State.
Sendo assim uma tela com 50 campos ficaria com 50 variáveis no state e 50 Style, e isso me parece claramente errado.
Answer: Você pode resolver esse problema de uma forma bem simplificada.
É importante você declarar a função no construtor para poder mudar o contexto da função.
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      bgColorQuatro: '',
    };
    this.validateQuatro = this.validateQuatro.bind(this);
  }

  validateQuatro(e) {
    if (e.target.value !== '4') {
      this.setState({
        bgColorQuatro: 'red'
      });
    } else {
        this.setState({
        bgColorQuatro: ''
      });
    }
  }

  render() {
    const {
      inputQuatroValue,
      bgColorQuatro,
    } = this.state;

    const styleInput = {
      backgroundColor: bgColorQuatro,
    }

    return (
      <React.Fragment>
        2 + 2 =
          <input
            style={styleInput}
            onChange={this.validateQuatro}
          />

      </React.Fragment>
    )
  }
}


Finding the correct formula for a mixed-effects linear regression model

Question: I have the following data:
## # A tibble: 525 × 8
##    Subject Group Type    ISI Label  MeanEMG MeanRRA MeanRRA2
##    <fct>   <fct> <fct> <dbl> <fct>    <dbl>   <dbl>    <dbl>
##  1 17      HC    BL        0 HC BL     41.4    1        1.28
##  2 17      HC    BL        4 HC BL     67.8    1.64     2.09
##  3 17      HC    BL        5 HC BL     51.3    1.24     1.58
##  4 17      HC    BL        8 HC BL     56.0    1.35     1.73
##  5 17      HC    BL       10 HC BL     79.7    1.93     2.46
##  6 17      HC    BL       15 HC BL    104.     2.51     3.21
##  7 17      HC    BL       20 HC BL    129.     3.13     3.99
##  8 17      HC    SWD       0 HC SWD    93.9    1        1.20
##  9 17      HC    SWD       4 HC SWD   107.     1.14     1.36
## 10 17      HC    SWD       5 HC SWD   142.     1.51     1.81
## # ℹ 515 more rows

I am attaching a summary plot of the variable of interest, MeanEMG, across distinct ISIs. On each plot, we separately show the distribution of MeanEMG for the two different levels of Group and Type.

I am interested in the effects of Group and Type on MeanEMG. I expect the overall distribution of MeanEMG to differ across ISI levels. In particular, I expect that MeanEMG is higher for higher values of ISI.
I am having trouble defining what the correct model would be. We have a random effect in Subject, evidently. But is ISI a random effect as well or a fixed one? Each Subject is exposed to the same number and same levels of ISI. In particular, ISI and Type are within subject categories, while Group is a between subject category.
Simple models, such as lmer(MeanEMG ~ Group * Type + (1|Subject) + (1|ISI), pdf) don't fit the model very well. What formula would be sensible to explore the effects I have described?
EDIT: Meaning of the variables and description of experiment.
Descritpion: Healthy controls and MDDs (Depressed) were subjected to two types of sleep sessions, BL (Baseline) and SWD (Sleep deprivation). After each session, brain stimulations were given to them and their responses were measured using EMG (electromyography). Some, but not all stimulations were paired with another. In paired stimulations, a second stimulation was given $x$ miliseconds after the first. The value of $x$ is called ISI (inter-stimulus interval).
So, the variables are

Group: Factor with Healthy Control or MDD (Depressive)

Type: Type of Sleep Session underwent prior to the experiment. Can be Baseline or SWD (Sleep deprivation).

MeanEMG: Average response to brain stimulations as measured by electromyography.

ISI: The interstimulus interval used in paired stimulations. Unpaired stimulations (a unique stimulation given) is represented by 0.

So, we could "read" the second row as follows to illustrate:

In Subject 17, a healthy control, after baseline (normal) sleep, the average response to those brain stimulations consisting of two paired-pulses separated by $4$ miliseconds, as measured by the electromyography, was $67.8$
Comment: It would be *really* helpful if you could explain what all of your variables mean, otherwise it is difficult to say for certain what model works here.
Comment: ISI would be fixed, probably. If you think MeanEMG responds to ISI linearly (or some other relationship), include it as a fixed term. Using it as a random effect, as you have in the final paragraph of your question, is treating it as a discrete variable. Which doesn't sound like it reflects your understanding of the scenario.
Comment: Your tibble shows `ISI` to be a numeric variable while random effects need to be categorical. Perhaps the software automatically makes that conversion, but it's safest to do that conversion yourself. Please edit the question to describe what your variables mean, as @ShawnHemelstrand has asked, and to state the hypothesis about them that you want to test. Provide that information by editing the question itself, as comments are easy to overlook and can be deleted.
Comment: I have cleaned and formatted the data so it is clearer, as well as included further explanation on the experiment in question and the meaning of the variables. Thank you all for taking the time to comment.
Comment: Thanks for adding that information. One follow-up: if unpaired stimulations take an ISI value of 0, what does the ISI value of -1 in your plot represent?
Answer: As ISI is a variable that's under experimental control, it should be included at least as a fixed effect in the model.* With a potentially continuous variable like ISI, you typically want to fit it flexibly, for example with a regression spline or other generalized additive model. That would account for baseline changes in MeanEMG associated with ISI.
With the ns() function in the R splines package, the model then might have the general form:
lmer(MeanEMG ~ Group * Type + ns(ISI,..) + (1|Subject))

where you choose the other arguments to ns() to provide the fitting flexibility you desire.
It's not completely clear how to handle the ISI values of $0$ and $-1$. It's not clear what the value of $-1$ represents. If the value of $0$ represents an unpaired stimulus, you should include an additional predictor indicating whether there was a paired stimulus. That would allow for a difference between the estimated MeanEMG without a paired stimulus and the extrapolated/interpolated estimate with 0 time between paired stimuli. This answer illustrates that approach to evaluating a continuous predictor that by definition can't have an actual value for some cases.
You might need to go even farther. If you think that ISI also influences the effects of Group, Type, or their combination, then you would need to include corresponding interaction terms. That can get tricky with a flexibly fit predictor like above for ISI. Frank Harrell discusses those issues and some useful compromises in Chapter 2 of Regression Modeling Strategies.

*In principle one might then include ISI also as a random slope in the model, to allow for differences in the association between ISI and MeanEMG among individuals. But the simple form of +(ISI|ID) would assume a linear association between ISI and EMG, and evaluating random slopes typically takes a lot of observations.


Customize Acumatica bulit-in dropdown list with conditions

Question: I have used the answer to Woody's question at
Is there a easy way to customize Acumatica build-in dropdown list? to customize several dropdown lists. Thank you for the guidance with that one. I want to further customize a different drop-down list based on the Class ID and the Status of an Acumatica Case. I am not sure at all how to achieve this. Can anyone provide advice please?
Comment: It's unclear what you are asking. Please specify the problem you encountered.
Comment: Sorry. For example, if the Class ID is "Technical Support", and Status is "Open" I want to offer a set of Reasons that applies to that scenario. If the Class ID is other than Technical Support, and the Status is Open, then the standard dropdown of Reasons applies. I do not know how to accomplish this.
Answer: I propose you to consider customizable selector, with which you can completely control all your data which will be displayed. Here is example of implementation.
Comment: Thank you very much for this response. I am also looking at this method, and think it just might be useful also for other more complicated customisations.
Comment: I have been unable to determine what the DRDocumentRecord.refNbr type is in the SelectCustomerContractAttribute function - I believe it needs to be replaced with CRCase in my application but am unsure. In reading the code, it is very clear what you are doing, and easy to understand that replacing items like ContractBillingSchedule in IEnumerable GetRecords with my requirements is what I have to do. Would you be able to point me in the right direction?
Comment: DAC class with refNbr type and RefNbr field. For now I don't have access to that code, so can't say exactly.
Answer: If you are able to write proper 'Search' BQL to get the result, you can use the PXSelector attribute. If you use 'Current' it will use the the current documents field value. So as per your case, you can use the current ClassID and Status to dynamically populate your selector.
Eg:
<code>[PXSelector(typeof(Search<DiscountSequence.discountSequenceID,
            Where<DiscountSequence.discountID, Equal<Current<DiscountSequence.discountID>>>>))]
</code>
Hope this helps.
Comment: I am having a look at this. Thank you for the response.


How does the shot clock work in pool?

Question: I was watching a little bit of a pool match. It appears that a 20-second shot clock was used, as they would sometimes display a countdown starting at 20.
But it's not clear to me how the shot clock worked. For example, at 45:35, the player takes a shot and makes it, and then the cue ball comes to a stop at 45:43. But then the shot clock doesn't start until 45:53. Then at 46:04, the shot clock is down to 9 seconds and it disappears, but the player hasn't taken his next shot yet. Then at 46:23, the shot clock reappears starting at 20, and the player takes his shot with 9 seconds left.
So my questions are:

When does the shot clock start?
What causes the shot clock to stop and reset before a shot is taken?
Answer: It appears different organizations/tournaments use different clocks.
This one looks to me like it's using a 30 second clock (starting after all the balls from the previous shot come to rest).  I think the TV graphics just don't bother showing the first 10 seconds of the count, but you can see the countdown "ring" is already about a third gone when the "20" appears.
In some tournaments, each player gets one time extension per rack.  WPA seems to prefer 25-second extensions.  To me it looks like the player has called for such an extension while considering the shot at 46:04.  When the clock reappears, it's about 30 seconds behind where it was previously, so this match might have used 30-seconds instead.

How does the shot clock work in pool?


create objects in member function

Question: The header is defined like
class MyClass_A;
typedef map<string, MyClass_A*> MyMap
typedef vector<MyClass_A*>      MyList

class MyClass_A
{
  // define some functions
}

class MyClass_B
{
public:
  void check(){ //create MyClass_A pointer to store in myMap and myList }
private:
  MyMap   myMap;
  MyList  myList;
}

The main function is like
int main()
{
  MyClass_B class_B;
  class_B.check();
  /*
    do some works
  */
}

I want to define MyClass_A objects in check which is a member function in MyClass_B. And the objects would not destruct until end the main function.
I have tried some methods but the objects would remove when leave the check member function. Is there any solution?
Comment: @A.S.H: It works! Thank you.
Comment: *the objects would remove when leave the check member function* -- uh, as far as i know, in C++ there is no garbage collection like in Java (where you could lose an instance if you never reference it). at least, could you give a clue on what *do some works* do and how `void check()` works. it might give some insight.
Comment: You should create these objects with `new`, so that they dont die when you leave the function `MyClass_B::check()`...
Comment: The names `_MAP` and `_LIST`, aside from being unconventional, are not legal in C++.  Names that start with an underscore must not have a second underscore or a capital letter as their second character.
Comment: Objects declared in `check` function will be destroyed as soon as the function's execution is complete. To do what you are trying to do, you need to declare that object outside `check` function.
Answer: Rather than storing raw pointers, use smart pointers:
class MyClass_B
{
public:
  void check(){
    //create MyClass_A pointer to store in myMap and myList
    Ptr_A obj = std::make_shared<MyClass_A>();
    myMap["hello"] = obj;
    myList.push_back(obj);
  }

private:
  typedef std::shared_ptr<MyClass_A> Ptr_A;
  std::map<std::string, Ptr_A> myMap;
  std::list<Ptr_A> myList;
}

Now the lifetimes of MyClass_A instances are managed automatically.  When an instance of MyClass_B is destroyed, the objects it contains will be destroyed also.
Comment: Thank you for the response. Is it possible to declare MyClass_A pointer inside or out the check function to this problem?
Comment: @ycliu: I don't know what you're asking now.
Comment: Just use `map` instead of `map`. And the problem is solved by using `MyClass_A* tmp = new MyClass_A`.
Comment: @ycliu: You can do that but then you will need to be very careful not to leak memory.

create objects in member function


Azure Portal --> Virtual Machine (Default Directory) page issue?

Question: I am very new to Azure Portal.
I have noticed the following for Subject mentioned page.
Once I open the Virtual machines page

The (Assign Tags,Start,Restart, Deleted, Services) are comes to be disable and it should be? as I have not selected any of the VM checkbox.
However once I select any of the checkbox then above mentioned buttons are enabled.
I deselect the checkbox but buttons remains enabled.
  So, behavior in *1 and *3 is different. I was expecting that buttons shall disable again as I have not selected any VM.

Moreover, I can delete, assign tags etc, even without selecting the VM.
Sorry if this question is not relevant here and please provide any information if my expectation is wrong as I am very new to Azure.
Answer: It is an odd user experience, but when you first visit the page (what you described in #1) there are no VMs selected and it has no context.  When you un-check the check box the the row and VM are still selected.  If you initiate one of those actions you will find that the highlighted row is the item you are changing.


What are the precise/exact halting conditions for batch Gradient Descent (GD) when working with data with random noise?

Question: I was trying to understand the different alternatives there are for halting batch gradient descent and concluding that one has reached some minimum (local or global). In the presence of noisy data (similar to what "real" data is) the empirical risk curve might not look very convex in every iteration of GD (right?even if the curve is provably convex?). Hence, I was wondering, in this scenario with noise (and most similar to the real world), how does one decide when a (global or local) minimum has been reached?
I did see the following question How to define the termination condition for gradient descent? trying to address something similar but wasn't quite sure if the current answer addressed the issue in enough detail. In particular, the third bullet point says:

reltol, which is like your second suggestion--stop when the
  improvement drops below a threshold. I don't actually know how much
  theory there is on this, but you'll probably tend to get lower minima
  this way than with a small maximum number of iterations. If that's
  important to you, then it might be worth running the code for more
  iterations.

in particular, the way I interpret this suggestion is to use some kind of update rule that has a while loop with a condition similar to:

"While current error - previous error keeps decreasing, then keep doing batch gradient descent (GD), if the decrease is not large enough or if there is an increase in the cost then stop"

That kind of update rule would make total sense if we knew our curve was perfectly convex, however, with noisy data (or real data), I'd suspect that this terminating condition might not a good idea (I might be totally wrong, hence the question). So the things I'd like to address are:

Is it reasonable to expect in batch gradient descent that every step of GD that the training/total cost is to decrease? Even in the presence of noise?
Is basing our halting condition on a single iteration ever a good idea on data with randomness? Might we see a moment when out cost increases for a tiny bit and the decreases? Or is that sort of weird behaviour only something one would expect from stochastic gradient descent?
Is there a situation where you can mathematically prove that batch GD monotonically decreases the error cost?
Is using something like a "moving average" a better idea? What I mean by that is that for every iteration up to the current one we have an average of the previous $m$ training costs and once this moving average stops decreasing in a significant way (or increases) then we halt GD and output the current parameter of our model. Is this reasonable for batch gradient descent or does this only (potentially) make sense for stochastic gradient descent?
Another thing could be to track the size of the gradient? If the gradient is exactly zero, then obviously we've reached a critical point (we'd probably need to do further tests to make sure its not a stadle point or inflection point...), is this a good idea or what do people actually use?
Answer:
That kind of update rule would make total sense if we knew our curve was perfectly convex, however, with noisy data (or real data), I'd suspect that this terminating condition might not a good idea (I might be totally wrong, hence the question).

You kept the cost function completely out of the picture! While your argument holds truth when using root-mean-square deviation (RMSD), it falls apart when you consider cross-entropy error. You might refer to Andrew Ng's Coursera course. He actually explains this concept very well in one of his lessons (see Week 3: Logistic Regression Model).
Comment: Sorry if I misunderstood the video and/or your answer, but doesn't the rule I suggested work for any convex function? i.e. if the empirical risk is convex, doesn't it work to always make sure the total/training cost is always going down? (obviously if the training cost function is convex, its due to the nature of f and the nature of the cost function, the reason I omitted it, since the convexity of the training error clearly depends on the nature of both cost function and predicting function)
Comment: btw, my question doesn't even really care about global minimum, I just care about stopping at any valid minimum.
Comment: "But doesn't the rule I suggested work for any convex function?" What would be the problem with that? I think what you actually refering to is the Rashomon effect: "there is often a multitude of diferent descriptions [equations f(x)] in a class of functions giving about the same minimum error rate." See Breiman for further explaination of this concept.


Primeface uploadFile + graphicImage: Fazer upload de imagem e exibir sem refresh

Question: Estou começando a programar no jsf + primefaces. A muito tempo atrás trabalhei com JSP(java 1.4) e estou meio perdido.
Estou querendo fazer o upload de uma imagem e que ela seja exibida logo abaixo.
imagens.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head>

</h:head>
    <h:form enctype="multipart/form-data">

</h:form>

FileUploadView.java
package br.com.testes;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.ejb.Stateful;
import javax.inject.Named;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import lombok.Getter;
import lombok.Setter;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.UploadedFile;
import org.primefaces.model.StreamedContent;

@Named(value = "fileUploadView")
@ManagedBean
@Stateful
public class FileUploadView {

    private UploadedFile file;

    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }

    @Setter
    private static StreamedContent imagem;

    public StreamedContent getImagem() throws IOException {
        return imagem;
    }

    /**
     * Creates a new instance of FileUploadView
     */
    public FileUploadView() {
        imagem = null;
    }

    public void upload(FileUploadEvent evt) {
        file = evt.getFile();

        try {
            if (file != null) {
                System.out.println(file.getContentType()+"\n\n"+file.getFileName());
                InputStream is = file.getInputstream();
                imagem = new DefaultStreamedContent(is, file.getContentType());
                FacesMessage message = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
                FacesContext.getCurrentInstance().addMessage(null, message);
            }
        } catch (Exception e) {
            FacesMessage message = new FacesMessage(e.getMessage());
                FacesContext.getCurrentInstance().addMessage(null, message);
        }
    }

    public void upload() {
        if (file != null) {
            FacesMessage message = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, message);
            imagem = new DefaultStreamedContent(new ByteArrayInputStream(file.getContents()), file.getContentType());
        }
    }

    public void handleFileUpload(FileUploadEvent event) {
        FacesMessage message = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

}

Ao tentar fazer o upload não exibe a imagem.
Answer: Eu no Html uso o jquery para fazer isso
no meu codigo HTML eu uso:

<img src="" id="imagem"

<input type="file" id="upload" />

No código JavaScript na própria pagina

espero que te ajude :)
Comment: O problema é que eu vou precisar da imagem denrto da classe/objeto, sendo assim, não me ajudaria fazer por JS
Comment: Pois é, essa resposta não compreende o tipo do problema.


How to compute $\int_C \frac{z^4}{z^5-z-1}$ where $C$ is the radius $2$ circle centred at $(0,0)$?

Question: Apparently, because all the finite poles are within the circle, it is good enough to use the residue at infinity. But I'm not sure how to even show all the roots are bounded in norm by 2.
Comment: How about Rouche's theorem?
Answer: Step1: all the roots of $z^5-z-1$ are simple and lie inside the region $\left|z\right|\leq\frac{3}{2}$.
The roots are simple because $\gcd(z^5-z-1,5z^4-1)=1$, and they lie in the region $\left|z\right|\leq\frac{3}{2}$ because if $\left|z\right|=C>\frac{3}{2}$, $\left|z\right|^5 > |z|+1 \geq |z+1|$ contradicts $z^5=z+1$.
Step2: by Cauchy's theorem, the given integral equals $2\pi i$ times the sum of the residues of the function $f(z)=\frac{z^4}{z^5-z-1}$, that also equals $\oint_{|z|=R}f(z)\,dz$ for any $R>\frac{3}{2}$. However:
$$ \oint_{|z|=R} f(z)\,dz - \oint_{|z|=R}\frac{dz}{z} = o(1) $$
for $R\to +\infty$, hence the given integral simply equals $\color{red}{2\pi i}$. This happen because for any $z$ far from the origin $f(z)-\frac{1}{z}=O\left(\frac{1}{|z|^5}\right)$, hence by integrating $f(z)-\frac{1}{z}$ over the circle $|z|=R$ we get something that is $o(1)$ for $R\to +\infty$.
Answer: Use Rouche's Theorem: on $\;|z|=2\;$ , we have that $\;|z+1|<|z^5|\;$ , so both $\;z^5\;$ and $\;z^5-z-1\;$ have the same number of roots in $\;|z|<2\;$ .
Define now $\;f(z):=\cfrac{z^4}{z^5-z-1}\;$ , and let now $\;z_k\;,\;\;k=1,2,3,4,5\;$ ,  be a root of our quintic, then as all these roots are simple we get that
$$Res_{z=z_k}(f)=\lim_{z\to z_k}(z-z_k)f(z)=\lim_{z\to z_k}\frac{z^4}{5z^4-1}=\frac{z_k^4}{5z_k^4-1}$$
Before going into this, you may want to observe that the roots of $\;z^5-z-1\;$ are: one real root and two pairs of complex non-real conjugate roots.
Comment: The residue computation and the distinction between real and non-real roots are actually irrelevant for evaluating the given integral.
Comment: @JackD'Aurizio Perhaps, yet to avoid doing calculations on residues at infinity, which apparently posed some problem to the OP, the above could possibly help...
Comment: of course it is a viable strategy, but I think it is easier to notice that $f(z)$ is very close to $\frac{1}{z}$ if $|z|$ is pretty large.
Comment: @JackD'Aurizio Yes, indeed: it's way easier in fact to work out even with the very residue at infinity. I really don't understand well how you accomplised your last equality $\;=o(1)\;$ . I would have directly go with the residue at zero of $\;-\frac1{z^2}f\left(\frac1z\right)\;$ ... DO you have any reference?
Comment: It is pretty simple, indeed: $f(z)-\frac{1}{z}=O\left(\frac{1}{|z|^5}\right)$, hence by integrating $f(z)-\frac{1}{z}$ over the circle $|z|=R$ we get something that is $o(1)$ for $R\to +\infty$. $O\left(\frac{1}{R^4}\right)$, actually.
Answer: Let$$g(z)=\frac{5z^4-1}{z^5-z-1}\text{, let }h(z)=\frac1{z^5-z-1}.$$ and let $r$ be the greatest absolute value of the roots of $z^5-z-1$. Then $f=\frac{g+h}5$ and therefore $\int_Cf=\frac15\bigl(\int_Cg+\int_Ch\bigr)$. By the argument principle, and because $r<2$, $\int_Cg=5\times2\pi i=10\pi i$. On the other hand, if $R>r$, then the integral of $h$ along the circle of radius $R$ around $0$ does not depend on $R$. Furthermore, its limit when $R\to\infty$ is equal to $0$. Therefore$$\int_Cf=\frac{\int_Cg+\int_Ch}5=\frac{10\pi i+0}5=\color{red}{2\pi i}.$$


Given conditions on differentiability, what can we say about second derivative?

Question: Let $f:[0,10] \rightarrow [10,30]$ be a continuous and twice differentiable function such that $f(0)=10$ and $f(10) =20$. Suppose $\mid f'(x) \mid \leqslant 1 \; \forall x \in [0,10]$. Then the value of $f"(5)$ is
$(a) 0$
$(b) 1/2$
$(c) 1$
$(d) Can't be determined$
My trial:
We need the function to be twice differentiable. So let $f"(x)=c$ where $c$ is a constant.
Then $f(x) =\frac{cx^{2}}{2} + dx + e$ where $c,d,e \in \mathbb{R}$
Also, $f(0) =10$ implies $e=10$
and $f(10) = 20 \;$ implies $ \; 50c + 10d =10$ or $5c + d=1$
Now, $f'(5) = 5c +d = 1$ (suprise, shawty!)
therefore $c = \frac{1-d}{5} , d \in \mathbb{R}$
How to proceed? what values of $d$ to chooses such that $\mid f'(x) \mid \leqslant 1$
Any other easier approach is also welcome. Thanks. Can we somehow use MVT or Brower's Fixed Point here?
Answer: You cannot assume that $f''$ is constant (though it will turn out that it is).
Assume $f'(a)<1$ for some $a\in[0,1]$. Then by continuity(!) of $f'$, there exists an interval $[a,b]$ and a number $q<1$ with $f'(x)<q$ for all $x\in[a,b]$.
Then
$$ \begin{align}10&=f(10)-f(0)\\
&=\int_0^{10}f'(x)\,\mathrm dx \\
&=\int_0^{a}f'(x)\,\mathrm dx+\int_a^bf'(x)\,\mathrm dx+\int_b^{10}f'(x)\,\mathrm dx\\
&\le \int_0^{a}1\,\mathrm dx+\int_a^bq\,\mathrm dx+\int_b^{10}1\,\mathrm dx\\
&=a+(b-a)q+10-b\\&=10-(b-a)(1-q)\\
&<10,\end{align}$$
contradiction.
Therefore $f'(x)=1$ for all $x$.

In fact, let's forget about the second derivative, i.e., start with once differentiable $f\colon [0,10]\to [20,30]$ with $f(0)=20$, $f(10)=30$, and $f'(x)\le 1$ for all $x$. Then this is enough to show $f(x)=x+20$ (and consequently, $f''$ exists and is identically $0$):
Consider $x$ with $0<x<10$

Assume  $f(x)>x+20$. Then by the Mean Value Theorem, there exists $\xi$ between $0$ and $x$ with
$$f'(\xi)=\frac{f(x)-f(0)}{x-0}>\frac{(x+20)-(0+20)}{x} =1,$$
contradiction.
Assume $f(x)<x+20$. Again by the mean value theorem, there eixts $\xi$ betwewn $x$ and $10$ with
$$f'(\xi)=\frac{f(10)-f(x)}{10-x}>\frac{30-(x+20)}{10-x} =1,$$
contradiction.
Therefore, the only remaining possibility $f(x)=x+20$ remains.
Comment: So you mean to say that the function is discontinuous at 10? As $f(10) = 20$
Comment: @ Hagen von Eitzen Kindly see above comment. I don't know whether it was directed to you or not by the platform as I had not tagged you directly...Hence, tagging you now.
Comment: I think it should be $f(x) = x +10$ for all values between 0 and 10 and the functional values at 0 and 10 be as given by definition. The second argument which uses 20 can be replaced by 10 if we do it more generally! Thoughts?
Answer: Hint
One can prove that $f'(x)=1$ for all $x\in [0,10]$.
Comment: The answer given by @Hagen von Eitzen contradicts your hint as it is discontinuous at $x=10$ and therefore not differentiable at that point. Was waiting for Hagen von Eitzen to reply back, but seems that he/she/ze is busy at the moment.
Comment: @KaranKumar: You should check the definition of being differentiable on $[0,10]$. There is no contradiction anywhere.


Show a Div first and then Submit on second click of button in a form

Question: I have a form with multiple divs with same names (full-width). They all are on the same level. One of them is hidden (with a class hide). What I want is that if I select Submit, it should not submit, first hide all the brother divs of the hidden div (in this case full-width) and unhide the one with the class hide.
Now when I press again, it should just submit the Form.
JSFiddle is here:- http://jsfiddle.net/xmqvx/2/
Answer: Your code had a couple issues:

You used event.preventDefault but passed event in as e - should be e.preventDefault
Your ID selector targeted an ID that didnt exist (changed to #submit-this)

The working code:
$("#submit-this").click(function (e) {
    e.preventDefault();
    if ($(".full-width").hasClass("hide")) {
        $(".full-width").hide();
        $(".full-width.hide").removeClass("hide").show();
    } else {
        alert("Submitting");
        $("#this-form").submit();
    }
});

http://jsfiddle.net/xmqvx/4/
Comment: Thank you. I should be more cautious :)
Comment: @Steve -- No problem, be sure to accept an answer if it accomplished what you were looking for,.
Answer: You could also take advantage of JavaScript's closures like so, to avoid having your behavior be dependent on your UI:
$(document).ready(function () {
    var alreadyClicked = false;
    $("#submit-this").click(function (e) {
        e.preventDefault();
        if (alreadyClicked) {
            $('#this-form').submit();
        } else {
            $('.full-width').hide();
            $('.hide').show();
            alreadyClicked = true;
        }
    });
});

Comment: Thanks a lot Jeff. You just made it so easy.


After update to Node 10-alpine - ERR_STREAM_CANNOT_PIPE

Question: After I updated our server node JS to Node 10-alpine version I started to get next error

Error [ERR_STREAM_CANNOT_PIPE]: Cannot pipe, not readable.

I have to mention that with node 8-alpine this code is working (I tried with rollback)
In my code I am trying to return file from GCloud:
try {
        const file = await
         gcs.bucket(`BUCKET_NAME`).file(filePath);

        if (file) {
            const results = await file.getMetadata();
            const stream = await file.createReadStream();
            return res.pipe(stream);
            else {
                return send(res, 403)
            }
        }
        else {
            return send(res, 404);
        }
    } catch (err) {
        console.error(err);
        return send(res, 500);
    }

Is any one met such issue after upgrade to node -10 -alpine?
Answer: Exactly what the error says. res.pipe(steam) attaches a writable stream, stream to the readable stream res. But stream is a stream.Readable. Use fs.createWriteStream(...) or file.createWriteStream(...) instead. This might have worked before because your gcs.bucket(...).file(...) function returns a file with a writable file descriptor. So it might be a case of duck typing gone wrong.


For an average Champions League team, is it financially more worth it to go through to knockout stages or drop down in to Europa League?

Question: 3rd placed teams in the Champions League group stages go into the Europa League. I was thinking, assuming an average Champions League team, is it more worth it (purely financially speaking) to go into the knockout stage (and risk getting knocked out at the next rounds), or drop down into the (potentially easier) Europa League and possibly go all the way to the final / win it?
Winning the Europa League has the ultimate reward as a spot in the following year's Champions League which is also financially rewarding in itself.
Comment: What would be the point in dropping out of UCL *and not making money **now*** in order to gain promotion back and *only make money two years later*?
Comment: Interesting question. I think most of the teams that drop down into Europa League don't really have a choice in the matter. They have to fight pretty hard to finish 3rd.
Comment: Because, say you are likely to draw one of the big teams like Barcelona or PSG or Real Madrid in the First Knockout Round with one match in the group stage remaining, as an average team you'll only earn financially from one set of home/away matches assuming you'd lose. However, your level of opposition for finishing 3rd and going to the EL may be lower and may be easier to win. Risk/reward?
Comment: Do you also count the attendance earnings? UCL 8th finals against a big club will have you sell all your home tickets. In Europa League, stadiums are more that half empty at early stages.
Answer: Reaching the eighth-finals of Champions League and being eliminated: worst case scenario
Finishing second with four draws and two loses will grant you 4x0.9 = 3.6 million euros.
For reaching the eighth-finals, add 9.5 million euros.
So, the team will earn 13.1 million euros.
Finishing 3rd in group stages, then winning the Europa League: best case scenario
Finishing third with four wins and two loses will grant you 4*2.7 = 10.8 million euros.
Then from the sixteenth-finals to winning the Europa, add 14 million euros.
So, the team will earn 24.8 million euros.

So in theory, you can have configurations where Europa League could be more profitable, but that is very unlikely and way too risky. And Europa is not that easy, a lot of good teams are playing in it and reaching the finals is very hard.
Other sources of income
Television, stadium attendance, sponsors incomes are higher with the UCL that EL.
 Sources: UCL Prize money, EL Prize money
Comment: The difference for finishing 2nd with 4 draws or 3rd with 4 wins should not be applied to the calculation, because that has nothing to do with deliberately dropping out of the UCL to make more profit in the EL. It makes more sense to only include the money rewarded *after* the group stage.
Comment: @dly, my answer is based on extreme (almost unlikely) cases to compare the worst you can make with UCL 8th and the best you can make by dropping out UCL to EL. To me an hypothetical team that would deliberately finish third (to try to maximize profit in EL), would also try to maximize profit during the group stage.
Comment: @dly, in other word I was kind of being the lawyer of OPs idea to show the maximum profit you can make through EL, but also showed it was very unlikely.
Comment: I see, but min-maxing the profit from the whole competition doesn't compare the earnings from the end of the group stage until the end of the competition (which is primarily what this question is about), that's why I suggested to remove the group stage results.
Answer: No, it's probably not worth the risk.
Reaching the knockout stage of the Champions League alone is worth 9.5 Million €, even if you get knocked out directly. Also you get a piece of the big cake... TV money and some cash based on the team's UEFA coefficient.
In the Europa League you'd have to reach the final in order to make that much money (~ 10 Million Euros). Surviving 4 rounds there is just as risky as playing a top tier team in the UCL and unlike in the UCL you have to win. The UCL prize money is guaranteed and surviving one round will net you a lot more.


Flask, jinja2 - Dynamically append templates one after another

Question: I am building a chatbot. There are few child templates like login.html, messages.html, transaction.html, etc. I want to append these templates in base.html dynamically. I am extending base.html in all these templates. My problem is only one template is rendered at a time. Is there any solution for appending these templates one after another? I have used {%include%} but it's a static approach. I need dynamic.
printer.py looks like -
@app.route('/respond', methods=['GET','POST'])
def respond_def():
   message = request.form['message_input']
   if message == "l":
       return render_template('printer/login.html')
   elif message == "t":
       return render_template('printer/transactionID.html')

base.html looks like -
//some code here

    {% block template %}{% endblock %}

//some code here

message.html looks like -
{% extends "base.html" %}
{% block template %}

 Message template called

{% endblock %}

Answer: I resolved it.
I made a list of templates in printer.py and then appended those templates in base.html whenever user asked for it.
printer.py
dictionary = []
// append name of template in this whenever needed.
return render_template('printer/base.html', dictionary=dictionary)

base.html
{% for d in dicts %}
{% set template = 'printer/' + d + '.html' %}
// can add conditions for different templates
{% include template %}
{% endfor %}


Why doesn't R's arima transform parameters when optimizing using CSS?

Question: According to the manual the arima function in R doesn't transform parameters when optimizing using CSS. Is there a particular (statistical) reason for this?
Answer: Conditional Sums of Squares (CSS) has a static one off solution based on the data that does not do recalculation based on the parameter estimates that due to noise variability could lead to non-stationary estimates http://www.stat.berkeley.edu/~aditya/resources/LectureTHIRTEEN.pdf. On the other hand, Maximum Likelihood (ML) estimation has an iterative process of obtaining partial autocorrelation estimates from the data and initial ARIMA parameter estimates, which then with new partial autocorrelation estimates obtains new ARIMA parameter estimates and so on and so on. Based on a variation of Jones (1980), partial autocorrelation transformation is done on potentially theoretically impossible estimated values to the theoretically constrained domain to assure that non-stationary estimates are not provided. Thus, provided the CSS method, transform.pars is not possible. However, CSS may provide a reasonable initial estimate to speed up calculation of a slower, but stationary, ML estimation process. This is why method = CSS-ML + transform.pars = TRUE is the default method for arima() in R.
Comment: Could you add a full reference for "Jones (1980)", as you'd cite it in an academic paper? It would be difficult for an interested reader to pin it down without more information, especially as Jones is such a common surname!
Comment: Let's see if I actually become a regular contributor now..."Maximum Likelihood Fitting of ARMA Models to Time Series With Missing Observations" -Richard H. Jones; 1980. Page 6, Section 6. Reparamatrizing for Stability.


Basic create component test failing with MoJs

Question: I have a component that is using the animation library Mojs. The create component test that comes out of the box with the spec.ts file is failing because of MoJs elements. I am not sure how to provide this library in the spec.ts file so that at the least this test for the component successfully creating passes.
The error I am getting is: 'Cannot read property 'CustomShape' of undefined'
the implementation of this CustomShape looks like:
    class paperOutlineTopCorner3 extends mojs.CustomShape {
     getShape () { return '<path d="123XYZ"/>'; }
    }

my current spec.ts file:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { CallbackComponent } from './callback.component';
import { requiredTestModules } from '../testing/import.helpers';

describe('CallbackComponent', () => {
 let component: CallbackComponent;
 let fixture: ComponentFixture<CallbackComponent>;

beforeEach(async(() => {
 TestBed.configureTestingModule({
  declarations: [ CallbackComponent ],
  imports: [requiredTestModules]
})
.compileComponents();
}));

beforeEach(() => {
 fixture = TestBed.createComponent(CallbackComponent);
 component = fixture.componentInstance;
 fixture.detectChanges();
});

it('should create', () => {
 expect(component).toBeTruthy();
});
});

any help/suggestions would be much appreciated
Answer: First you'll have to have your mojs object defined.
Hopefully there is a library you can install into your node_modules folder?
After you have the mojs definitions in the node_modules folder you can import it into the file and as long as mojs.CustomShape is defined in that import you should be good to go.
you might be able to do something like
npm install mojs

and then to import it, you can try a couple of different things:
i'd try require:
const mojs = require('mojs');

or import:
import * as mojs from 'mojs';

it's even easier if the mojs library has been 'typed' already.
also can you build correctly?  but only get the error when testing?  that's usually an indication that something from your .module file needs to be copied into the .spec file.
hope that helps
Comment: MAN! my problem was the import line. I had import mojs from 'mo-js';  Thanks for the much needed help
Comment: Sorry about that. Enjoy the bounty while I enjoy my sanity coming back.
Comment: glad to help! if you dont mind, i think you might have to click the bounty button under the votes, the points may just go away if not


how ssh to differenet hosts on same network easily

Question: we have a lot of servers on the same network, 220.127.116.11/24. I have to ssh to several server a day quite often. Right now I do like this:
ssh firstname.lastname@example.com
ssh email@example.com
ssh firstname.lastname@example.com

With this simple command there two problems:
1. too long - I always need to type the host space
2. sometimes I forget the address completely
Is there any way to replace the host space with a string? like ssh user@net3 .. ssh user@net32 maybe I can manually fill up the /etc/hosts file but is there any more sophisticated solution for this?
Comment: You can use host-based authentication when ssh server use predefined user to log in with ssh-key accordingly to the user's host. Then you can login simply like that: `ssh server1` where `server1` is name assigned to the 126.96.36.199 in the `/etc/hosts`
Answer: By default ssh tries to log in with the user account it's currently launched on the host you are connecting from. So, if all of the hosts can same accounts database, there's no need to specify user. Plus, if the DNS is properly configured, including search directive in the /etc/resolv.conf (or hostnames are configured in the /etc/hosts file), you can use the short form
ssh host
I cannot propose any shorter way of connecting.
Comment: so would be good to set up a DNS on this network?
Comment: Actually DNS of some sort is required in just any network. :)
Answer: I would suggest ~/.ssh/config as a solution. Here you can defined how the ssh client connects with any server.
Try

Host Server01
Hostname 126.96.36.199
User user

Should now be able to connect per

ssh server01
Comment: yes, you need to define it for all servers, but you can also generate this list simply if you have continues list of servers in the address block
Comment: yes I would have mentioned ssh config file - but still I need to define for this entry for all the servers


Erro ao enviar dados de formulário Ionic + PHP + MySQL

Question: Estou tentando enviar dados de meu formulário, já todo validado para meu banco de dados em MySQL com PHP, mas me retorna o erro a seguir e não envia:

O que posso esta fazendo de errado? Preciso desta ajuda.
Meu Controller:
    (function() {
    "use strict";

    angular.module("nhaac").controller("serVovoCtrl", function($scope, Data, $ionicScrollDelegate){

         // ENVIAR DADOS
    $scope.cadastroVovo = function(vovo) {
            console.log(vovo);
            Data.setData(vovo).success(function(data) {
                console.log(data.data);
                console.log("imprimiu console data");
                alert(data);
            }).error(function(data) {
                alert(data? data: "Não foi possivel cadastrar");
            });

        console.log("Vai imprimir o vovos");
        console.log(vovo);

    };

    });
})();

Meu Service:
    (function(){
    "use strict";

    angular.module("nhaac").value("Config", {

        getUrl: "http://vovocooks.com.br/admin/apis/put/"

    });

    angular.module("nhaac").service("Data", function($http, Config){

        //cadastro
        this.setData = function(dados){
         return $http({
                method: "POST",
                url: Config.getUrl + "rest-api.php",
                data: dados,
                headers : {
                                'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
                            }
            });
        };

    });
})();

Minha View (Form):
     <ion-view view-title="Tornar uma Vovó Cook" hide-nav-bar="false" >

            <ion-content delegate-handle="top" lazy-scroll >

Cadastro de novos Cozinheiros

            <form name="formCadastroVovo">

                        Nome
                        <input type="text" placeholder="Nome" name="nome" ng-model="vovo.nome" ng-required="true">
                        Pereencha o campo nome corretamente!

                        Email
                        <input type="email" placeholder="Email"  name="email" ng-model="vovo.email" ng-required="true">
                        Pereencha o campo email corretamente!

                        CPF ou CNPJ
                        <input type="number" placeholder="CPF ou CNPJ"  name="CPF" ng-model="vovo.CPF" ng-required="true">
                        Pereencha o campo CPF ou CNPJ corretamente!

                        Identidade
                        <input type="text" placeholder="Identidade" name="identidade" ng-model="vovo.identidade" ng-required="true">
                        Pereencha o campo Identidade corretamente!

                        CEP
                        <input type="number" placeholder="CEP"  name="cep" ng-model="vovo.cep" ng-required="true">
                        Pereencha o campo CEP corretamente!

                        Logradouro
                        <input type="text" placeholder="Endereço" name="logradourro" ng-model="vovo.logradourro" ng-required="true">
                        Pereencha o campo Endereço corretamente!

                        Número
                        <input type="text" placeholder="Número"  name="numero" ng-model="vovo.numero" ng-required="true">
                        Pereencha o campo Número corretamente!

                        Complemento
                        <input type="text" placeholder="complemento" name="complemento" ng-model="vovo.complemento">

                        Bairro
                        <input type="text" placeholder="Bairro" name="bairro" ng-model="vovo.bairro" ng-required="true">
                        Pereencha o campo Bairro corretamente!

                        Cidade
                        <input type="text" placeholder="Cidade" name="cidade" ng-model="vovo.cidade" ng-required="true">
                        Pereencha o campo Cidade corretamente!

                        Estado
                        <input type="text" placeholder="Estado" name="estado" ng-model="vovo.estado" ng-required="true">
                        Pereencha o campo Estado corretamente!

                        Responsável por Contato
                        <input type="text" placeholder="Responsável por Contato" name="responsavel_contato" ng-model="vovo.responsavel_contato" ng-required="true">
                        Pereencha o campo Responsável corretamente!

                        Telefone Fixo
                        <input type="number" placeholder="Telefone Fixo" name="telefone_empresa" ng-model="vovo.telefone_empresa">

                        Celular de Contato
                        <input type="number" placeholder="Celular de Contato" name="celular" ng-model="vovo.celular" ng-required="true">
                        Preencha o campo Celular corretamente!

                        Senha
                        <input type="password" placeholder="Senha"  name="senha" ng-model="vovo.senha" ng-required="true">
                        Pereencha o campo senha corretamente!

            </form>

            <button class="button button-full button-positive" ng-disabled="formCadastroVovo.$invalid" ng-click="cadastroVovo(vovo)">Enviar</button>

            </ion-content>

    </ion-view>

Meu PHP:
<?php

header("Access-Control-Allow-Origin:*");
header("Content-Type: application/html; charset=UTF-8");

    //formulário
    $data = file_get_contents("php://input");
    $objData = json_decode($data);

    // TRANSFORMA OS DADOS

    $CPF = $objData->CPF;
    $bairro = $objData->bairro;
    $celular = $objData->celular;
    $cep = $objData->cep;
    $cidade = $objData->cidade;
    $email = $objData->email;
    $estado = $objData->estado;
    $identidade = $objData->identidade;
    $logradourro = $objData->logradourro;
    $nome = $objData->nome;
    $numero = $objData->numero;
    $responsavel_contato = $objData->responsavel_contato;
    $senha = $objData->senha;
    $telefone_empresa = $objData->telefone_empresa;

    // INSERE OS DADOS
    $db = new PDO("mysql:host=ohostaqui;dbname=vovocooks_db", "vovocooks_db", "rain14570");

    if($db){
        $sql = "INSERT INTO fornecedores VALUES (CPF, bairro, celular, cep, cidade, email, estado, identidade, logradourro, nome, numero, responsavel_contato, senha, telefone_empresa) VALUES ('".$CPF."', '".$bairro."', '".$celular."', '".$cep."', '".$cidade."', '".$email."', '".$estado."', '".$identidade."','".$logradourro."', '".$nome."', '".$numero."', '".$responsavel_contato."', '".$senha."','".$telefone_empresa."')";

        $query = $db->prepare($sql);

        $query ->execute();

        echo json_encode(array('message'=> ' Os dados foram inseridos com sucesso. Obrigado e bem vindo!' ));
    }else{
        echo json_decode(array('message'=> ' Não foi possivel iserir os dados! Tente novamente mais tarde!' ));
    };

?>

A estrutura da tabela:
Comment: Onde está o código em PHP?
Comment: Achei que tinha postado, está ai... Obrigado.
Comment: Aproveitei e coloquei a estrutura da tabela.
Comment: O `undefined` me parece ser exatamente porque o objeto enviado é vazio (ou o atributo  `.data`). Além disso, parece que você guarda a senha direto no banco sem criptografia (sugiro um MD5()) ali no `INSERT`.
Comment: Oi @leonardopessoa sim, o data está vazio, mas lanço os objetos todos completos. Não estou sabendo resolver.
Comment: Então ele não dá erro? Só aparece como executado mas o valor não é inserido no banco. É isso?
Comment: Isso mesmo. @leonardopessoa
Comment: Alguma das resposta lhe foi útil? Não esqueça de escolher uma e marcar o ✅ para que possa ser utilizada caso alguém tenha uma dúvida similar!
Answer: Você tem que criar não só o model vovo, mas todos os seus elementos e quando enviar na requisição, + ou - assim:
$scope.vovo = {
  'nome' : '',
  etc etc...
}
Além disso é para usar Data.setData($scope.vovo), isso deve resolver...
Comment: Voltei só pra agradecer. Muito obrigado pela ajuda! :)))


Custom control for flickr is not works on the production server but it works on the development server

Question: We developed a site named donmueang.com; this site contains two custom controls named Youtube control and flickr control. Our problem is this two custom controls runs well on the development server but only flickr control does not work on the production server.
What would be the actual problem?
Comment: *Not working* is a phrase commonly employed by people who don't know or don't care about how a computer works. This phrase is totally inappropriate for a software developer. You will need to provide much more details about those controls, how are they implemented, show some source code, explain what is the expected result and how the actual result on the production server differs from this expected result.
Answer: I figured it out. It has to do with where the Flickr API tries to store it's cache. By default it tries to create a directory and store a file in the currently logged in user's ApplicationData folder. Since most production servers will not grant access from your application to this folder, the Flickr API will not load correctly.
The fix for me, since I'm using the ASP.NET Flickr API, was to add an entry to the web.config file:
<flickrNet cacheLocation="E:\inetpub\[MyWebAppDirectory]\flickr_cache\"></flickrNet>
Hope this helps.


Creating a table in PHP within current function

Question: I am really struggling with some PHP. I have Googled and asked everyone I know before troubling you fine people!
I have cribbed together the below to display the latest 20 files as links from a folder.
The only problem I have is the output is a single string. I really want to put it in a table.
Each time I try it just dumps everything in each field, so I guess there is some clever looping that I need!
Any ideas? Here is my code:
<?php
$dir = "./PDF";
chdir($dir );
$show = 20;

$files = glob( '*.{pdf}', GLOB_BRACE );
usort( $files, create_function('$b, $a', 'return filemtime( $a ) - filemtime( $b );') );

for ( $i = 0; $i < $show; ++$i )
echo '', $file, ' - ', date( 'D, M d, Y', filemtime($file) ), ' - ',filesize($file),'kb;

', "\n";
?>

Answer: Is this what you are looking for?
<?php
$dir = "./PDF";
chdir($dir );
$show = 20;

$files = glob( '*.{pdf}', GLOB_BRACE );
usort( $files, create_function('$b, $a', 'return filemtime( $a ) - filemtime( $b );') );

echo '
';
for ( $i = 0; $i < $show; ++$i ) {
    $file = $files[$i];
    echo '
';
    echo ''. $file .'	';
    echo ''.date( 'D, M d, Y', filemtime($file) ). '	';
    echo ''. filesize($file) .'kb	';
    echo '
';
}
echo '
';

Comment: YES!!! This is exactly what i needed to happen. I tried so many times and just got a blank page. I must have missed something in my set up. I spent the entire weekend trying to do this! Thank you so much
Answer: foreach might make this easier for you,
But it looks like your problem is:
1). Use . not , to concatenate.
2). put "\n" at the end for "new line"
foreach($files as $file){

    echo '
'.$file.'	'., date( 'D, M d, Y', filemtime($file) ).'	 '."\n";//double quotes around "\n"
 // for your 20 limit, you could:
i++; if(i>=20){break;}

//  but you could just stick with the for loop, and take the assignments out.
      }
Comment: Thank you so much for your response. I really appreciate it.


Form altered select field is submitting the wrong values

Question: I created a content type in a module called travel_page.
In Drupal, I added a new empty List(text) field called English_side_menu
Now I want to populate the List text dynamically.
I did:
<code>/**
 * Implements hook_form_alter().
 */
function travel_page_form_alter(&$form, $form_state, $form_id) {

  // $english_side_menu_list has been initialed here

  $form['field_english_side_menu']['und']['#options'] = $english_side_menu_list;
  dpm( $form['field_english_side_menu']);

}
</code>
Every thing is working fine, except the value that appears for the select once I submit the button, is the rank of the selection instead of the text selected.
Do you have an idea what is wrong in the code?
Thanks.
Comment: That's how HTML forms works - index of the selected option is submitted, not it's descriptive text. Exactly what you got. And it appears that it's not your code that processes it further, so what really bothers you?
Answer: For dynamic list text no need of form alter for a content type.
You can achieve this goal using Content Construction Kit (CCK) module.
Install this module and configure field as below image

and define function statement like
<code>function _options_english_side_menu(){
    $english_side_menu_list = array('1' => 'value1', '2' => 'value2');
    return $english_side_menu_list;
}
</code>
Using this function you can assign dynamic list to list text.
Answer: The code should be similar to the following :
<code> function hook_form_alter(&$form, &$form_state, $form_id) {

    if ($form_id == 'ENTER_YOUR_FORM_ID') {

    $english_side_menu_list = array('1' => 'value1', '2' => 'value2');
    //enter the values for the list above similarly
       $form['field_english_side_menu']['und']['#options'][] = $english_side_menu_list;

    }

 }
</code>
Comment: I did. It does the same thing. I got English_side_menu:1 when I select value1. I presume I did something wrong when I created the field English_side_menu, but can't show because it is not code. :-(
Comment: can u give me something like screenshot or code?
Comment: The code, I don't have except the code below. what I did : Add new field, English_side_menu, List(text), Select list, Save, Save field settings, Save settings. I add content, select value1 from English_side_menu, save,  what I get is:  Submitted by xxx on Thu, 04/17/2014 - 14:50
english_side_menu:
1
Comment: I found a way :

$english_side_menu_list = array('value1' => 'value1', 'value2' => 'value2');

What do you think?
Answer: That is because of the options you have set using $english_side_menu_list.
The keys of that array are what is submitted when the user selects a value and submits the form.
Either you have to map the selected value back to the human readable value by using the $english_side_menu_list array when you need to (like in the submit handler of the form or elsewhere when displaying that value), or you have to change the $english_side_menu_list array so that the keys are the same as the values (then that is how they will be submitted).


How To Troubleshoot Excess Time From Connect to First Byte?

Question: I measured load times for a wordpress 2.9.2 install on apache 2.2.3 and I was intrigued by the long periods between connect and first byte for the css and image files.
Load Average is 0.0, 0.0, 0.0 and there is 150MB free RAM on the VPS. There are a few other VPSes on this box, with even more free RAM and underutilized CPU, that have the same issue. Sample Pingdom results are at http://imagebin.ca/img/6UaiOU.png
How do I gain insight into the possible causes of this problem and how would I troubleshoot it?
Thanks
Answer: You should diagram, isolate and observe all possible paths for latency.  It appears that all I/O-related requests (files) are taking much longer than the dynamic content.  Use iostat.  Try to compare with other local I/O operations and benchmarking tools (dd, bonnie) and see if it looks like "normal" behavior for this system or something specific to Apache.
Comment: i ran IOstat, on the hardware node (since the problem occurs on all VPSes in this HW node), disk %util over 5 minutes is at most times under 5%, goes to ~20% and once went to 50%, but it is clear the disk subsystem has plenty of capacity. still intrigued.
Comment: I concluded that there is nothing wrong with my server. Other measurement tools show very responsive times: Yslow, site-perf.com and uptrends.com. I'm going to write this off as Pingdom/Octagate simply "don't like" my server or its network.

I COULD create another question to find out why pingdom does this all sites on all VPSes on my server. I might get to that some day.
Comment: If you'd like to test your system with Circonus (http://circonus.com/), I can hook you up with a trial account.  Shoot me a tweet (same contact) if you're interested.
Answer: can it be that somewhere you check rev-dns for the ip connection comes from? make sure neither apache or mysql do no try to do it:

for mysql use skip-name-resolve
for apache HostnameLookups Off

maybe there are some other checks - try running tcpdump on loopback and wan interface while running single http query and see what happens.
Comment: probably not mysql related because images and js do not generate a DB hit, but on the apache side it is set to off.
Comment: Also `skip-name-resolve` is only for remote MySQL connections. Most likely they are using a local MySQL server with a socket connection.


Regex not stopping where I think it should

Question: I can't figure out why this is not stopping where I thought it should.
Here is the example string.

foo bar

bar foo

This grouping repeats itself over and over so I'm using the following.
preg_match('@
.*
@', $page, $matches);

It works but gets every single grouping at once instead of one at a time.  Am I missing something simple here?
Thank you.
Answer: Try:

.*?

.* matches greedily, so it will encapsulate as much as it can within that .* before matching the rest of the regex.  .*? matches reluctantly, so it matches as little as possible before continuing to the rest of the regex.
Comment: Thank you. 1 character, I should have known! Much appreciated.
Answer: Another solution is to use the U (PCRE_UNGREEDY) option, which makes by default all searches ungreedy :
preg_match('@
.*
@U', $page, $matches);


python - derivative of a function provided by user (read from file)

Question: I've been writing a few programs that, given a math expression (provided as a string in a file), would evaluate f(x) for a given x, using py_expression_eval
Example:

input.txt

x^2 + 1

func.py

from py_expression_eval import Parser

parser = Parser()

file = open("input.txt")

func = file.readline().strip()

f_of_5 = parser.parse(func).evaluate({'x': 2})

output

5

Is there any way I can get the derivative of a function provided as a string like that?
Comment: Yes, of course you can, but you'll have to write a derivative algorithm, just like you wrote an evaluate algorithm. This is a pretty good learning exercise if you just want to differentiate polynomials, or if you want to approximate a derivative at a point by numerical means, or something else simple, but you have to pick something specific, read the math on how to do it, and then try to code it.
Comment: Meanwhile, if you want to code up a general-purpose symbolic derivative algorithm, that's probably way too big to do as a learning project (and if you actually need this for some real work, you're better off using sympy or some other existing library than trying to build it yourself).
Comment: Although it _might_ be an interesting project to build a "sympy compiler" that takes your parse tree and builds a sympy expression that you can then do stuff with.
Comment: This is not an exact duplicate since the OP starts with a string. Reopened.
Answer: I've been using sympy for this lately. Here's a small demo:
>>> from sympy import diff, Symbol
>>> from sympy.parsing.sympy_parser import parse_expr
>>>
>>> user_str = 'x**3 + x + 1'
>>> my_symbols = {'x': Symbol('x', real=True)}
>>> my_func = parse_expr(user_str, my_symbols)
>>> my_func
x**3 + x + 1
>>>
>>> diff(my_func, my_symbols['x'])
3*x**2 + 1
>>> diff(my_func, *3*[my_symbols['x']])
6

Of course, nothing stops you from getting user_str from a file.
(You will have to use ** instead of ^ for exponentiation.)
Comment: Thank you! I didn't know about `parse_expr`. Using that + `lambdify()` made my life 10x easier :)


Lagrangian of matrices equation derivation

Question: This is equation (41) from this paper:
A Lagrangian is constructed with a symmetric matrix multiplier $\Lambda$:
$$L(R, \Lambda)=tr(X^*R^T \tilde{X}^{*T}) - \frac{1}{2} tr(\Lambda^T(R^TR - I_k))$$
where $R$ is orthonormal ($R^TR = I_K$); $X^*$ and  $\tilde{X}^{*T} \in R^{N \times K}$ and with entries only one 1 and all remaining zeros in each row (e.g. [1 0 0; 0 0 1; 0 1 0])
It then says the optimum $(R^*, \Lambda^*)$ must satisfy
$$L_R = \tilde{X}^{*T} X^* - R\Lambda = 0$$
However I couldn't get how the second equality is derived from the first Lagrangian formula?
Comment: $R$ isn't orthonormal *a priori*; enforcing this constraint is the whole point of the second term.
Answer: For matrix derivatives I like to work with the differential and variations:
The derivative of $L$ with respect to the variation $\delta R$ in $R$ is
$$dL\delta R = \operatorname{tr}\left(X^* \delta R^T \tilde{X}^{*T}\right) - \frac{1}{2}\operatorname{tr}\left(\Lambda^T (\delta R^T R + R^T \delta R)\right),$$
where we've used the linearity of trace and the product rule.
Now let's use the fact that the trace is invariant under transposing to convert all of the $\delta R^T$ to $\delta R$:
$$dL\delta R = \operatorname{tr}\left(X^* \delta R \tilde{X}^{*T}\right) - \frac{1}{2}\operatorname{tr}\left(R^T \delta R \Lambda\right) - \frac{1}{2}\operatorname{tr}\left(\Lambda^T R^T \delta R\right).$$
I'd like to rearrange all of the trace terms to look like $\operatorname{tr}(M^T \delta R)$ so that I can rewrite them as the Frobenius product $M : \delta R$. I can do this by invoking invariance of trace under cyclic permutations:
\begin{align*}
dL\delta R &= \operatorname{tr}\left(\tilde{X}^{*T}X^* \delta R\right) - \frac{1}{2}\operatorname{tr}\left(\Lambda R^T \delta R\right) - \frac{1}{2}\operatorname{tr}\left(\Lambda^T R^T \delta R\right)\\
&= \left(\tilde{X}^{*T}X^* - \frac{1}{2} R\Lambda^T - \frac{1}{2}R\Lambda \right) : \delta R\\
&= \left(\tilde{X}^{*T}X^* - R\Lambda \right) : \delta R,
\end{align*}
where the last step uses the symmetry of $\Lambda$.


is it a security hole to verify an uploaded supposed-to-be-zip file as a zip with zip_open()?

Question: Question's subject is pretty much it.
I have an upload widget on a custom content type that is for users to provide a zip file.
I want to verify the file they provide is indeed a zip file, and take appropriate action if not. However, first I need to know if it's safe to pass an unknown file type to zip_open(), probably using the ZIP_CHECKONS flag for extra integrity checks.
edit: just realized ZIP_CHECKONS is not exposed in php. :(
Is this a safe way to verify a file is a zip file?
Answer: That seems reasonable to me. I would probably place the file in a temporary directory first and then use zip_open on it in that location.
You may also be able to use OS level commands (which come with their own risks) to verify the integrity of the file without actually unzipping it.
Are you going to store the zip files as zip files after being uploaded? Doing so presents additional issues since zips can be used to contain lots of files that may or may not be appropriate. You may want to get a list of the contents of the file to automatically include in your field so people downloading them will know if the file contents are valid. You could also integrate with something like http://drupal.org/project/clamav to scan all the files that are uploaded.
Comment: Greggles, thanks for the very informative answer. The zip files are intended to be user contributed digital download products at an online store. So there is moderation, as in each zip file is opened, examined & tested by human staff before being added to the online store. Something like clamAV looks quite important to integrate into the workflow, for some measure of internal protection. Thanks again!


How to access non static cloned arrayList for use in static method in Java

Question: As part of an assignment Im trying to access a cloned array list from another class so I can utilize it. But when attempting to do so I get the following error "non-static method getConnections() cannot be refrenced from a static context".
This is the code I'm using to access the cloned array. It is in the context of working out the best way to take flights from one destination to another.
public boolean determineRoute(City from, City to, ArrayList<City> flightRoute)
{
    ArrayList<City> Connections = new ArrayList<City>();
    Connections = City.getConnections();
    return true;
}

And this is how the code for that class begins. It does start as static but as far as i can see it should only affect the first method how can I tell java that this method should not be considered static so I can access the cloned list from the non static class??
import java.util.*;

public class Lab9_Ex2_Main
{
    //////// START-UP /////////
    public static void main(String[] args)
    {
        new Lab9_Ex2_Main();
    }

I have left out a lot of the code as I think it may not be right from me to put every thing up. But should you need more to get a clearer picture I will happily add more of the code.
This is the code from another class which contains a cloned array which im attempting to access.
import java.util.*;

// Class:  City
// Purpose: To represent a place in the world that you can fly from/to.
public class City
{
    private String name;        // The name of the City
    private ArrayList<City> connectsWith;       // Which cities are connected to this one

    public City(String cityName)
    {
        name = cityName;
        connectsWith = new ArrayList<City>();
    }

    // Method: addConnection
    // Purpose: To note that you can catch a flight to the destination, from this city
    // Passed:
    //     destination - The City which you can fly to.
    public  void addConnection(City destination)
    {
        if (destination != null && destination != this)
            connectsWith.add(destination);
    }

    // Method:  getConnections
    // Purpose: To retrieve a list of cities you can reach from this one.
    // Note: You are given a clone, (to avoid a privacy leak), and can manipulate it however
    //    you like. E.g. you could delete elements.
    public ArrayList<City> getConnections()
    {
        return (ArrayList<City>) connectsWith.clone();
    }

    public String getName()
    {
        return name;
    }

    public String toString()
    {
        return name;
    }
}

Comment: If you learned to format your question properly so the *text* didn't come up as *code* you wouldn't need the gibberish in the middle. Please learn how to use the system instead of mocking it...
Comment: Please try and learn how to format your posts without adding "gibberish" text. :) - Edited that for you.
Comment: Sorry for being annoying. How would I format the text so it does not come up as code?
Answer: City actually doesn't provide a static getConnections() method, since that doesn't make sense. The connections depend on an actual City instance and if you have access to one you can call getConnections() on it, even from a static method.
This is the comment on the array list that is cloned in getConnections():

// Which cities are connected to this one

Note that this means you just can't get the connections without specifying this city (the one you get the connections for) and thus just can't call that method on the City class only.
Comment on the method itself:

Purpose: To retrieve a list of cities you can reach from this one.

Assuming your determineRoute(...) method might be static, it could look like this:
public static boolean determineRoute(City from, City to, ArrayList<City> flightRoute)
{
   ArrayList<City> connections = new ArrayList<City>();
   connections = to.getConnections(); //or from.getConnections(); what ever makes sense

   //connections is not used, so I assume you want to put them into flightRoute
   flightRoute.addAll(connections);

   return true;
}

Your determineRoute(...) logic seems quite odd. I assume you want to actually calculate the route between the from and the to city, which you are not doing right now. Fixing that, however, is an exercise for you.
You could then call that method in your main method (which has to be static) like this:
public static void main(String... args) {
  City berlin = new City("Berlin");
  City beijing = new City("Beijing");

  //fill the connections here

  ArrayList<City> route = new ArrayList<City>();

  boolean success = determineRoute(berlin, beijing, route);
}

Comment: Thanks for taking the time to answer. So why do I then get the error message when trying to access the cloned arraylist??
Comment: oops I did not see your entire post yet when I commented just before.
Comment: Yes thanks that makes a lot of sense now that you have explained it.
 Of course I cannot access City as it has not been instantiated!!. aha thanks.
Yes this is an assignment based on recursion where flights only go from one city to another and we need to work out the countries needed to go through to get their.


Sum from infinity to infinity

Question: How does one evaluate the following limits?

$\lim\limits_{n \to \infty} \sum\limits_{k=n}^\infty (1)$

$\lim\limits_{n \to \infty} \sum\limits_{k=n}^\infty k^{-1}$

$\lim\limits_{n \to \infty} \sum\limits_{k=n}^\infty 2^{-k}$

Do all three limits evaluate to $0$? If so, why? Perhaps only the third limit evaluates to $0$, while the first two are undefined. Again, why? @PeterTamaroff pointed out that the first two limits are undefined for fixed $n$, but does that necessarily imply they are undefined in the limit?
Comment: All three terms are already meaningless for any fixed $n$. One can study the limit of a sequence if one really has one.
Comment: @PeterTamaroff True, but does that necessarily imply they are meaningless as $n \rightarrow \infty$? Also, in light of your comment, I've edited the third limit so that it is meaningful for fixed $n$.
Comment: I repeat: if you want to talk about $\lim\limits_{n\to\infty} s_n$, the $s_n$ have to be "something". In this case, at best, we can say $s_n=+\infty$. In the third case, the limit is $0$; since you're subtracting from $1$ the partial sums of $1+2^{-1}+\cdots$ that converge to it.
Comment: @PeterTamaroff Thanks, I understand now :-)
Comment: To whomever downvoted this question to -1: I've found a useful rule on StackExchange websites is to *always* explain a downvote in the comments. Some users may be more active in other communities and may not understand why a question in a particular community is considered a "bad" question.
Answer: Consider the sequence $$\left(\sum_{k=n}^\infty 1\right)_{n \geq 1}.$$ This sequence is $$(\infty,\infty,\infty,\ldots).$$  Hence, if we wish to define a limit of this sequence, it should be $$\lim_{n \rightarrow \infty} \sum_{k=n}^\infty 1=\lim_{n \rightarrow \infty} \infty=\infty.$$
The second example is resolved in the same way (since the series is also divergent).
In the third case, the sequence is $$\left(\sum_{k=n}^\infty \frac{1}{2^k}\right)_{n \geq 1}.$$  Since $$\sum_{k \geq 1} \frac{1}{2^k}=1,$$ the sequence is $$(1,\tfrac{1}{2},\tfrac{1}{4},\ldots)$$ so $$\lim_{n \rightarrow \infty} \sum_{k=n}^\infty \frac{1}{2^k}=0.$$
Answer: As limits are usually defined, you can only take $\lim_{n \to \infty}$ of an actual sequence of real numbers, so the first two limits are in fact meaningless, while the third evaluates to $0$ since $\frac{1}{2^{n-1}} \to 0$.
However, it is possible to discuss convergence in the extended real line $\mathbb{R} \cup \{-\infty,\infty\} = [-\infty, \infty]$.  In this framework, observe that the sequences of partial sums for the first two sums both approach $\infty$, so both sums are equal to $\infty$ for any fixed $n$.  Then the first and second limits are the limit of the sequence $\infty, \infty, \infty, \dots$, which converges to $\infty$.  The third limit is still $0$ as it was before.
Comment: Thanks, this is useful. I've given the answer tick to @Rebecca since you both provided the same answer but she posted first (by a small margin :-). Cheers.
Answer: Although your second sum

2) $\lim_{n \rightarrow \infty} \sum_{k=n}^\infty k^{-1}$

converges to 0, it is intresting that
$\lim_{n \rightarrow \infty} \sum_{k=n}^{2n} k^{-1} = \ln 2$
looking for other cases that base index starts from some infinity?

Sum from infinity to infinity


[Guitar][Newbie][Build Issues] My bridge might be cracking?

Question: I finally got some time to pick up on my guitar skills, but after cleaning it and then proceeding to change the strings,  , and almost like that they could break if the strings were too tight. Are they gonna break and should I get them checked out?
The images: https://i.stack.imgur.com/E8LAs.jpg
Edit: looked like I was only concerned about the bridge pins.
Comment: I would be more concerned about the bridge.  It looks like someone used a screwdriver to get the pins out.  As long as the pins stay in while you are playing, you should be okay.  If you break one or lose one, they are easy to replace.
Answer: Just in time! The pins will split the bridge when all the tension is on. It's already partially happened, sadly.
Some options:
Very carefully with a sharp chisel, work under the bridge until it's off as cleanly as possible, and get a replacement, stuck back on as exactly as you can, using two-part epoxy. Maybe consider a brass compensated saddle at the same time?
Try to open op the split gently, to dribble two-part epoxy in everywhere you can - including the pin holes (re-drill later), and carefully clamp the brige back together, which may not be possible if the lower shoulder of the bridge is too chamfered.
I recently did the first on a 12 string, and it's absolutely fine now. (Original owner used 4 drywall fixings, which strangely didn't do too good a job... Buy a bridge that's at least the same size, slightly longer/wider is better, but will entail more work cutting the lacquer away to give in a tidy, tight fit - and look good again. Good luck!
Comment: Thank you, I will probably try to get it fixed it at a workshop, if there are any nearby.
Can you enlighten me on why this is happening, as I don't actually play my guitar that often, like just a few times every few months or so.
And would you happen to know how much it would cost to get it fixed?
Comment: @Gr8Bedo Yeah, I was gonna say, "Or another option, take it to a good luthier." And I'm sure they'd be able to quote you. There could even be other, related issues they find.
Comment: If you fancy some diy, give it a go. Most repairs are worth doing, but there are plenty of folk who would write off this due to the effort involved. I wouldn't do someone else's repair like this for less than a couple of hrs labour, probably 3 or 4, by the time it's all tidied up. So if the guitar's worth less than, say, $100, its not worth doing - unless there's a lot of sentimental value involved.
Comment: Please let me know what happens in the end. Good luck - but it won't be a cheap repair!
Comment: I do fancy DIY, and honestly I would love to repair it, but knowing myself I might mess it up one way or another. And the guitar is worth around a 100$, but I still think getting it repaired is the way to go as I come from a third-world country, and art like this isn't valued much, infact I got a guitar that had it's neck splitting away from its fretboard (not sure if that is the right way to describe it) fixed for 10$. I would update you on my final decision if you are interested. And once again, thank you for all the help.
Comment: @Tim Thank you for your help, yesterday I gave the guitar for repairing, and they estimate it wouldn't cost more than INR 500, which is a bit less than 7$.
Comment: @Gr8Bedo - that's incredible! Sounds like about 5 minutes work!


Can a domain that has a website build with WordPress, be re-use outside WordPress?

Question: I have a domain, and so far I used WordPress to have a momentary website, now that I want to replace it. Can WordPress be turned off, so I can deploy on the same domain?
Comment: I'm voting to close this question because it's not about programming and isn't on topic as defined here [help/on-topic]
Answer: Yes, it can! But you'll need access to your/a server and to the domain management service where your domain is currently registered.


Integrate $x^2 \sqrt[]{3+5x^2}dx$ (preferably) using substitution

Question: Today we went over solving integrals with tables. My task is to integrate the following:
$\int x^2 \sqrt[]{3+5x^2}dx$
In the back of the book, I am provided with over $100$ integrals.  I believe this is in the form of:
$\int u \sqrt[]{a + bu} ~du = \frac{2}{15b^2}\left(3bu - 2a\right)\left(a + bu\right)^{\frac{3}{2}} + C$
So, $a = 3$ and $b = 5$.
Now, if I let $u = x$, then $du = dx$, but that does not sound right because then $a + bu$ would be $3 + 5x$.
But if I let $u = x^2$, then $du = 2xdx \rightarrow \frac{1}{2}du = xdx$.  That does not sound right because there is no $x$.
Answer: Hint
Making the problem more general
$$I=\int x^2 \sqrt{a+b x^2}\,dx$$ where $a$ and $b$ are positive, write $$b x^2=a \sinh^2(t)\implies x=\sqrt{\frac ab} \sinh(t)\implies dx=\sqrt{\frac ab} \cosh(t)\,dt$$ Replace and use some basic properties of the hyperbolic functions.
Answer: The hint:
Let $x=\frac{1}{2}\sqrt{\frac{3}{5}}(e^t-e^{-t}).$
Thus, $$t=\ln\left(\sqrt{\frac{5}{3}}x+\sqrt{\frac{5x^2}{3}+1}\right),$$ $$dx=\frac{1}{2}\sqrt{\frac{3}{5}}(e^t+e^{-t})dt$$ and
$$\int x^2\sqrt{3+5x^2}dx=\frac{9}{80\sqrt5}\int\left(e^{2t}-e^{-2t}\right)^2dt.$$
Can you end it now?


C# code to fill color in a table cell in a word document

Question: I have created a word document which contains a table, using C#.
Now I want to fill one of the cells in this table with red color.
While searching on the net, I found that I could use the shading object to do this. But I dint get any details on how I could use this.
I tried using something like:
<code>doc.Tables[whichTable].Cell(1,4).Range.Shading.BackgroundPatternColor
</code>
But how can I set a color using this???
Answer: If you look at this reference page you will see the WdColor constants listed. These are colours available to word, to see more about them there is an enumeration listing here.
Your code to select the table cell looks correct to me, so you just need to set the BackgroundPatternColor to one of the WdColors.


Show that $(0,1)$ and set of positive real numbers are equivalent sets

Question: I try to prove that the open interval $(0,1)$  and $\mathbb{R}_+$ are equivalent sets.
I thought maybe if I define a bijective function between those two sets; it would help, but I couldn't. Can you help with it?
Comment: Which functions did you try?  There is an obvious example which almost works and needs a slight adjustment to actually work
Comment: Please do not roll back improvements.
Comment: You can find some bijections here: [Monotonic bijection from positive reals to reals between 0 and 1](https://math.stackexchange.com/questions/1631521/monotonic-bijection-from-positive-reals-to-reals-between-0-and-1).
Answer: Try with
$$f(x):(0,\infty)\to (0,1)\;,\;\;f(x)=\frac{2x}{x^2+1}\;\ldots$$
Comment: Firstly thank you for your answer.I may have misrepresented it. Find a bijective function between this sets to prove they are equal is just a way that i thought. Actually I need to prove that they are equal step by step.
Comment: Well, there you have it! Prove the above function is bijective and thus invertible, and thus both sets are equipotent...because when you write "equal" I guess you actually mean "equipotent = have the same cardinal".
Answer: Try  $f:(0,1)\to(0,\infty)$ by $f(t)=\tan(π/2t)$.
Answer: The map $f:(0,1)\rightarrow (0,\infty)$ defined by $f(x)=x/(1-x) $  proves the equivalence.
$f$ is 1-1: Easy to check.
$f$ is onto:  For every $y\in (0,\infty)$ there exists $x=y/(1+y) $ such that $f(x)=y.$
f is continuous and $f^{-1}:y\rightarrow y/(1+y)$ is also continuous.
Hence proved! Complete the 1-1 part!
Comment: Firstly thank you for your answer.I may have misrepresented it. Find a bijective function between this sets to prove they are equal is just a way that i thought. Actually I need to prove that they are equal step by step.
Comment: I don't know what you mean by step by step.  This answer seems fine.


Is an absent batsman out?

Question: One of the opposition batsmen failed to turn up. Is he out?
This matters especially for my competition where teams receive 0.25 points for each wicket taken.
Comment: While Nij's answer is almost certainly correct in terms of the laws of the game, you really need to be asking this question to your league organisers. It doesn't really matter if somebody on the Internet says you're right if the organisers say "no".
Answer: Law 1.2 requires that the players of each team be provided in writing to the umpires before the toss, and thereafter not changed without the agreement of the opposing captain.
Law 40 requires that the next batsman be ready on the field within three (3) minutes of a dismissal, unless Time is called. If the three minutes elapse without the batsman being ready, they are liable to be out, Timed out on appeal by the fielding team.

Is an absent batsman out?


Upgrading to Angular 9 using Ivy, cannot combine @Input decorators with query decorators (@ContentChild)

Question: Upgrading to Angular 9 I got the followings errors related to a package:
Compiling @ngx-package : es2015 as esm2015

ERROR in Failed to compile entry-point @ngx-package (es2015 as esm2015) due to compilation errors:
node_modules/@firstname.lastname@example.com:1325:34 - error NG1006: Cannot combine @Input decorators with query decorators

1325     'actions': [{ type: Input }, { type: ContentChild, args: [Component,] },],

The responsible code of this error is the following:
@Input() @ContentChild(Component) actions: Component;

Comment: Searching for that error message brings up other questions asking the same thing. Not sure why this required a self-answered question? https://stackoverflow.com/questions/56457566/cannot-combine-input-decorators-with-query-decorators-using-ivy
Comment: you're right, I didn't see that question, I am answering there.
Comment: It's already answered?
Comment: partially, I think that my answer will give a concrete example of the solution of this case, doesn't it?
Comment: It's a concrete workaround, but it might be something you should be avoiding for a good reason. What's your use case for the original code?
Comment: what do you mean? my use case is what I showed in this question & answer.
I was upgrading to Angular 9 and a code had @input() and @ContentChild combined which is not allowed for Angular 9
Comment: Use case != your current implementation.
Answer: The problem is that I can't combine @Input() and @ContentChild, so I replaced the code responsible of the error with the following:
get actions(): Component {
  return this._actions;
}

private _actions: Component;

@Input()
set actions(value: Component) {
  this._actions = value;
}

@ContentChildren(Component)
set viewActions(value: Component) {
  if (!this._actions && value) {
    this._actions = value;
  }
}


What does it mean to introduce local coordinates near a point $p$?

Question: Let $p$ be a periodic point of period $m$ for a $C^1$ map $f$. Suppose that the differential $Df^m_p$ does not have 1 as an eigenvalue. Can someone explain me what does it mean the folowing facts:

Let us introduce local coordinates near $p$ with $p$ as the origin. In this coordinates $Df^m_0$ becomes a matrix.

What does it mean to introduce local coordinates near $p$? Why $Df^m_0$ becomes a matrix?
P.S I'm a beginner in this area, so please be patient with me :D Thank you!
Comment: By definition, a manifold is covered by local charts. So you have an open set $U$ containing $p$, with a homeomorphism $f:U\to V$, where $V$ is an open set in a Euclidean space. Fix such an $f$. Then any $x\in U$ can be specified by giving the (ordinary, Euclidean-space) coordinates of $f(x)$. These coordinates are called local coordinates near $p$. Since you also want $p$ to be the origin, you should arrange that $f(p)=0$, by composing your original $f$ with a Euclidean translation.
Answer: On some kind of spaces (topological manifolds, differentiable manifolds,...) we assume that around each point $p$ there is an open neighbourhood $U(p)$ which is homeomorphic (or diffeomorphic) to an open neighbourhood $V(p)$ of $\mathbb{R}^n$ (or $\mathbb{C}^n$, etc.). We thus say that our space is locally homeomorphic (diffeomorphic) to $\mathbb{R}^n$ (or $\mathbb{C}^n$, etc.). On $\mathbb{R}^n$ you can choose different types of coordinates (Cartesian, polar, cylindrical, spherical, etc.), which means that if you have a point in $\mathbb{R}^n$ you can attach $n$ numbers $x^1,\dots,x^n$ to identify it in the space (that is why you say that a point in the plane has Cartesian coordinates $(0,1)$ or whatever). Now if you call $\phi \colon U(p) \rightarrow V(p)$ the homeomorphism (diffeomorphism) above, then
$$(x^1 \circ \phi)(p), (x^2 \circ \phi)(p), \dots, (x^n \circ \phi)(p)$$
are the coordinates of $p$. You can of course do the same for any point of $U(p)$ getting coordinates of points in $U(p)$, i.e. around $p$. $(x^i_{|p})_{i=1,\dots,n}$ is then called a local coordinate system.


Show that $e^x$ and $e^{-x}$ are linearly independent in C$(-\infty,\infty).$

Question: Show that $e^x$ and $e^{-x}$ are linearly independent in C$(-\infty,\infty).$
In order to solve this one must use the Wronskian of $f_1,f_2..f_n$

Using this we show
$$W[e^x,e^{-x}] = \begin{vmatrix}e^x & e^{-x} \\e^x& -e^{-x} \end{vmatrix} = -2$$
Can anyone explain why this matrix is equal to $-2$?
Comment: That just follows from how to compute determinants. In your case, $W[e^x,e^{-x}]=e^{x}\cdot -e^{-x}-e^{x}\cdot e^{-x}=-1-1=-2$. Since $W[e^{x},e^{-x}]\neq 0$, this gives you the linear independence of the two functions that you seek.
Comment: The determinant  $\left|\begin{array}{rr}a&b\\c&d\end{array}\right|=ad-bc$
Answer: First of all it is not the matrix equal -2, but its determinant.
$$\begin{vmatrix}e^x & e^{-x} \\e^x& -e^{-x} \end{vmatrix} = e^x(-e^{-x}) - e^{-x}e^x = -e^{x-x}-e^{x-x} = -e^0-e^0 = -1-1=-2$$
Answer: The elementary solution is also possible in this simple case of two exponential functions. If $e^x$ and $e^{-x}$ were linearly dependent, then they were proportional: $$e^x=\alpha e^{-x}$$ for some $\alpha\ne 0$ and for all $x\in\Bbb R$. For $x=0$ we get $\alpha=1$ and $e^x=e^{-x}$ for all $x$, which is the nonsense.
This argument works also for $e^{ax}$ and $e^{bx}$ with $a\ne b$.


Normal Distribution for Pearson Correlation

Question: I have read that the variables must be approximately normally distributed to apply Pearson correlation;
However, I came across this answer
here that they dont need to be, so I am confused about that. Can i have a clarification about that ?
Answer: As Rob's answer in the post you link to would suggest, you certainly don't need it to calculate a Pearson correlation.
The need for normality would notionally apply if you used a test or interval that assumed normality in its calculations.
However, you can construct tests and intervals that avoid that assumption, if it's important to. For example, one could easily conduct a permutation test (a nonparametric test) of a Pearson correlation.
You should probably approach some of the advice you're getting at that site with some caution (e.g. see Harvey's answer at Is normality testing 'essentially useless'?)
Comment: You *can* (you type the commands to calculate a Pearson correlation, *et voilà*, you will have a Pearson correlation). The issue is whether it tells you what you want to know. The Pearson won't capture how strongly related they are in whatever form the relationship is, it will capture the portion of the relationship that's linear (i.e. it will be high if the relationship is nearly linear and less high if it's strongly monotonic but nonlinear, and it may be near zero if it's a non-monotonic relationship). So the question is *what are you trying to achieve*? (We have questions relating to this)
Comment: my data isn't either normal or follow a linear relashionship, so can i apply pearson in that case?
Comment: If you want to capture the strength of a monotonic relationship, you might use Kendall's tau or Spearman's rho (among numerous other possibilities). See, for example, the answers by mbq and Gravitas at https://stats.stackexchange.com/questions/8071/how-to-choose-between-pearson-and-spearman-correlation for some relevant issues. If  you want to measure how strong a relationship is in some non-monotonic sense, you need some more general measure of relationship/association. What may be suitable will depend on what kind of data you have and what you want to do with the measure (among other things)
Comment: This is a much more involved question than the original thing you posted.
Comment: now its clear to me. Can you provide me an example of a general measure of relationship/association to measure non monotonic/linear relation?
Comment: See the section on *Other measures of dependence among random vairiables* in the wikipedia page on [Correlation and dependence](https://en.wikipedia.org/wiki/Correlation_and_dependence#Other_measures_of_dependence_among_random_variables) for example.


what "average" to use that will give the most relevant value f0r portfolio

Question: My assignment requires me to find return on capital, industry wise for the loan portfolio classified into various industry/sector, the data fields are : ...
Name of account|industry|Outstanding Amount|Return on capital|....
for example:             XYZ Ltd.|Automobile|30 million|34%
                         PQR Ltd.|Infrastructure|100 milllion|18%
                         DCR Ltd| Retail| 8 million|-128%
I have data of 3500 accounts classified into 28 industries, now the problem I am facing is I am confused as to what kind of mean or average function to use that will give me the most relevant result for the particular sector. Say in Retail sector there are 70 accounts and majority of them have returns ranging from 20% to 48% but for the few defaulted accounts in this sector returns range from -50% to -500% so how do I tell what is the average return that a particuar account from  this sector will give. I am not totally convinced on using Simple average for particular sector because few outliers make the average value too different from observed or logical results, I am not using geometric mean because the returns for each account are independent of each other for one year period and are not multiplicative in any way, and, finally for the defaulted accounts returns are negative so I am not able to use harmonic mean.
Please help and guide me as to How and what average value should I take that would best represent return on capital from an account for a particular sector.
Thanks in advance
Answer: If you want to avoid the effect of outliers, you can try with the median, that is, the value that leaves 50% of your observations below it and 50% of observations above it


web3 get name from address

Question: import Web3 from "web3";

useEffect(() => {
const web3 = new Web3(window.ethereum);

web3.eth.ens.getAddress("ethereum.eth").then(function (address) {
    console.log(address);
});
}, []);

here using this code I am getting address from ether name
is there any way I can get name from address
web3.eth.ens.getOwner("0xc74E8eFaFE54481bD109f97422AeBca607499f57").then(function (address) {
    console.log(address);
});

I am trying above piece of code but it is not working
if I input 0xc74E8eFaFE54481bD109f97422AeBca607499f57
I should get ethereum.eth
Answer: As you can see from the ENS documentation, web3.js can't perform "reversed resolution", i.e. getting a ENS name from an address. However, you can do this from the ensjs API like this:
const address = '0xc74E8eFaFE54481bD109f97422AeBca607499f57';
var name = await ens.getName(address)
// Check to be sure the reverse record is correct.
if(address != await ens.name(name).getAddress()) {
  name = null;
}

web3 get name from address


Find tangential plane of a surface given as an equation on a given point

Question: I have a surface given by the equation $f(x,y,z)=0$ and need to find the Tangential plane on a given point $p$.
Answer: $$ \frac{\partial f}{\partial x} (x - p_x) +  \frac{\partial f}{\partial y} (y - p_y) +  \frac{\partial f}{\partial z} (z - p_z) = 0 $$
is the equation of the tangent plane to the surface defined by $f(x,y,z)=0$ at the point $p = (p_x, p_y, p_z)$.  The partial derivatives are evaluated at $p$.