Backbone.js - views within views and re-renders

Question: I have a collection of items and I am building a simple interface that lists the items on the left, then shows the detail of the currently selected item on the right.
I am trying to render a ItemView for each item within a ItemsListView. I need to bind to the model's change event so that the ItemView is updated along with the ItemDetailView.
In my implementation below, when updating the model that is showing in the ItemDetailView, setting a new property on the model updates the ItemDetailView but not it's representation in the ItemView. I know that I am doing something silly. How can I re-implement this so that both are re-rendered?
P.S. I am trying to avoid re-rendering the List view every time. I'd like to re-render each ItemView in the list separately.
var Item = Backbone.Model.extend({

});

var Items = Backbone.Collection.extend({

  model: Item

});

var ItemView  = Backbone.View.extend({

  template: window.JST['item/list'],

  initialize: function() {
    _.bindAll(this, 'render');
    this.model.bind('change', this.render);
  },

  render: function() {
    $(this.el).html(this.template(this.model.toJSON()));
    return this;
  }

});

var ItemDetailView = Backbone.View.extend({

  el: $('.detail .grid'),

  template: window.JST['item/detail'],

  initialize: function() {
    _.bindAll(this, 'render');
    this.model.bind('change', this.render);
    this.render();
  },

  render: function() {
    $(this.el).html('').fadeOut('fast', function() {
      $(this.el).html(this.template(this.model.toJSON())).fadeIn();
    }.bind(this));
    return this;
  }

});

// for the Items collection
var ItemsView = Backbone.View.extend({

  el: $('.items ol.grid'),

  initialize: function() {
    _.bindAll(this, 'render');
  },

  render: function() {

    // need to put this as the first item in the list
    $(this.el).html('

');

    // iterate over the collection and render each ItemView separately
    this.collection.each(function(l) {
      var lv = new ListView({ model: l, collection: this.collection });
      var html = lv.template(lv.model.toJSON());
      $(this.el).append(html);
    }.bind(this));
  }

});

Answer: I think the problem (maybe not the only one?) is that you haven't set the el property on ItemView, so it doesn't know how to render itself.  I'm not sure what the best way to fix this is.  Maybe add the client ID to the template using <li id='<#= cid #>' ..., and then in the initialize function of ItemView, set el using this.el = "#" + this.model.cid; or something similar.
Comment: Yeah, I figured that was the issue but wasn't sure how to have the el be dynamic. I will try your idea out and see where it gets me.


Show a bound on the error

Question: Suppose $g \in C[a,b]$, and $M(b-a) < 1$, and let $y$, $y_N$ $\in C[a,b]$ be the unique solutions of the equations,
$y = g + Ky$  and $y_N = g + K_N y_N$.
$y_N$ has been previously defined as an approximation to $y$. $K$ and $K_N$ are linear operators.
We are asked to show that,
$$|| y - y_N||_\infty \leq \dfrac{M_N \|g\|_\infty}{(1 - M(b-a))^2}$$
where
$M =\max | k(x,t)|$  ( $k$ is the kernel applied by the operator $K$) and
$M_N = \max | k(x,t) - k_N(x,t)|$ ( $k_N$ is the kernel applied by $K_N$).
Some previous results we have to use are,
$\|K\|, \|K_N\|$ are both $\leq M(b-a)$.
$\|K - K_N\| \leq M_N (b-a)$.
Also, I believe
$\|Ky\| \leq M\|y\|$.
Any help would be much appreciated! I'm failing to even work the inequality backwards at the moment! I believe the first step should be to write $\|y - y_N\|$ as,
$\| K(y - y_N)  + (K - K_N) y_N \|$, but beyond that I'm stumped!
$K$ is defined as, $K\phi = \int_a^b k(x,t) \phi(t) dt$
$K_N$ is defined as, $K_N \phi = \int_a^b k_N(x,t) \phi(t) dt$  where,
$k_N(x,t)$ is an approximation to $k$ by picking a step size $h$ to cut up $[a,b] $into $a=t_0 < t_1 < ... <t_N = b$. and evaluating $t$ at the midpoint of the interval it's in. Although I don't think the definition of $k_N$ will be needed in showing the desired result.
$k \in $ $(C[a,b])^2$.
Comment: what does it mean $\|g\|_{\inf}$ for example ?
Comment: Do you mean the uniform norm/ supremum norm $\|g\|_{\infty}$ ?
Comment: Yes I do! Thank you!
Comment: I think you should better include the definition of the operator $K$ and say where $k(x,t)$ is defined.
Comment: Sure, I'll include that now.
Answer: $$\|y-y_n\|_\infty=\| K(y - y_N)  + (K - K_N) y_N \|\leq \|K\|\|y-y_n\|_\infty+\|K-K_N\|\|y_N\|$$
$$\Leftrightarrow (1-\|K\|)\|y-y_N\|_\infty\leq \|K-K_N\|\|y_N\|$$
$$\|y-y_N\|_\infty\leq \frac{\|K-K_N\|\|y_N\|_\infty}{1-\|K\|}\quad\quad (*)$$
For $\|y_N\|$ you have:
$$y_N=g+K_Ny_N\Rightarrow \|y_N\|_\infty\leq \|g\|_\infty+\|K_N\|\|y_N\|_\infty\Rightarrow \|y_N\|_\infty\leq \frac{\|g\|_\infty}{1-\|K_N\|}$$
Plug this in $(*)$:
$$\|y-y_N\|_\infty\leq \frac{\|K-K_N\|\|y_N\|_\infty}{1-\|K\|}\leq \frac{\|K-K_N\|\|g\|_\infty}{(1-\|K\|)(1-\|K_N\|)}\leq \frac{M_N(b-a)\|g\|_\infty}{(1-M(b-a))^2}$$
Comment: That makes perfect sense, thank you so much for your help! This was driving me mad!
Comment: You are welcome :)
Comment: I've just noticed that your result has an extra (b-a) on top of the inequality though, can that be factored out?

Surely if $a$ and $b$ were such that b-a > 1  the result I was seeking can't be assured?
Comment: If $b-a<1$ it follows. Or you can write further $b-a\leq \frac{1}{M}$ and plug it in the estimate. Are you sure that what you wrote is exactly what you have to prove ?
Comment: That's definitely the result written in this handout however there have been a fair few typo's earlier so I am definitely more inclined to believe that your result was the intended result!

Show a bound on the error


Image from Java GUI to MATLAB

Question: I have a problem with transferring the image (RGB data) I get from Java GUI (for which I have the source code) to a MATLAB array. Can this be done?
I don't know where to start since I'm not very familiar with Java programming. Any help would be appreciated. I'm a Ph.D. student and I need to solve this for my future research.
Comment: MATLAB can read in image files using functions like `imread()`.  What is the format of the image?  Is it on disk?
Comment: I am familiar with imread function and most of the other in image processing toolbox in matlab. However, I don't thing that the image is on disk so I can't use it that way. I can't help you with the format either, since i don't know the answer. The JavaGui is one used  for CmuCam2 image retrieval: http://www.cs.cmu.edu/~cmucam2/downloads.html
Answer: Since you are in Java there are a few things that can happen here.
1) Use the MATLAB Builder JA.  This will allow you to create a Java layer that allows you to marshal data from within Java into the MATLAB runtime.  Note that this option has other requirements that I talk about here
2) You can write out the image in Java into one of the image formats that MATLAB understands and then load it using the aforementioned imread
3) And this is a dubious solution, but will work.  Write out the image as a matrix in CSV format.  You can then load that into MATLAB and it will convert the CSV into a multidimensional matrix which is more or less the representation of the image
Basically it breaks down into writing out the image data in some format that MATLAB understands or write an interop layer.
Comment: Matlab Builder JA is not required in order to access the image data.
Comment: @zellus. Yes, as your solution mentions you could do all this from within the MATLAB environment however then you have to also run the entire CmuCam2 application from within MATLAB, but this is an option that should be considered.
Comment: Thank you all for help.
I thing that first solution can be used, since I have to transfer the data in real time. I can't save the image I get on the disk.
At first, I can start the gui from matlab, but the ideal solution is to control the gui functions without gui opening. Can this be done with builder ja?
Comment: This can technically be done as zellus mentions.  You are able to instantiate Java objects at MATLAB command prompt.  If you know the Java objects that are used to generate the object in question you can script the method calls to the Java objects. See http://www.mathworks.com/help/techdoc/matlab_external/f4863.html.  Build JA can be used to create a distributable solution when you finalize your process.
Comment: Ok, thank you again. I'll let you know what I manage to do in a day or two.
Answer: Well, if you haven't got any better ideas, use a screen grabber (Alt+PrntScreen on Windows, whatever on Linux) and paste the grab into MS Paint or GIMP.  Then save in your favourite image file format and bob's your uncle.
Or, am I as usual, missing some incredible complication ?
If that's too simple, modify the Java to write the image to a file -- you say you have the source.  You could even have Matlab call the Java to do that, then retrieve the image directly.
Answer: One of the outstanding capabilities of MATLAB is its Java scripting capability. As you can download CmuCam2 sources, you just instantiate the Java classes you need and call the required methods as they were MATLAB built-in functions.
Have a look at "Bringing Java Classes and Methods into MATLAB Workspace" of The MathWorks documentation.

Image from Java GUI to MATLAB


Is power always associated with hypothesis testing?

Question: Suppose I know that the true population proportion of a mutation is p = 0.3493119. I want to know that given power = 0.8, what's the proportion of of mutation in my sample of n = 30? Here's what I have so far:
1 - cdf((x-p)/sqrt(p*(1-p)/30) = 0.8
Since p = 0.3493119, I can solve for x and I get x = 0.276055. So does this mean that the probability of having 27.6% of the sample be mutated = 0.8? Is it correct to say that?
From my experience I know that power is the probability of correctly rejecting the null. But since I already know the true population proportion of the mutation, is it still necessary to conduct a hypothesis test? I am leaning towards the negative, but without a hypothesis test, how can I calculate the power?
If I had to perform a hypothesis test to get the power...would it be something like this:
H0: p = 0.5 vs. H1: p > 0.5
power = P(Z_statistic > critical_value | p > 0.5)
power = 1 - normal_CDF(critical_value | p > 0.5)
Now I'm confused by how to deal with the p > 0.5, if it were just p = 0.5, I could've standardized the critical value so that it follows a N(0, 1) distribution.
Overall I think I just want to know the answer to the question, given power = 0.8, what is the proportion of mutation in my sample of n = 30? (true population proportion = 0.3493119).
Comment: To calcuate a specific power, you also need a specific effect size and type I error level, if you do not have a specific effect size, you can draw a power curve, think.
Comment: I think your hypothese should be Ho: p=0.3493139 and H1:p>0.3493139, Something like that. Since you already stated that the true population proportion is 0.3493119, test p=0.5 vs. p>0.5 seems very strange to me.
Comment: @DeepNorth Ok. So power = P(Z > critical value | p > 0.3493139) correct? How do I proceed to find the power? How do I standardize the critical value? Let critical value = c. Would I just do (c - p)/sqrt(p * (1-p) / 30) to standardize the critical value?
Answer: I would say "Yes"power is alway associated with hypothesis testing it relates to  sample size, type I error and both H1 and H0.
The followings are R code to show the power curve for OP's cases (one tailed at 0.05 level, by approximate a normal distribution.
mu<-30*0.35
sd<-sqrt(30*0.35*(1-0.35))
c<-qnorm(0.95,mu,sd)
mus<-seq(10,30,1)
power = 1-pnorm(c, mus, sd)
plot(mus, power, type="l")

Two tailed case by approximating normal distribution
mu<-30*0.35
sd<-sqrt(30*0.35*(1-0.35))
mu
sd
c1<-qnorm(0.025,mu,sd)
c2<-qnorm(0.975,mu,sd)
mus<-seq(0,30,1)
power2 <- pnorm(c1,mus,sd)+1-pnorm(c2,mus,sd)
plot(mus, power2, type="l")

Comment: I also included a two tailed power curve.
Comment: So to attain a power of 0.8, I need p = 0.2? What does p represent? Effect size?
Comment: Ok, I will modify I answer, it is not clear by using p.
Comment: Now, supose your mutation rate is p=0.6 which is 18 muations then your power is about 80% to reject H0:p=0.35.
Comment: Thank you. What if I wanted to do a 2 tailed test? So H1: p =/= 0.35. How would I plot the the power function then?
Answer: This is for binomail distribution not by approximation.
#under binomail distribution, one tail,
qbinom(0.05,30,0.35) #critical rigion
n<-seq(6,30,1) #numbers bigger than critical region
pow<-pbinom(n,30,0.35)#one tailed test
plot(n, pow, type="l")

Answer: Your question is not a question about power.  Assuming a given population mean, you are interested in predicting the sample mean. If you have a binomial distribution, you can find the density distribution centered over your population mean.
Power would require specification of a criterion value for deviations of sample means from the population mean.


How do I add a class to a row based on the value of a field in that row?

Question: I have a view with a page display showing a list of events. I'd like to add a class to the rows of those events that are in the past.
The problem I have is that views-view-list.tpl.php doesn't have access to the values of fields within the rows.
And I can use views-view-fields.tpl.php to check the date field of one row, and wrap each field in that row with a div or span based on whether or not the date field is in the past.
I just can't figure out how to use the value of a field within a row to wrap the whole row in something with a class.
Answer: The following will add the class 'hello' to the li tag. I used a view with machine name 'dates' and a display name of 'page'. The time field is the node created time. You can just install Devel and uncomment the dpm($vars) statement to get what you need. I also left the conditional logic up to you.
Put this in your theme's template.php file:
function MYTHEME_preprocess_views_view_list(&$vars) {
  if ($vars['view']->name == 'dates' && $vars['view']->current_display == "page") {
    // dpm($vars); //uncomment to see variables
    foreach($vars['view']->result as $key => $value){
      $timestamp = $value->node_created;
      if ($timestamp) { // add whatever conditional logic you need here
        $vars['classes_array'][$key] .= ' hello'; // note the space in front of class
      }
    }
  }
}

An alternative method is as follows:
Put this in your theme's template.php file:
function MYTHEME_preprocess_views_view_fields(&$vars) {
  if ($vars['view']->name == 'dates' && $vars['view']->current_display == "page") {
    $timestamp = $vars['row']->node_created;
    if ($timestamp < strtotime('now')) {
      $vars['classes_array'][] = 'bye';
    }
  }
}

and use this views-view-fields--VIEWNAME.tpl.php file:
<div class="<?php print $classes;?>">
<?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>

  <?php print $field->wrapper_prefix; ?>
  <?php print $field->label_html; ?>
  <?php print $field->content; ?>
  <?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>

Comment: OMG OMG OMG THIS TOTALLY WORKED (I used the first chunk of code in my template.php). Thank you SO. MUCH.
Comment: Is there a way to do this by only using the template file?
Comment: You will have to move the logic that is in the preprocess function into the beginning of the template, and add the class to the $classes variable (not the classes_array variable). The variables that in the preprocess function is accessed under $vars will have been flattened so that in the template file you can access them directly, ie $vars['view'] will become $view.
Comment: couldn't user $vars['classes_array'][$key] for table style because of Notice: Undefined offset: 2 error where 2 is the found key. Is this only works for non-table styles


Exception occured on query when i Edit or Delete row from wpf datagrid using LINQ to SQL

Question: I am new to WPF and C#.
I am trying CRUD operations on WPF Datagrid. My datagrid shown records from two table that are linked with foreign key reference.
But the problem occurs when I edit a cell data and click on submit button the following message is displayed by exception.

ERROR:"Excetpion has thrown by the target on invocation" and it point
  me on linq to sql query that i have written in edit code.

Same problem occurs when I perform Delete operation.
<code>    private void LoadDataGrid()
    {

        DataClassesDataContext dataContext = new DataClassesDataContext();

        var results = from b in dataContext.iBankNames
                      join acc in dataContext.iBankAccountNos on b.BankID equals acc.BankId
                      orderby b.Name ascending
                      select new
                      {
                          BankID = b.BankID,
                          BankName = b.Name,
                          BankAccNo = acc.BankAccNo,
                          BranchName = acc.Branch
                      };

        MyDataGrid.ItemsSource = results;

    }
</code>
and here is my XML Code of wpf.
<code>   <DataGrid x:Name="MyDataGrid" x:Uid="MyDataGrid" AutoGenerateColumns="False"
                   SelectionMode="Single"
                AlternationCount="2"

              >
        <DataGrid.Columns>
            <DataGridTemplateColumn Header="Bank ID" Width="SizeToHeader">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBox IsReadOnly="True" Text="{Binding BankID,Mode=OneWay}"
                                />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

           <!----HERE ARE SOME MORE COLOUMNS----->

            <DataGridTemplateColumn Header="Edit Row">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Content="Edit" Click="EditButton_Click" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn Header="Delete Row">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Content="Delete" Click="DeleteButton_Click" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
</code>
Here is Edit code:
<code>         private void EditButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {

            DataClassesDataContext dataContextEdit = new DataClassesDataContext();
            iBankName bankRow = MyDataGrid.SelectedItem as iBankName;
            //string m = customerRow.CustomerID;
            iBankName bank = (from p in dataContextEdit.iBankNames
                                 where p.BankID == bankRow.BankID
                                 select p).Single();

            bank.Name = bankRow.Name;

            iBankAccountNo banAccRow = MyDataGrid.SelectedItem as iBankAccountNo;

            iBankAccountNo bankAccNo = (from p in dataContextEdit.iBankAccountNos
                                            where p.BankAccNo == banAccRow.BankAccNo
                                            select p).Single();

            bankAccNo.BankAccNo = banAccRow.BankAccNo;
            bankAccNo.Branch = banAccRow.Branch;

            dataContextEdit.SubmitChanges();

            MessageBox.Show("Row Updated Successfully.");

        }
        catch (Exception Ex)
        {
            MessageBox.Show(Ex.Message);
           // return;
        }
    }
</code>
I am using VS 2012 and SQL Server 2012 Express.
Comment: my guess, your problem is in the sql operation (could be: changing primary key, or error foreign key constrait, etc). Try to simulate what your linq was trying to do directly using sql statement in SSMS.
Comment: I have done in SSMS but found not error. Every thing is fine in foreign key constraints.
Comment: you need to specify more detailed error message, like [this](http://stackoverflow.com/questions/11809530/linq-and-exception-has-been-thrown-by-the-target-of-an-invocation) may be. And which linq was causing error, the one when you assign bank variable or bankAccNo varibale?
Comment: hmm.. possible error source i can think of: Single() will throw error if no data matched by your query, use SingleOrDefault() to avoid this error.
Comment: @har07 thanks. error occured on bank variable. But i don't know how to print whole stack error. I have used SigleOrDefault() but it also didn't work. When i appliend ex.InnerException.Message() on cathc exception it shows "Object reference not set to instance of object".
Comment: I would recommend to check if bankRow.BankID is null, or is there any iBankName having BankID = null. Maybe comparing null value trigger error
Comment: nah, you said that. Something must be null. Maybe bankRow?
Comment: I have checked all the bank rows but there is no column having null value exist either parent or foreign key column. In backend I have created Linq to Sql where i have map all the tables in O/R designer of LINQ to SQL. every thing go na fine it works on other db's but in this db it give error.
Comment: oH one thing that i forget to mention that I have set BankAccNo type as BigInteger. I think error occured when i make comparison to bank accountNo and bankRow accountNo. Is it true that we can't make comparison of such type values?
Answer: You can try this. I think it is properly work....
<code>private void EditButton_Click(object sender, RoutedEventArgs e)
{
    try
    {

        DataClassesDataContext dataContextEdit = new DataClassesDataContext();
                   object item = MyDataGrid.SelectedItem;

        string m = (MyDataGrid.SelectedCells[cellNumber].Column.GetCellContent(item) as TextBlock).Text
        iBankName bank = (from p in dataContextEdit.iBankNames
                             where p.BankID == m
                             select p).Single();

        bank.Name = (MyDataGrid.SelectedCells[ColumnNumber].Column.GetCellContent(item) as TextBlock).Text

        //iBankAccountNo banAccRow = MyDataGrid.SelectedItem as iBankAccountNo;

//similarly another object create and access item
object item = MyDataGrid.SelectedItem;
        iBankAccountNo bankAccNo = (from p in dataContextEdit.iBankAccountNos
                                        where p.BankAccNo == banAccRow.BankAccNo
                                        select p).Single();

        bankAccNo.BankAccNo = (MyDataGrid.SelectedCells[columnNumber].Column.GetCellContent(item) as TextBlock).Text
        bankAccNo.Branch = (MyDataGrid.SelectedCells[columnNumber].Column.GetCellContent(item) as TextBlock).Text

        dataContextEdit.SubmitChanges();

        MessageBox.Show("Row Updated Successfully.");

    }
    catch (Exception Ex)
    {
        MessageBox.Show(Ex.Message);
       // return;
    }
}
</code>


Calculating the sum of $\sum_{n=1}^\infty \frac{(-1)^n2n(2n-1)}{2^{2n}}$

Question: The sum of the title is
$$\sum_{n=1}^\infty (-1)^nn(2n-1)x^{2n-1}$$
evaluated at $x=\frac{1}{2}$. I have tried to calculate the sum by writing
$$\sum_{n=1}^\infty (-1)^nn(2n-1)x^{2n-1} = \sum_{n=1}^\infty (-1)^n2n^2x^{2n-1} - \sum_{n=1}^\infty (-1)^n nx^{2n-1}$$
Now the second addend is easy to compute, but I don't know how to deal with the $n^2$ of the first one. Any tips on how to do it?
Comment: A hint:  consider what happens when you take $(2n)(2n-1)x^{2n}$ and differentiate twice.
Comment: Perhaps not eligant or efficient but I would differentiate or integrate until you get a simple taylor that you recognize or understand...
Answer: $$\sum_{n=1}^\infty (-1)^nn(2n-1)x^{2n-1}=\frac{x}2\sum_{n=1}^\infty (-1)^n(2n)(2n-1)x^{2n-2}$$
and note that
$$(x^{2n})''=(2n)(2n-1)x^{2n-2}$$
Can you proceed from here?


Explanation of dual-sideband vs. single-sideband I/Q modulation

Question: I'm reading a the paper "Dual-Sideband Linear FMCW Lidar with Homodyne Detection for Application in 3D Imaging" (PDF) in which an in-phase/quadrature (I/Q) modulator is used in different modes: in single-sideband (SSB) mode, in which
$V_{I,SSB}(t)=V_D \cos(2\pi f_1 t + \pi \frac{f_2-f_1}{T}t^2), V_{Q,SSB}(t)=V_D \sin(2\pi f_1 t + \pi \frac{f_2-f_1}{T}t^2)$
and in double-sideband (DSB) mode, in which
$V_{I,DSB}(t)=V_D \cos(-2\pi f_2 t + 2\pi \frac{f_2}{T}t^2), V_{Q,DSB}(t)=V_D \sin(-2\pi f_2 t + 2\pi \frac{f_2}{T}t^2)$
where $V_D$ is a constant amplitude factor, $f_2-f_1$ is the bandwidth of the chirp, and $T$ is the period of the chirp.
I'm having trouble seeing where these expressions come from. In particular, further down in the article some examples are given why the thus obtained DSB signal has twice the bandwidth (resulting in twice the range resolution), but it is not at all clear to me why this is the case. Can someone explain this in simple terms?
Answer: The instantaneous frequency of the modulating signal is $f_1 + \frac{f_2 - f_1}{T}t$ in the SSB case, and $-f_2 + 2 f_2 \frac{t}{T}$ in the DSB case. Hence in the period from $0$ to $T$, the frequency ranges over the intervals $[f_1, f_2]$ and $[-f_2, f_2]$, respectively.
In the paper it is given that $f_1$ is 0.1 GHz and $f_2$ is 20 GHz, so for these particular parameters, in the second case the total frequency excursion is about twice as large.


Reproducing "multiple declarations" error from linker

Question: So, I was going to demonstrate the problem of (non-template) implementation in C++ .h files to a college.
But right now I can't reproduce it as expected. Here's my code:
<code>// common.h

#ifndef common_h
#define common_h

#include <iostream>

class common
{
    public:
    void Hello() {
        // Implementation in header file
        std::cout << "Hello from common" << std::endl;
    }
};

#endif // common_h
</code>
<code>// user1.h

#ifndef user1_h
#define user1_h

#include "common.h"

class user1
{
    public:
    user1();

    private:
    common g;
};

#endif // user1_h
</code>
<code>// user1.cpp

#include "user1.h"

#include <iostream>

user1::user1()
{
    std::cout << "Constructing user 1" << std::endl;
    g.Hello();
}
</code>
<code>// user2.h

// Exactly as user1.h except the class+constructor name
</code>
<code>// user2.cpp

// Exactly as user1.cpp except the class+constructor name
</code>
<code>// main.cpp

#include "user1.h"
#include "user2.h"

int main()
{
    user1 u1;
    user2 u2;
}
</code>
I'm compiling the code like this:
<code>g++ -c -g -O0 -fno-lto -fno-inline-small-functions user1.cpp
g++ -c -g -O0 -fno-lto -fno-inline-small-functions user2.cpp
g++ -c -g -O0 -fno-lto -fno-inline-small-functions main.cpp

g++ user1.o user2.o main.o
</code>
Nothing fails and program works as expected.
Why am I not getting a "multiple declarations" error on the "Hello" function in common.h?
I looked into the object files (using objdump) and I see this tag: LINK_ONCE_DISCARD. Could this be the reason? Can anyone supply more details? I'm sure I've seen this before so something must have change (maybe from a compiler update or something).
Compiler version:
<code>>g++ --version
g++ (Rev2, Built by MSYS2 project) 12.1.0
Copyright (C) 2022 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code>
Comment: A function defined inside the class declaration is automatically `inline`, so the linker takes care of removing duplicates.
Comment: Wow. I had no idea.  Defining Hello outside (but still in the header file) gives me the expected error. Thank you, @BoP
Comment: @DoP, do you really mean "inline" in the sense that the code will be inlined in a caller and not result in a call to "Hello"?
Comment: @jgreen81 Yes, although you should remember inline is only a "recommendation" to the compiler (i.e. it can be ignored anyway).
Comment: The [inline](https://en.cppreference.com/w/cpp/language/inline) keyword has two meanings - that a function might be expanded inline, and that it can be included several times without creating a duplicate. The second part is the most important nowadays. Modern compilers will tend to expand functions where it makes sense, whether they are marked or not - that's why you need `-fno-inline-small-functions` to ask it not to...
Comment: Thank you. I was aware of "inline variables" but not that this effect also affected functions.
Answer: Thanks to @BoP, here's the answer:
https://en.cppreference.com/w/cpp/language/inline
My "Hello" function is inline because it is defined inside a class declaration.


OpenStack Redundant Ceph/Cinder Storage Architecture

Question: Hello Serverfault community,
I'm currently designing an OpenStack cluster. The part where I'm currently stuck is the Storage Architecture.
I thought of building two redundant Ceph clusters in different racks with a different fuse and UPS. So far so good. The thing is, Openstack Cinder communicates via the network with Ceph. Even when I have redundant switches in place what if the router/gateway of the Ceph network goes down. So in order to achieve full redundancy I need two redundant gateways, am I right?
I have made an abstract image of what I'm trying to do: Storage Architecture
On the left you can see the OpenStack Compute nodes, everyone connected via two separate 10GE Links to each switch. Those switches are connected via 2x 10GE trunk to each of the dedicated Ceph cluster switches who are connected with each other, so Ceph nodes can communicate with each other for redundancy. Note, that even when I have used different colors this whole network topology is in one VLAN.
From my point of view, everything can fail and the cluster would still be operating normally. But what if the gateway of the storage network fails? Then I guess it would work as long as the switch has cached MAC ARP entries but when they expire the cluster would go down. Do you have any suggestions for me how to make the cluster fully redundant and optimize it?
I am only focusing on the storage component of OpenStack, therefore the Compute nodes are not connected to the network node or management network yet.
Thanks
Comment: Is there a specific reason why you want two separate CEPH clusters?
Comment: I don't want two separate Ceph Clusters. It should only show that I don't want the replica to be in the same rack as if for example the fuse for the rack would have an issue the replica would also be down.
Answer: For the CEPH part of your question: CEPH uses the CRUSH map to decide where objects are stored, which you can customize. Marking OSDs with the rack they belong to and preventing copies of the same object to be stored in the same rack is actually quite common. For more on this, look here. Therefore you don't need two separate CEPH clusters. For network configuration, CEPH nodes should be in a "Cluster Network" thats accessible from your Cinder nodes and have a private Cluster network thats used for replication between OSDs.
As for Cinder: Yes, if Cinder goes down you loose access. Therefore you'll want to deploy Cinder in a HA configuration.
Comment: Thanks. The point I was trying to make is that the Cluster Network needs to be redundant too through an external device/HA router configuration, am I right? I would indeed deploy Cinder on HA controller nodes.
Comment: The cluster network is normally deployed using e.g. redundant switches and LACP. It's not routed anywhere since it's only used by CEPH internally, so I'm not sure what you mean?


apache balancer, workers on internal IPs

Question: I'm planning to build my first balancer  for one of our website, using apaches mod_proxy and mod_proxy_balancer. Having not so many external IP's I'm thinking about to use each machines Internal IP but I can not decide if this would be a good workaround or not!
Is it going to be enough fast? This is a usable or not?
Answer: This is what everybody else does (who also doesn't have enough IPv4 addresses).
You could also use your IPv6 addresses internally, if you have gotten them yet.
Comment: Thank you very much for your feedback. One issue is not really clear for me. How to handle the web contents and mysql database? Is it a problem if the workers are Virtual Machines?
Comment: That sounds like a completely different question. :)


CakePHP: best way to remove a field from the admin scaffold

Question: When I admin-scaffold the Users model, everything works great. However, it also has the "password" field. Which is a hash of the actual password.
When you save a user in the admin console, it saves the hashed password, which screws everything up.
What's the simplest way to exclude a field from the admin-scaffold with minimal interference to the awesome auto-magic of the admin-scaffold?
Thanks
Comment: Is there a reason why you don't bake your code using (custom) bake templates when going "productive"? scaffolding as such is usually just for prototyping until the database layer stabilizes enough to start baking solid files.
But besides that you might be interesting in my proposals for cake2.4 regarding $skipFields: https://cakephp.lighthouseapp.com/projects/42648/tickets/1920-enhancements-for-bake-templates (could also be applied to your case).
Comment: Thanks Mark. I am not ready to bake yet. But I think your proposal for skipping fields in bake is good.
Answer: You will want to make your own bake theme, so you can then edit the template to remove the file.
It really is as simple as this, http://book.cakephp.org/2.0/en/console-and-shells/code-generation-with-bake.html#modify-default-html-produced-by-baked-templates
Just copy the files from inside lib/Cake/Console/Templates/default/views into your project under app/Console/Templates/[themename]/views and then you can edit the view templates.
The same applies to all the other files too, such as controllers and models. Then when you bake your project you'll be asked which theme you want to use and you can select your own.
Here is an example from one of my projects.

The only real thing to note is that your theme names must be unique!


Leave-one-out cross validation: Relatively unbiased estimate of generalization performance?

Question: I have read that leave-one-out cross-validation provides a relatively "unbiased estimate of the true generalization performance" (e.g. here) and that this is an advantageous property of the leave-one-out CV.
However, I don't see how this follows from the properties of leave-one-out CV. Why is the bias of this estimator low when compared to others?
Update:
I keep investigating the topic, and I believe it has to do with the fact that this estimator is less pessimistic than, say, K-fold validation, since it uses all the data but one instance, but it would be great to read a mathematical derivation of this.
Comment: Hi Amelio - I have seen several mathematical derivations of this in the papers cited in this answer https://stats.stackexchange.com/questions/280665/does-k-fold-cv-with-k-n-loo-provide-the-most-or-least-variable-estimates/358278#358278 - is there one in particular you want to see ?
Answer: I don't think there is a need for a mathematical derivation of the fact that in ML, with increasing training test size, the prediction error rates decrease. LOO -- compared to k-fold validation -- maximizes the training set size, as you have observed.
However, LOO can be sensitive to "twinning" -- when you have highly correlated samples, with LOO you have the guarantee that for each sample used as a test set, the remaining "twins" will be in the training set. This can be diagnosed by a rapid decrease in accuracy when LOO is replaced by, say, 10-fold crossvalidation (or a stratified validation, if for example the samples are paired). In my experience, this can lead to a disaster if generally your data set is small.
In a perfect world, you have also a validation set that you never use to train your model, not even in a CV setting. You keep it for the sole purpose of testing the final performance of a model before you send of the paper :-)
Answer: I am new to this topic but I think I can give you a concrete and elementary example of how least square cross-validation with the leave-one-out method produces an "unbiased" estimate of integrated mean square error ($\mathrm{IMSE}$ for short) in the context of kernel density estimation.
Recall a typical univariate kernel density estimator $\widehat{f}$:
$$
\widehat{f}(x)=\frac{1}{n h} \sum_{i=1}^n K\left(\frac{X_i-x}{h}\right),
$$
where we have imposed the following assumptions:

A.1 $X_1, \cdots, X_n \stackrel{i . i . d .}{\sim} f$.
A.2 $f^{\prime\prime}(x)$ is continuous and bounded in the neighborhood of $x$.
A.3 The kernel function $K(\cdot)$ is a symmetric pdf which maximized at $0$ and satisfies:
$$
(i)\begin{aligned}\int K(u) d u=1\end{aligned},\quad
(ii)\begin{aligned}\nu_2:=\int K^2(u) d u<\infty\end{aligned},\quad
(iii)\begin{aligned}\kappa_2:=\int u^2 K(u) d u \in(0, \infty)\end{aligned}
$$
A.4 $h \rightarrow 0$, $n h \rightarrow \infty$ as $n \rightarrow \infty$, which means $n^{-1}=o\left((n h)^{-1}\right)$.

Under the above assumptions, the integrated mean square error can be computed as:
$$
\begin{aligned}
\mathrm{IMSE}\left(\widehat{f}\right) =& \int \operatorname{MSE} \widehat{f}(x) d x\\
=& \frac{1}{n h}\int K(u)^2 d u+\frac{h^4}{4}\left(\int u^2 K(u) d u\right)^2 \int\left[f^{\prime\prime}(x)\right]^2 d x+o\left(h^4+\frac{1}{n h}\right),
\end{aligned}
$$
which can be easily derived from the bias rendered by KDE (the derivation can be referred to in this question).
Accompanied with this knowledge, let us see how least square cross-validation with the leave-one-out method produces an "unbiased" estimate of $\mathrm{IMSE}\left(\widehat{f}\right)$.
Let us define the objective function of least square cross-validation as follows:
$$
\begin{aligned}
LSCV&=\int[\widehat{f}(x)-f(x)]^2 d x \\
&=\underbrace{\int[\widehat{f}(x)]^2 d x}_{=:\mathcal{I}_{1n}}-2 \underbrace{\int \widehat{f}(x) f(x) d x}_{=:\mathcal{I}_{2n}}+\int f^2(x) d x \\
&=\mathcal{I}_{1n} - 2\mathcal{I}_{2n}+\int f^2(x) d x\\
&={\mathcal{I}}_{1n} - 2\widehat{\mathcal{I}}_{2n}+\int f^2(x) d x + o_{\mathbb{P}}(1),\\
\end{aligned}
$$
where $\widehat{\mathcal{I}}_{2n}$ denotes the estimand of ${\mathcal{I}}_{2n}$.
The leave-one-out method is applied to the computation of $\widehat{\mathcal{I}}_{2n}$. To ease of exposition, let me define two versions of
$\mathcal{I}_{2n}$:
$$
\begin{aligned}
\widehat{\mathcal{I}_{2n}}^{\text{LOO}} :=& \frac{1}{n} \sum_{i=1}^n \widehat{f}_{-i}\left(X_i\right) =\frac{1}{n^2 h} \sum_{i=1}^n \sum_{j=1, j \neq i}^n K\left(\frac{X_j-X_i}{h}\right),\\
\widehat{\mathcal{I}_{2n}}^{\text{without LOO}} :=& \frac{1}{n} \sum_{i=1}^n \widehat{f}\left(X_i\right)=\frac{1}{n^{2}h} \sum_{i=1}^n\sum_{j=1}^n K\left(\frac{X_j-X_i}{h}\right).
\end{aligned}
$$
Notice that their only difference lies in:
$$
\widehat{\mathcal{I}_{2n}}^{\text{without LOO}} = \widehat{\mathcal{I}_{2n}}^{\text{LOO}} + \frac{1}{n h} K(0).
$$
But as we will see later, this difference plays a key role in the conclusion that without leave-one-out, the objective function $LSCV$ is biased concerning $\mathrm{IMSE}$ and is minimized at $h=0$, which violates the condition of $n h \rightarrow \infty$ as $n \rightarrow \infty$.
Now, taking the expectation $\mathbb{E}_{X}(\cdot)$ to $LSCV^{\text{LOO}}$ gives:
$$
\mathbb{E}_{X}\left(LSCV^{\text{LOO}}\right) = \mathbb{E}_{X}\left[{\mathcal{I}}_{1 n}\right]-2 \mathbb{E}_{X}\left[\widehat{\mathcal{I}}_{2 n}^{\text{LOO}}\right]+\int f^2(x) d x.
$$
The first term is computed as:
$$
\begin{aligned}
\mathbb{E}_{X}\left[{\mathcal{I}}_{1 n}\right]=& \mathbb{E}_{X}\left[\int[\widehat{f}(x)]^2 d x\right] = \int\mathbb{E}_{X}\left[[\widehat{f}(x)]^2\right]  d x\\
 =& \int\mathrm{Var}\widehat{f}(x)  d x + \int\mathbb{E}_{X}^2\left[\widehat{f}(x)\right]  d x \\
=&\int  \frac{f(x)}{n h} \nu_2+o\left(\frac{1}{n h}\right)  + \left(f(x)+\frac{h^2}{2} f^{\prime \prime}(x) \kappa_2 + o\left(h^2\right)\right)^{2} dx \\
=& \frac{\nu_2}{n h}+o\left(\frac{1}{n h}\right) + \int f^{2}(x) dx + \frac{h^4}{4} \int u^2 K(u) d u \int\left[f^{\prime \prime}(x)\right]^2 d x+o\left(h^4\right)\\
& + \int h^{2}f(x)f^{\prime \prime}(x) \kappa_2 dx + 2 \int f(x)o\left(h^2\right) dx ,
\end{aligned}
$$
where the third line can be referred (again) to the link and
$$
\nu_2:=\int K^2(u) d u.
$$
The second term is computed as:
$$
\begin{aligned}
2 \mathbb{E}_X\left[\widehat{\mathcal{I}}_{2 n}^{\mathrm{LOO}}\right] =& \mathbb{E}_{X}\left[\frac{1}{n^2 h} \sum_{i=1}^n \sum_{j=1, j \neq i}^n2 K\left(\frac{X_j-X_i}{h}\right)\right] = \mathbb{E}_{X}\left[\frac{2(n-1)}{n^{2}} \sum_{i=1}^n \widehat{f}_{-i}(X_{i})\right] \\
=& \frac{2(n-1)}{n^{2}} \sum_{i=1}^n \mathbb{E}_{X_{i}}\left[\mathbb{E}_{X_{-i}}\left[\widehat{f}_{-i}(X_{i})\right]\right] \\
=& \frac{2(n-1)}{n^{2}} \sum_{i=1}^n \mathbb{E}_{X_{i}}\left[f(X_{i})+\frac{h^2}{2} f^{\prime \prime}(X_{i}) \kappa_2+o\left(h^2\right)\right] \\
=& \frac{2(n-1)}{n} \int\left[f(X_{i})+\frac{h^2}{2} f^{\prime \prime}(X_{i}) \kappa_2+o\left(h^2\right)\right]f(X_{i}) d X_{i}\\
=& \frac{2(n-1)}{n} \int\left[f(x)+\frac{h^2}{2} f^{\prime \prime}(x) \kappa_2+o\left(h^2\right)\right]f(x) d x\\
=& \frac{2(n-1)}{n} \int f^{2}(x) dx +\frac{2(n-1)}{n} \int \frac{h^2}{2} f^{\prime \prime}(x)f(x)  \kappa_2 dx + \frac{2(n-1)}{n} o\left(h^2\right)  \\
\end{aligned}
$$
Inserting the two expressions back $\mathbb{E}_{X}\left[{LSCV}^{\text{LOO}}(h)\right]$ gives:
$$
\begin{aligned}
& \mathbb{E}_{X}\left[{LSCV}^{\text{LOO}}(h)\right]\\
=& \frac{\nu_2}{n h}+o\left(\frac{1}{n h}\right) + \int f^{2}(x) dx + \frac{h^4}{4} \int u^2 K(u) d u \int\left[f^{\prime \prime}(x)\right]^2 d x+o\left(h^4\right) \\
&+ \int h^{2}f(x)f^{\prime \prime}(x) \kappa_2 dx + 2 \int f(x)o\left(h^2\right) dx \\
&-\left[\frac{2(n-1)}{n} \int f^{2}(x) dx +\frac{2(n-1)}{n} \int \frac{h^2}{2} f^{\prime \prime}(x)f(x)  \kappa_2 dx + \frac{2(n-1)}{n} o\left(h^2\right)\right]+\int f^2(x) d x\\
=& \frac{\nu_2}{n h}+o\left(\frac{1}{n h}\right) + \frac{h^4}{4} \int u^2 K(u) d u \int\left[f^{\prime \prime}(x)\right]^2 d x+o\left(h^4\right) + O\left(\frac{1}{n}\right),
\end{aligned}
$$
Now, we can see that
$$
\mathbb{E}_{X}\left[{LSCV}^{\text{LOO}}(h)\right]\sim \operatorname{IMSE}(\widehat{f}).
$$
And it is quite evident to see that
$$
\mathbb{E}_{X}\left[LSC V^{\text {without } L O O}(h)\right]=\mathbb{E}_{X}\left[LSC V^{L O O}(h)\right]-\frac{2}{n h} K(0).
$$
To this end, one can be informed in the context of KDE that the leave-one-out cross-validation provides a relatively "unbiased estimate of the true generalization performance".


Nova linha em PHP na função fopen

Question: Bom pessoal, eu estava seguindo uma apostila de PHP e ate aqui tudo bem, mas o problema esta em gravar os dados em um bloco de notas do windows, ao invés de ele dar nova linha "\n", ele esta colocando os dados uns atras dos outros como se não desse enter, vou postar o código e desde já obrigado pela ajuda de vocês...
$texto = $date."\t".$tireqty." Pneus \t".$oilqty." Oleo \t "
.$sparkqty." Plugues de velas \t $".$totalamount."\t".$address."\n";

if($arquivo = fopen("carteirainter.txt", 'ab'))
{
    fputs($arquivo, $texto."\n");
    fclose($arquivo);
}
else
    echo "Não foi possivel efetuar a gravaçao.
";

Answer: Utilize a constante PHP_EOL:
fputs($arquivo, $texto.PHP_EOL);

Alternativamente, pode forçar desse modo:
fputs($arquivo, $texto."
");

Outro modo é usar o carriage return \r juntamente com o newline \n:
fputs($arquivo, $texto."\r\n");

Recomenda-se que o ambiente esteja usando um conjunto de caracteres UTF8.
Observação adicional sobre compatibilidade do carriage return e newline:
\n -> linux
\r -> Mac
\n -> Mac OS-X
\r\n -> Windows

Comment: pdf tocar no assunto?

Nova linha em PHP na função fopen


É possível reiniciar o servidor do NodeJS quando ocorrer uma modificação automaticamente?

Question: Toda vez que eu tento fazer alguma modificação no meu arquivo app.js tenho que fechar e iniciar o servidor para que as modificações tenham efeito, teria alguma forma de reiniciar automaticamente depois de uma mudança? como no php.
Exemplo:
var http = require('http');

var server = http.createServer(function(request, response){
    response.writeHead(200, {"Content-Type": "text/html"});
    response.write("
Hello World!
"); // <-- se mudar o texto no F5 não atualiza.
    response.end();
});

var servidorLigou = function () {
    console.log('Servidor Hello World rodando!');
};

server.listen(3000,servidorLigou);

Answer: Você pode utilizar um supervisor para essa função. Uma alternativa para esse papel é o nodemon.
Para instalar é bem simples, como mostra o site:
$ npm install nodemon -g
$ nodemon app.js

Esta pergunta possui diversas opções de supervisors e como utilizar, caso tenha interesse.
Comment: Opa, era isto mesmo. então eu devo usar o `forever` em produção e o nodemon em desenvolvimento? não sei por que isso não vem por padrão o.O
Comment: @GabrielRodrigues não vem por padrão porque há mais maneiras de fazer e são soluções independentes e específicas do ambiente (sistema operativo do servidor) em que o Node correr.


CMake substitute text in a file generated by a target

Question: I have cmake target which runs a setup.exe on windows which installs a tool using add_custom_target as follows
# TOOL_TEMP_INSTALL_PATH is the installation path which is set earlier in cmake
add_custom_target(
    install_tool
    COMMAND ${TOOL_TEMP_DIR}/setup.exe /DIR=${TOOL_TEMP_INSTALL_PATH}
)

After the installation, I want to replace text in a configuration file located at ${TOOL_TEMP_INSTALL_PATH}/tool.ini replacing a line of text "LICENSE_FILE=Enter License server" with  "LICENSE_FILE=30309@server"
Following commands will achieve this but this needs to be run after install_tool target is built.
file(READ "${TOOL_TEMP_INSTALL_PATH}/tool.ini" filedata)
string(REGEX REPLACE "LICENSE_FILE=Enter License server here"
"LICENSE_FILE=30309@server" filedata "${filedata}")
file(WRITE  "${TOOL_TEMP_INSTALL_PATH}/tool.ini" "${filedata}")

How can I add these commands as a dependency to install_tool? Or is there a better way to achieve this on windows?
Answer: Since you want to run two things in order as part of the same target, you can use multiple COMMAND entries in the same target.  The difficulty is that COMMAND can't handle CMake code, but only system commands.  The typical solution is to call CMake in a subshell on a script file:
COMMAND ${CMAKE_COMMAND} -P path_to_script
So, place your file modification commands in a file in your source tree called license-install.cmake, and add another COMMAND to your add_custom_target
Hint: You might consider add_custom_command instead, so you can specify a file in the installed tree as a dependency.  This will allow CMake to see the installed tool as a build product, and to skip the install step if the tool is already installed.  You'll still need an add_custom_target with a dependency on your command output to hook it in correctly.


What does it mean for regression to the mean to "work backward in time"?

Question: Please see the emboldened phrase below.

      Then the hammer drops. The triumph of mediocrity observed by Secrist,
Hotelling points out, is more or less automatic whenever we study a variable
that's affected by both stable factors and the influence of chance. Secrist's
hundreds of tables and graphs "prove nothing more than that the ratios in
question have a tendency to wander about." The result of Secrist's exhaustive
investigation is "mathematically obvious from general considerations, and
does not need the vast accumulation of data adduced to prove it." Hotelling
drives his point home with a single, decisive observation. Secrist believed the
regression to mediocrity resulted from the corrosive effect of competitive
forces over time; competition was what caused the top stores in 1916 to be
hardly above average in 1922. But what happens if you select the stores with
the highest performance in 1922? As in Galton's analysis, these stores are
likely to have been both lucky and good. If you turn back the clock to 1916,
whatever intrinsic good management they possess should still be in force, but
their luck may be totally different. Those stores will typically be closer to
mediocre in 1916 than in 1922. In other words, if regression to the mean
were, as Secrist thought, the natural result of competitive forces, those forces
would have to work backward in time as well as forward.
      Hotelling's review is polite but firm, distinctly more in sorrow than in
anger: he is trying to explain to a distinguished colleague, in the kindest way
possible, that he has wasted ten years of his life. But Secrist didn't take the
hint. The issue after next of JASA ran his contentious letter of response,
pointing out a few misapprehensions in Hotelling's review, but otherwise
spectacularly missing the point. Secrist insisted once again that the regression
to mediocrity was not a mere statistical generality, but rather was particular to
"data affected by competitive pressure and managerial control." At this point
Hotelling stops being nice and lays it out straight. "The thesis of the book," he
writes in response, "when correctly interpreted, is essentially trivial. . . . To
'prove' such a mathematical result by a costly and prolonged numerical study
of many kinds of business profit and expense ratios is analogous to proving
the multiplication table by arranging elephants in rows and columns, and then
doing the same for numerous other kinds of animals. The performance, though
perhaps entertaining, and having a certain pedagogical value, is not an important contribution either to zoölogy or mathematics."

Ellenberg, How Not to Be Wrong (2014), pages 307-8.
Answer: Hotelling's point is that both these features not only happened but should have been expected to happen:

leading stores in 1916 more often than not became closer to the average in 1922 than they had been in 1916
leading stores in 1922 more often than not had been closer to the average in 1916 than they became in 1922

so regression to the mean happened forward in time for the 1916 leading stores but backward in time for the 1922 leading stores.
There was nothing new in this:  Galton's original studies had shown that the children of extremely tall parents tended to be closer to the average height than their parents were, leading to the use of the word "regression" for the analysis which showed this; Galton then showed with the same data that the parents of extremely tall children tended to be closer to the average height than their children were.  One of his 1875 charts, copied from Wikipedia, looked like this


Do we require an invertible function in substitution method for integration?

Question: When we use a substitution $u = g(x)$ to compute an indefinite integral $\int f(x) dx$ or a definite integral $\int_a^b f(x)dx$, what is required of the function $g$ in each case? Here are what I think. Please correct me if I am wrong.
For some integrals, we need to express $x$ in terms of $u$; in that case, I think we should require $g$ to be invertible on $\mathbb{R}$ (in the case of $\int f(x) dx$), or on $[a, b]$ (in the case of $\int_a^b f(x)dx$). Or else we need to discuss by cases, i.e. break the function $g$ into invertible pieces.
For integrals that do not require us to express $x$ in terms of $u$, consider for example $\int \sin^2 x \cos x dx$ and $\int_0^{\frac{2\pi}{3}} \sin^2 x \cos x dx$. Here $u = \sin x$ would work, but notice that the function $g(x) = \sin x$ is not invertible on $[0, \frac{2\pi}{3}]$, let alone on $\mathbb{R}$. So it seems to me that invertibility is not necessary.
In short, my question is about precisely which functions $g$  yield legitimate substitutions $u = g(x)$.
Comment: When you do a $u$-substitution like $u = g(x)$, you don't care about invertibility. You just need the function to be differentiable on the interval of your given integral. Changing variables during integration doesn't inherently require monotonicity, invertibility, or injectivity except when obtaining the new integration limits after making an implicit substitution. You can also solve for $x$ as a function of $u$, but if you get that $x(u)$ is multivalued with more than one branch, you would have to sub differently along each branch.
Answer: $g(x)$ only has to be such that it is differenetiable.
See UCSD notes.
I suppose there is also assumption that $g'(x)$ is an integrable function.


How to get number of rows returned by Resultset while using HSQLDB?

Question: I am getting exception feature not supported while getting the total no of rows using ResultSet.last() function.
I tried using the hsqldb specific connection and ResultSet class but no success.
Can some one guide any way to get the no of rows from result set except looping through all the rows.
the code snippet used for getting no of rows is given below:
rs.last();
int total = rs.getRow();
System.out.println("total no of rows in stu are "+total);
rs.beforeFirst()

Comment: Why not just do `select count(*) from your_condition` and refer to http://stackoverflow.com/questions/19469812/getting-the-count-of-results-returned-by-a-mysql-query-with-jdbc-in-the-most-per/19470146#19470146
Comment: you will have to execute a separate query that returns only the count and use the value , else you will have to run a loop to get the count which isnt appropriat
Comment: Please share your exception
Comment: The exception thrown is :
java.sql.SQLFeatureNotSupportedException: feature not supported
Comment: @Jagdeep Please mention on which line this exception is coming,i think it is on rs.last()
Answer: After having look at HSQLDB api ,it can be done same as for ORACLE which is shown below
String URL = "jdbc:oracle:thin:@ip:port:sid";
String USER = "test";
String PASS = "test";
String query = "Select * from mytable";
try {
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
    Connection con = DriverManager.getConnection(URL, USER, PASS);
    Statement stmt = con.createStatement(
            ResultSet.TYPE_SCROLL_INSENSITIVE,
            ResultSet.CONCUR_READ_ONLY);
    ResultSet rs = stmt.executeQuery(query);
    if (rs.next()) {
        rs.last();
        System.out.println("total rows is : " + rs.getRow());
    } else {
        System.out.println("No Data");
    }
} catch (Exception e) {
    e.printStackTrace();
}

Comment: The key in the answer is specifying ResultSet.TYPE-SCROLL_INSENSITIVE. The default does not allow use of rs.last().
Comment: @fredt yes that's right.he has to mention these flags for manipulating the resultset in both direction
Comment: @fredt: Thanks for your help, setting the flag helped to get the count ...:)


$http service in AngularJS

Question: I am new to AngularJS and I am trying to put together a practice WebApp,
In the earlier versions of My App I had a single Controller and I used the $http Service to fetch Data from a JSON file like so
var App = angular.module('testApp', []);
App.controller('firstCtrl', ['$scope', '$http', function($scope, $http) {
    $scope.items = [];
    $http.get('data.json').success(function(data) {
      $scope.items = data;
    });
}]);

The $http Service worked fine, Then as I progressed I had Multiple Controllers and to Share the Data between the Controllers I moved the $http Service to a Factory like so
var App = angular.module('testApp', []);

App.factory('DataFactory', ['$http', function($http) {
    var DataFactory = {};
    var items = [];
    $http.get('data.json').success(function(data) {
      items = data;
    });
    DataFactory.data = function() {
        return items;
    };
    return DataFactory;
}]);

App.controller('firstCtrl', ['$scope', 'DataFactory',function($scope, DataFactory) {
    $scope.items = [];
    $scope.items = DataFactory.data();
}]);

And here is the HTML

{{item.name}}

I don't know why for some reason the Data is not being Displayed after I moved the $http Service to a Factory,
What am I doing wrong, I don't see any errors in the Console
Answer: As one learns a lot in 18 months, I would like to  update my answer. The below example is how I would solve the problem today. (See bottom for original solution)
function dataFactory($http) {
    //Service interface, all properties and methods will be set to this object.
    var dataFactory={};

    //Instead of using $q, the function will just return the http-promise containing the response data.
    dataFactory.getItems=function() {
        return $http
            .get('data.json')
            .then(function(response) {
                return response.data;
            });
    }

    //Return object containing the service interface.
    return dataFactory;
}
//Use $inject property to specifiy your DI objects, rather than using array syntax.
dataFactory.$inject=['$http'];

function firstController(DataFactory) {
    //Use this with controllerAs instead of injecting $scope.
    var vm=this;
    vm.items=[];

    DataFactory
        .getItems()
        .then(function(items) {
            vm.items=items;
        }, function(err) {
            //error handler
            alert("Got an error");
        })
}
//same here, use $inject property.
firstController.$inject=['dataFactory'];

angular
    .module('testApp', [])
    .factory('DataFactory', dataFactory)
    .controller('FirstController', firstController);

And the HTML

{{item.name}}

This is how I would write the code. However, this is not how I would solve it. I wouldn't make any changes the data service, But I would change the implementation of the controller. Either I would resolve the items data through the router, or I would bundle the controller and html as a directive, or as of 1.5 a component.
Using a directive
function itemsDirective() {
    function controller(DataFactory) {
        var vm=this;
        vm.items=[];

        DataFactory
            .getItems()
            .then(function(items) {
                vm.items=items;
            }, function(err) {
                //error handler
                alert("Got an error");
            })
    }
    controller.$inject=['dataFactory'];

    return {
        restrict:'E',
        template:'

{{item.name}}

',
        controller: controller,
        controllerAs: 'first'
    }
}

angular
    .module('testApp')
    .directive('itemsDirective', itemsDirective);

Old answer (Jul 23 '14 at 20:26)
Because the value doesn't get set before it returns it's value. Having that said you might wanna restructure your Service(factory), also use $q to handle the promise. Consider the following example:
var App = angular.module('testApp', []);

App.factory('DataFactory', ['$http', '$q', function($http, $q) {
    var getItems = function() {
        var deffered = $q.defer();

        $http.get('data.json').success(function(data) {
             deffered.resolve(data);
        });

        return deffered.promise;
    };

    return {
       getItems: getItems
    };
}]);

App.controller('firstCtrl', ['$scope', 'DataFactory',function($scope, DataFactory) {
   $scope.items = DataFactory.getItems();
}]);

It's common practice to use $q while working with async tasks such as http-request.
Comment: At least in AngularJS 1.2+ it's not possible to directly bind to a promise. You'll have to unwrap the promise in the controller and set the $scope.items variable in the then(...) callback.
So it's enough to return the prmise from the $http.get and unwrap it in the controller. No custom promise logic required (which actually is unnecessary anyway).
Comment: $http also is set up as a promise by default. It's using 'success' and 'error' in place of $q's 'then'.
Answer: A simplified solution based on the Answer from cbass, unwrapping the promise in the controller:
var App = angular.module('testApp', []);

App.factory('DataFactory', ['$http', function($http) {
    var getItems = function() {
        return $http.get('data.json');
    };

    return {
       getItems: getItems
    };
}]);

App.controller('firstCtrl', ['$scope', 'DataFactory',function($scope, DataFactory) {
   DataFactory.getItems().success(function(result){
       $scope.items = result;
   });
}]);

Comment: What if I have another Controller which needs the items? Do I have to redo it to get the items in this new Controller? If Yes then won't I be making another http request?
Comment: Either of the soluations above will make a http-request apon calling the getItems function. You can however choose to cache the response in the service and then reference that in your controller(s). In this case you might wanna make the http-request apon initalization of the service and/or continuosly update the cache.
Comment: @abhi yes, with this solution every controller makes it's own request. But you can use the `cache: true` option to cache the result. So the second controller will load the data from the cache. see the Caching section in the docs here: https://docs.angularjs.org/api/ng/service/$http

$http service in AngularJS


Evento MySQL para bloquear usuario com x denuncias

Question: Tenho uma tabela de denuncias onde gravo as informaçoes dos usuários que denunciaram e quem eles denunciaram
   id | user   |   denunciado
    1 | userx  |   userY
    2 | userz  |   userY

e por aí vai, agora gostaria de fazer um evento diário no mysql que verificasse se o numero de vezes que o usuario foi denunciado é maior do que um numero X de denuncias para poder bloquear o mesmo
Vou fazer uma verificação 1 vez por dia, apenas ja que tem muitas pessoas que gostam de "floodar" nas denuncias
Resolvi da seguinte forma
UPDATE usuarios SET cadastro=3 WHERE
id IN (SELECT
denunciado
FROM denuncias
GROUP BY denunciado
HAVING COUNT(*) > 30)

Dentro de um evento que vai rodar as 3 da manhã de cada dia
Realmente, não sou bom em fazer as perguntas, eu não teria entendido o que eu estou perguntando se fosse responder essa pergunta, porém foi a unica forma que eu consegui me expressar, se alguém tiver uma sugestão baseada na resposta e na pergunta pode editar pra ajudar outros membros da comunidade
Comment: Outro fator assim que fiquei na dúvida, é por dia ? ou seja, tem uma data envolvida ?
Comment: Enquanto eu respondia, percebi que a pergunta não é muito clara. Você poderia editá-la para esclarecer se quer o que eu respondi com as duas primeiras queries, o que eu respondi com a terceira, ou se é alguma outra coisa?
Comment: Você poderia criar uma trigger para verificar se caso o usuário tivesse número >= x o seu status poderia alterar. [=
Comment: depende @Fúlvio é executada 1 vez ao dia, mas não é avaliado se o usuario foi denunciado x vezes naquele dia e sim num total de denuncias desde que se registrou
Comment: Entendi @RodrigoBorth ... vlw
Answer: Você só precisa contar os resultados:
SELECT COUNT(*) AS denuncias
FROM tabela
WHERE denunciado = 'userY'

Ou, se quiser a resposta já na query (exemplo para maior que 5 denúncias):
SELECT CASE WHEN COUNT(*) > 5 THEN 1 ELSE 0 END AS bloquear
FROM tabela
WHERE denunciado = 'userY'

Se precisar disso para vários usuários simultaneamente, use um agrupamento:
SELECT
    denunciado,
    COUNT(*) AS denuncias
FROM tabela
GROUP BY denunciado
HAVING COUNT(*) > 5

Comment: perfeito, ja acoplei dentro de um update e saiu funcionando redondinho :D... Não conhecia a o ´HAVING´ ainda
Comment: a primeira e a terceira query me ajudaram a resolver o problema, a primeira porque com ela eu entendi a logica a terceira pq era a aplicação da logica pronta
Comment: @RodrigoBorth O `HAVING` é uma espécie de `WHERE` sobre colunas agregadas (no caso, o `COUNT(*)`, que é o total de denúncias por denunciado).


Digital Piano Midi Latency Problem

Question: I'm connecting Casio cdp-230r to PC(windows 7) using Ableton 10 and I'm experiencing massive Latency.
Sound driver: ASIO4ALL(I've also tried with audio interface+ASIO).
I know about reducing buffer size. Also, I know midi latency couldn't be 0 seconds. When I choose minimum buffer size, latency is still huge. I've also tried using the digital piano as only midi controller(so that piano doesn't have sound, even when its volume is up). Unfortunately I couldn't find anything on that matter on the internet. Everyone is talking about reducing buffer size. I've also tried changing Midi Clock Sync Delay, Sync Type etc in Ableton in Midi Ports(Link MIDI), still nothing.
So, does anyone have the same problem with Casio cdp series or any digital piano? And can this problem be solved or the specific digital pianos just can't work as midi without annoying latency? P.S. I haven't checked using another DAW, I've only tried using Ableton.
Comment: A MIDI interface's latency is so small that it should not be noticeable; try checking if you get the same latency with something like [VMPK](https://sourceforge.net/projects/vmpk/). I suspect that your problem is with the sound output, i.e., the MIDI synthesizer, or with the audio hardware.
Comment: How are you connecting the keyboard? Are you plugging a USB cable directly from the keyboard to the computer, or are you using MIDI cables to connect the keyboard to a MIDI adapter or interface? What virtual instrument are you using in Live? Do you have any audio effects or MIDI effects loaded in Live?
Comment: ASIO4All is not the most efficient ASIO driver.  What soundcard do you have?  It may have its own ASIO driver available.  For example, Realtek has their own ASIO driver, which is better than ASIO4All, but still behind dedicated low-latency interfaces.
Comment: Try the keyboard in a friend's computer to confirm there isn't a problem with the keyboard or the connecting cable. Next step is to stop programs on your PC that are not involved in making sounds. Stop your mail client, web browser, and reduce the number of programs that show up as little icons in the task bar. Switch off WiFi. Check to see if your virus checker is scanning your computer. If so, pause it while you run the tests. Then see if latency reduces.
Answer: It will be the digital piano. Casio's lower range keyboards are known for it. Even when you buy the best cable there is and connect it to something like an iPad Pro, it still has about an eighth of a second delay.
Comment: Yes, that's my experience too. I have this cheapo 25 keyboard, which has a lot of latency, and in exactly the same setup (same DAW, drivers, vst's etc.) I experience a lot less latency with my more expensive 61 keyboard.
Answer: ASIO4ALL is just a CPU emulation of real ASIO and it's always slower than hardware supported ASIO. So check if your audiocard supports hardware ASIO. If it doesn't - you can either buy a new one or just accept that it can't do it with appropriate latency.
Comment: "CPU emulation" doesn't really describe what ASIO4All does. It implements the ASIO programming interface on top of WASAPI, which itself may be fast or slow depending on the hardware and possible driver. Windows 10 has many improvements to WASAPI over Windows 7, so it's worth it to upgrade.
Comment: @ojs hmm.. didn't know about WASAPI, thanx for hint, it's valueble info for better understanding. But anyway, topicstarter has to get an a/c with h/w ASIO support for lower latency :)

Digital Piano Midi Latency Problem


Wildfly error: [org.jboss.remoting.remote.connection] (XNIO-1 I/O-2) JBREM000200: Remote connection failed

Question: Ao tentar executar um projeto pelo Eclipse Mars utilizando o Wildfly 9 no Windows 10 acontece o seguinte erro:
11:25:08,167 ERROR [org.jboss.remoting.remote.connection] (XNIO-1 I/O-2) JBREM000200: Remote connection failed: java.io.IOException: Uma conexão estabelecida foi anulada pelo software no computador host

A exibição no console:
11:25:05,671 INFO  [org.jboss.modules] (main) JBoss Modules version 1.4.3.Final
11:25:05,914 INFO  [org.jboss.msc] (main) JBoss MSC version 1.2.6.Final
11:25:05,988 INFO  [org.jboss.as] (MSC service thread 1-6) WFLYSRV0049: WildFly Full 9.0.2.Final (WildFly Core 1.0.2.Final) starting
11:25:07,092 INFO  [org.jboss.as.controller.management-deprecated] (ServerService Thread Pool -- 7) WFLYCTL0028: Attribute 'enabled' in the resource at address '/subsystem=datasources/data-source=ExampleDS' is deprecated, and may be removed in future version. See the attribute description in the output of the read-resource-description operation to learn more about the deprecation.
11:25:07,093 INFO  [org.jboss.as.controller.management-deprecated] (ServerService Thread Pool -- 18) WFLYCTL0028: Attribute 'job-repository-type' in the resource at address '/subsystem=batch' is deprecated, and may be removed in future version. See the attribute description in the output of the read-resource-description operation to learn more about the deprecation.
11:25:07,094 INFO  [org.jboss.as.controller.management-deprecated] (ServerService Thread Pool -- 7) WFLYCTL0028: Attribute 'enabled' in the resource at address '/subsystem=datasources/data-source=UmariDS' is deprecated, and may be removed in future version. See the attribute description in the output of the read-resource-description operation to learn more about the deprecation.
11:25:07,094 INFO  [org.jboss.as.controller.management-deprecated] (ServerService Thread Pool -- 7) WFLYCTL0028: Attribute 'enabled' in the resource at address '/subsystem=datasources/data-source=PostgresDS' is deprecated, and may be removed in future version. See the attribute description in the output of the read-resource-description operation to learn more about the deprecation.
11:25:07,109 INFO  [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) WFLYDS0015: Re-attempting failed deployment Umari.war
11:25:07,121 INFO  [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) WFLYDS0004: Found Umari.war in deployment directory. To trigger deployment create a file called Umari.war.dodeploy
11:25:07,140 INFO  [org.jboss.as.server] (Controller Boot Thread) WFLYSRV0039: Creating http management service using socket-binding (management-http)
11:25:07,157 INFO  [org.xnio] (MSC service thread 1-7) XNIO version 3.3.1.Final
11:25:07,164 INFO  [org.xnio.nio] (MSC service thread 1-7) XNIO NIO Implementation Version 3.3.1.Final
11:25:07,208 WARN  [org.jboss.as.txn] (ServerService Thread Pool -- 54) WFLYTX0013: Node identifier property is set to the default value. Please make sure it is unique.
11:25:07,211 INFO  [org.jboss.as.security] (ServerService Thread Pool -- 53) WFLYSEC0002: Activating Security Subsystem
11:25:07,215 INFO  [org.jboss.as.security] (MSC service thread 1-3) WFLYSEC0001: Current PicketBox version=4.9.2.Final
11:25:07,224 INFO  [org.jboss.as.webservices] (ServerService Thread Pool -- 56) WFLYWS0002: Activating WebServices Extension
11:25:07,226 INFO  [org.jboss.as.jsf] (ServerService Thread Pool -- 44) WFLYJSF0007: Activated the following JSF Implementations: [main]
11:25:07,226 INFO  [org.jboss.as.naming] (ServerService Thread Pool -- 46) WFLYNAM0001: Activating Naming Subsystem
11:25:07,229 INFO  [org.jboss.as.clustering.infinispan] (ServerService Thread Pool -- 38) WFLYCLINF0001: Activating Infinispan subsystem.
11:25:07,258 INFO  [org.wildfly.extension.undertow] (ServerService Thread Pool -- 55) WFLYUT0003: Undertow 1.2.9.Final starting
11:25:07,261 INFO  [org.wildfly.extension.undertow] (MSC service thread 1-5) WFLYUT0003: Undertow 1.2.9.Final starting
11:25:07,268 INFO  [org.jboss.as.connector] (MSC service thread 1-4) WFLYJCA0009: Starting JCA Subsystem (IronJacamar 1.2.5.Final)
11:25:07,285 INFO  [org.wildfly.extension.io] (ServerService Thread Pool -- 37) WFLYIO001: Worker 'default' has auto-configured to 8 core threads with 64 task threads based on your 4 available processors
11:25:07,303 INFO  [org.jboss.as.naming] (MSC service thread 1-3) WFLYNAM0003: Starting Naming Service
11:25:07,311 INFO  [org.jboss.as.mail.extension] (MSC service thread 1-1) WFLYMAIL0001: Bound mail session [java:jboss/mail/Default]
11:25:07,404 INFO  [org.jboss.as.connector.subsystems.datasources] (ServerService Thread Pool -- 33) WFLYJCA0004: Deploying JDBC-compliant driver class org.h2.Driver (version 1.3)
11:25:07,409 INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-4) WFLYJCA0018: Started Driver service with driver-name = h2
11:25:07,419 INFO  [org.jboss.remoting] (MSC service thread 1-7) JBoss Remoting version 4.0.9.Final
11:25:07,422 INFO  [org.jboss.as.connector.subsystems.datasources] (ServerService Thread Pool -- 33) WFLYJCA0005: Deploying non-JDBC-compliant driver class org.postgresql.Driver (version 9.4)
11:25:07,424 INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-4) WFLYJCA0018: Started Driver service with driver-name = postgres
11:25:07,435 INFO  [org.jboss.as.connector.subsystems.datasources] (ServerService Thread Pool -- 33) WFLYJCA0005: Deploying non-JDBC-compliant driver class com.mysql.jdbc.Driver (version 5.1)
11:25:07,436 INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-4) WFLYJCA0018: Started Driver service with driver-name = mysql
11:25:07,484 INFO  [org.wildfly.extension.undertow] (ServerService Thread Pool -- 55) WFLYUT0014: Creating file handler for path C:\java_dependencias\wildfly-9.0.2.Final/welcome-content
11:25:07,490 INFO  [org.wildfly.extension.undertow] (MSC service thread 1-3) WFLYUT0012: Started server default-server.
11:25:07,496 INFO  [org.wildfly.extension.undertow] (MSC service thread 1-3) WFLYUT0018: Host default-host starting
11:25:07,584 INFO  [org.wildfly.extension.undertow] (MSC service thread 1-3) WFLYUT0006: Undertow HTTP listener default listening on localhost/127.0.0.1:8080
11:25:07,774 INFO  [org.jboss.as.server.deployment.scanner] (MSC service thread 1-1) WFLYDS0013: Started FileSystemDeploymentService for directory C:\java_dependencias\wildfly-9.0.2.Final\standalone\deployments
11:25:07,775 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-3) WFLYSRV0027: Starting deployment of "Umari.war" (runtime-name: "Umari.war")
11:25:07,841 INFO  [org.jboss.as.connector.subsystems.datasources] (MSC service thread 1-2) WFLYJCA0001: Bound data source [java:/UmariDS]
11:25:07,842 INFO  [org.jboss.as.connector.subsystems.datasources] (MSC service thread 1-2) WFLYJCA0001: Bound data source [java:jboss/datasources/ExampleDS]
11:25:07,841 INFO  [org.jboss.as.connector.subsystems.datasources] (MSC service thread 1-6) WFLYJCA0001: Bound data source [java:/PostgresDS]
11:25:08,078 INFO  [org.jboss.ws.common.management] (MSC service thread 1-7) JBWS022052: Starting JBoss Web Services - Stack CXF Server 5.0.0.Final
11:25:08,167 ERROR [org.jboss.remoting.remote.connection] (XNIO-1 I/O-2) JBREM000200: Remote connection failed: java.io.IOException: Uma conexão estabelecida foi anulada pelo software no computador host
11:25:09,727 ERROR [org.jboss.remoting.remote.connection] (XNIO-1 I/O-2) JBREM000200: Remote connection failed: java.io.IOException: Uma conexão estabelecida foi anulada pelo software no computador host
11:25:11,294 ERROR [org.jboss.remoting.remote.connection] (XNIO-1 I/O-1) JBREM000200: Remote connection failed: java.io.IOException: Uma conexão estabelecida foi anulada pelo software no computador host
11:25:15,752 INFO  [org.jboss.as.jpa] (MSC service thread 1-3) WFLYJPA0002: Read persistence.xml for UmariPU
11:25:16,321 INFO  [org.jboss.as.jpa] (ServerService Thread Pool -- 58) WFLYJPA0010: Starting Persistence Unit (phase 1 of 2) Service 'Umari.war#UmariPU'
11:25:16,334 INFO  [org.hibernate.jpa.internal.util.LogHelper] (ServerService Thread Pool -- 58) HHH000204: Processing PersistenceUnitInfo [
    name: UmariPU
    ...]
11:25:16,388 INFO  [org.hibernate.Version] (ServerService Thread Pool -- 58) HHH000412: Hibernate Core {4.3.10.Final}
11:25:16,390 INFO  [org.hibernate.cfg.Environment] (ServerService Thread Pool -- 58) HHH000206: hibernate.properties not found
11:25:16,391 INFO  [org.hibernate.cfg.Environment] (ServerService Thread Pool -- 58) HHH000021: Bytecode provider name : javassist
11:25:16,493 INFO  [org.jboss.weld.deployer] (MSC service thread 1-3) WFLYWELD0003: Processing weld deployment Umari.war
11:25:16,708 INFO  [org.hibernate.validator.internal.util.Version] (MSC service thread 1-3) HV000001: Hibernate Validator 5.1.3.Final
11:25:16,767 INFO  [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-3) JNDI bindings for session bean named EstabelecimentoBean in deployment unit deployment "Umari.war" are as follows:

    java:global/Umari/EstabelecimentoBean!br.com.umari.ejbs.EstabelecimentoEjb
    java:app/Umari/EstabelecimentoBean!br.com.umari.ejbs.EstabelecimentoEjb
    java:module/EstabelecimentoBean!br.com.umari.ejbs.EstabelecimentoEjb
    java:global/Umari/EstabelecimentoBean
    java:app/Umari/EstabelecimentoBean
    java:module/EstabelecimentoBean

11:25:16,767 INFO  [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-3) JNDI bindings for session bean named EstabelecimentoDAOImpl in deployment unit deployment "Umari.war" are as follows:

    java:global/Umari/EstabelecimentoDAOImpl!br.com.umari.dao.EstabelecimentoDAO
    java:app/Umari/EstabelecimentoDAOImpl!br.com.umari.dao.EstabelecimentoDAO
    java:module/EstabelecimentoDAOImpl!br.com.umari.dao.EstabelecimentoDAO
    java:global/Umari/EstabelecimentoDAOImpl
    java:app/Umari/EstabelecimentoDAOImpl
    java:module/EstabelecimentoDAOImpl

11:25:17,132 INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-7) WFLYJCA0005: Deploying non-JDBC-compliant driver class com.mysql.jdbc.Driver (version 5.1)
11:25:17,133 INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-7) WFLYJCA0005: Deploying non-JDBC-compliant driver class com.mysql.fabric.jdbc.FabricMySQLDriver (version 5.1)
11:25:17,134 INFO  [org.jboss.weld.deployer] (MSC service thread 1-7) WFLYWELD0006: Starting Services for CDI deployment: Umari.war
11:25:17,159 INFO  [org.jboss.weld.Version] (MSC service thread 1-7) WELD-000900: 2.2.16 (SP1)
11:25:17,188 INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-5) WFLYJCA0018: Started Driver service with driver-name = Umari.war_com.mysql.fabric.jdbc.FabricMySQLDriver_5_1
11:25:17,189 INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-7) WFLYJCA0018: Started Driver service with driver-name = Umari.war_com.mysql.jdbc.Driver_5_1
11:25:17,191 INFO  [org.jboss.weld.deployer] (MSC service thread 1-3) WFLYWELD0009: Starting weld service for deployment Umari.war
11:25:17,323 INFO  [org.jboss.as.jpa] (ServerService Thread Pool -- 58) WFLYJPA0010: Starting Persistence Unit (phase 2 of 2) Service 'Umari.war#UmariPU'
11:25:17,382 INFO  [org.hibernate.annotations.common.Version] (ServerService Thread Pool -- 58) HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
11:25:18,452 INFO  [org.hibernate.dialect.Dialect] (ServerService Thread Pool -- 58) HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
11:25:18,523 INFO  [org.hibernate.engine.jdbc.internal.LobCreatorBuilder] (ServerService Thread Pool -- 58) HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
11:25:19,548 INFO  [org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory] (ServerService Thread Pool -- 58) HHH000397: Using ASTQueryTranslatorFactory
11:25:22,870 INFO  [org.hibernate.tool.hbm2ddl.SchemaUpdate] (ServerService Thread Pool -- 58) HHH000228: Running hbm2ddl schema update
11:25:22,870 INFO  [org.hibernate.tool.hbm2ddl.SchemaUpdate] (ServerService Thread Pool -- 58) HHH000102: Fetching database metadata
11:25:22,882 INFO  [org.hibernate.tool.hbm2ddl.SchemaUpdate] (ServerService Thread Pool -- 58) HHH000396: Updating schema
11:25:22,965 INFO  [java.sql.DatabaseMetaData] (ServerService Thread Pool -- 58) HHH000262: Table not found: Estabelecimento
11:25:22,971 INFO  [java.sql.DatabaseMetaData] (ServerService Thread Pool -- 58) HHH000262: Table not found: Estabelecimento
11:25:22,976 INFO  [java.sql.DatabaseMetaData] (ServerService Thread Pool -- 58) HHH000262: Table not found: Estabelecimento
11:25:25,738 INFO  [org.hibernate.tool.hbm2ddl.SchemaUpdate] (ServerService Thread Pool -- 58) HHH000232: Schema update complete
11:25:33,859 INFO  [javax.enterprise.resource.webcontainer.jsf.config] (ServerService Thread Pool -- 62) Inicializando Mojarra 2.2.12-jbossorg-2 20150729-1131 para o contexto '/Umari'
11:25:42,937 INFO  [org.primefaces.webapp.PostConstructApplicationEventListener] (ServerService Thread Pool -- 62) Running on PrimeFaces 5.3
11:25:43,015 INFO  [org.wildfly.extension.undertow] (ServerService Thread Pool -- 62) WFLYUT0021: Registered web context: /Umari
11:25:43,055 INFO  [org.jboss.as.server] (ServerService Thread Pool -- 34) WFLYSRV0010: Deployed "Umari.war" (runtime-name : "Umari.war")
11:25:43,508 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0060: Http management interface listening on http://127.0.0.1:9990/management
11:25:43,509 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0051: Admin console listening on http://127.0.0.1:9990
11:25:43,509 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0025: WildFly Full 9.0.2.Final (WildFly Core 1.0.2.Final) started in 38120ms - Started 364 of 536 services (221 services are lazy, passive or on-demand)

Comment: Uma instância do Wildfly já não esta rodando na máquina?
Comment: Não. Mas o wildfly funciona normalmente. Só a aplicação que não.
Comment: Tem firewall ativo? quando instalou o servidor por acaso você colocou ele em arquivos de programas? pode postar o standalone.xml?
Answer: Achei uma referencia. Como workaround, você deve iniciar o JBoss com -Djboss.remoting.pooled-buffers=false. Mesmo assim, é interessante ler a issue para entender o que acontece.
Outra referência diz que é problema relacionado ao Windows.
Comment: Achei o esse poste, mas não entendi muito bem como faz para mudar a porta.
https://developer.jboss.org/thread/201728?tstart=0
Comment: Eu até ia te sugerir isso, mas vi que a mensagem era diferente. Para mudar a porta do management, você pode passar via linha de comando ou mudar no standalone. Via linha de comando: `$ ./standalone.sh -Djboss.managment.http.port=8990 -Djboss.managment.https.port=8443 -Djboss.managment.native.port=8999`.
Answer: Dai Victor, blza ?
Vou compartilhar o que passei, veja se te ajuda. Se não fica como dica :-D
Isso acontecia comigo também e comigo foi a seguinte situação. Eu tinhas algumas conexões (java.sql.Connection) que eu pegava do gecenciamento de conexões do servidor {DataSource} e gerenciava essas conexões no braço como por exemplo :
Context context = new InitialContext();
Context lautx = (Context) context.lookup("java:");
DataSource ds = (DataSource)lautx.lookup("jboss/punit");
connection = ds.getConnection();

O que eu nao estava fazendo era fechar as conexões. Por esse motivo o servidor as fechava para mim. Fui atraz dessas conexões e fechei ela no braço:
 resultSet.close();
 statement.close();
 connection.close();

e nao aconteceu mais esses erros.
Não sei se em seus códigos vc tem casos como o meu, de ter que abrir conexões assim, para mim resolveu. Boa sorte


Creating a custom url when navigating to a custom module form

Question: I have created a custom module which can be visited via the address
http://myhost.me/my_module/form where it will show my created form. Is there a way wherein instead of using http://myhost.me/my_module/form I can navigate to http://myhost.me/mynewmoduleurl without breaking anything? I'm currently using Drupal 6. Please help. Thanks.
Answer: There are multiple ways.

You could use hook_menu() to declare a new path with the same callback (while still leaving the old one intact).
You could use Redirect module.
You could create a .htaccess redirect. (A 301 redirect is the proper way to do it if you want the new one to permanently replace the old one.)
You could create a new Path Alias.
Comment: I'm quite new to Drupal, can you please show me how it's done? I edited my module function to something like this, `function my_module_menu() {
  $items = array();
  $items['time'] = array(
    'title' => t('My form'),
    'page callback' => 'my_module_form',
    'access arguments' => array('access content'),
    'description' => t('My form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}` but when I navigate http://myhost.me/time it says page cannot be displayed.
Comment: never mind my previous comment, I already solved it using Pathauto module. Thanks man.
Comment: Your problem could have been if you didn't clear caches after changing the `hook_menu()` function.


Get text when enter is pressed in a text box in wxPython

Question: I have a (single line) TextCtrl. The user types data into this. When they press enter, the contents of the box need to be extracted so they can be processed. I can't figure out how to catch enter being pressed.
According to the docs, with the style wx.TE_PROCESS_ENTER set on my TextCtrl, it should generate a wx.EVT_COMMAND_TEXT_ENTER event when enter is pressed in the box, which I could then catch. However, wx.EVT_COMMAND_TEXT_ENTER seems not to exist (I get "module has no attribute EVT_COMMAND_TEXT_ENTER), so I'm a bit stuck. Googling just gets a couple of hits of people complaining wx.EVT_COMMAND_TEXT_ENTER doesn't work, so I guess I need another way of doing it.
Answer: Use style = wx.TE_PROCESS_ENTER in TextCtrl and Bind with Event wx.EVT_TEXT_ENTER
self.Text_Enter = wx.TextCtrl(self , 2 ,style = wx.TE_PROCESS_ENTER, size =(125,150), pos = (170,0))

self.Text_Enter.SetForegroundColour(wx.RED)

self.Bind(wx.EVT_TEXT_ENTER, self.Txt_Ent, id = 2)
def Txt_Ent(self,event):
   msg1 = (str(self.Text_Enter.GetValue()))
   wx.MessageBox(msg1)

Answer: I've never seen wx.EVT_COMMAND_TEXT_ENTER. I have used wx.EVT_TEXT_ENTER though...
Comment: Ah, yes, this is the event that's generated. I guess this is a difference between wxPython and the C++ version, then. EVT_COMMAND_TEXT_ENTER is mentioned here: http://docs.wxwidgets.org/stable/wx_wxtextctrl.html


Jquery hide unselected rows in a table that has been loaded in from a url.

Question: The important HTML

     <input type="text" id="q" class="form-control" placeholder="Search for User">

                  <button class="btn btn-default" id="user_search" type="button"></button>

The User result Html that is loaded

        First Name
        Last Name
        Email

        first_name1
        last_name1
        email1
        1

        first_name2
        last_name2
        email2
        2

The jQuery code


Module development - integrating custom content types

Question: I want to create a module which would need custom content types from the cck module. I know in the .info I can say a dependency is the cck module.
How can I best have the module create the content type? I want this to be easily distributed rather than when I put it on a website I have to also create the content type using cck.
Answer: One way is to create an export of a CCK content type to use in the module. For an example of this method see How to create a CCK content type and fields from a module.
Another exported CCK example
Comment: Features can be of great help as well setting up fields and configuration.


Integration Test Data Set Up in Spring Boot

Question: Here is my test class
    @SpringBootTest
    @ActiveProfiles("test")
    public MyTest {

       ...

       @Before
       public void init() {
          System.out.println(":::: --- start init() ---");
          ...
        }
       ...
    }

Strange enough, the init() won't run for some reason. If I change the @Before to @BeforeAll and the method to static, the init() will run. A problem is that those data set up code doesn't run inside a static method and I can't change all of them to run inside a static block. For now, I have the following code in each test method to overcome the issue
    if(list.size() == 0)
       init();

I am wondering why the @Before won't run. Any advice?
Answer: In JUnit 5, @BeforeEach and @BeforeAll annotations are the equivalents for @Before and @BeforeClass in JUnit 4.
@Before is a JUnit 4 annotation, while @BeforeAll is a JUnit 5 annotation. You can also see this from the imports org.junit.Before and org.junit.jupiter.api.BeforeAll.
Also, the code marked @BeforeEach is executed before each test, while @BeforeAll runs once before the entire test fixture.
To be able to run @BeforeAll on a non-static method you can change the lifecycle of the the test instance with:
@TestInstance(TestInstance.Lifecycle.PER_CLASS)

You have to be careful though, since the test class instance is now only created once, and not once per test method. If your test methods rely on state stored in instance variables, you may now need to manually reset the state in @BeforeEach or @AfterEach lifecycle methods.
Comment: Thanks for the information. It seems that Spring 2.4.M comes with both JUnit 4 and JUnit 5. For this case, I only need to set up data once for entire test fixture. As @BeforeAll with a static method, I need to figure out how to involk non-static method.
Comment: If you want to run it once without a static method, you can change the test instance lifecycle with @TestInstance(TestInstance.Lifecycle.PER_CLASS). You have to be careful with your state management though, since now it won't re-create the test class per method. I will alter my answer to include this information.
Comment: Thanks for the additional information. I am wondering why the annotation requests a static method. To work around the restriction, I am thinking of creating an inter class with a method to wrap around data initialization.
Comment: Check out the JUnit 5 documentation about test lifecycle, it's what they recommend: https://junit.org/junit5/docs/current/user-guide/#writing-tests-test-instance-lifecycle
Comment: Thanks for your additional information again. The data setup portion of my test is for populating test data for read only usage. So, there isn't a state issue for those test.


Derive minimizer of logistic loss

Question: The logistic loss is given by: $l(y, z) = \log(1+\exp(-y\,z))$. Show that the optimal classifier for the logistic loss is given by: $\phi(x) = \log(\eta(x)) - \log(1-\eta(x))$. More formally, for a random variable $Y \in \{-1, 1\}$, show that the following expression is minimized by $\phi$:
$$\min_{f}\mathbb E [l(Y, f(X)]$$
Where the minimization is done over all measurable functions from the domain of $X$ to $\mathbb R$.
What I've tried
It's straightforward to break this down by considering the conditional expectation and applying the tower property of expectation, but the next step (the minimization over all measurable functions) is where I'm having trouble. It seems to require some calculus of variations.
Answer: This doesnt need calculus of variations. Write the loss, pointwise conditional on $X$:
$$\eta(x)l(c) + (1-\eta(x))l(-c)$$
Now minimize this expression with respect to the pointwise prediction $c$. This gives the desired expression for the bayes classifier.

Derive minimizer of logistic loss


How to record accelerometer readings in a persistent storage file on a windows phone

Question: ``I am trying to develop a Windows phone application which can record accelerometer readings after every 10 secs or so to a persistent file storage area.
For that, I have written a program code which gets the accelerometer readings and displays them seperately( one textblock for x reading, one for y reading and one for z reading). Then I store all these readings together in a Textbox and use the TextChanged event to record the changes to the file. The readings are stored to an Isolated File storage area.
The different functions are working fine but the problem I am facing is that the file is showing only the last value of acccelerometer read or in other words, the textbox is saving only the last value read.
Can anyone suggest why is this happenning and what can I do to solve this?
The code I used is as follows:
<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Devices.Sensors;
using Microsoft.Xna.Framework;
using System.Windows.Threading;
using System.IO.IsolatedStorage;
using System.IO;

namespace PhoneApp1
{
    public partial class MainPage : PhoneApplicationPage
    {
        Accelerometer a;
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            if (!Accelerometer.IsSupported)
            {
                status.Text = "Sensor not supported";
                start.IsEnabled = false;
                stop.IsEnabled = false;
            }
            }

        private void start_Click(object sender, RoutedEventArgs e)
        {
            if (a == null)
            {
                a = new Accelerometer();

            }
            try
            {
                status.Text = "Starting Accelerometer";
                a.TimeBetweenUpdates = TimeSpan.FromMilliseconds(1000);
                a.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<AccelerometerReading>>(a_CurrentValueChanged);
                a.Start();
            }
            catch (Exception e1)
            {
                status.Text = e1.Message;
            }
        }

        private void stop_Click(object sender, RoutedEventArgs e)
        {
            if (a != null)
            {
                a.Stop();
                status.Text = "Accelerometer stopped";
            }
            else
            {
                status.Text = "Accelerometer not started";
            }
        }
        void a_CurrentValueChanged(Object sender, SensorReadingEventArgs<AccelerometerReading> sr)
        {
            Dispatcher.BeginInvoke(() => UpdateUI(sr.SensorReading));
        }
        void UpdateUI(AccelerometerReading ar)
        {
            DispatcherTimer newTimer = new DispatcherTimer();
            newTimer.Interval = TimeSpan.FromSeconds(1);
            status.Text = "Getting Accelerometer Readings";
            Vector3 xyz = ar.Acceleration;
            values.Text = "X: " + xyz.X.ToString("0.00") + "\t" + "Y: " + xyz.Y.ToString("0.00") + "\t" + "Z: " + xyz.Z.ToString("0.00");
            newTimer.Tick += OnTimerTick;
            newTimer.Start();

        }
        void OnTimerTick(Object sender, EventArgs args)
        {
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
            isoStore.CreateDirectory("Accelerometer");
            IsolatedStorageFileStream fileStream=isoStore.OpenFile("Accelerometer\\myFile.txt",FileMode.Append,FileAccess.Write);
            using(StreamWriter writeFile=new StreamWriter(fileStream))
            {
            writeFile.WriteLine(values.Text);
            writeFile.Close();
            }
        }

        private void read_Click(object sender, RoutedEventArgs e)
        {
            IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
            IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("Accelerometer\\myFile.txt", FileMode.Open, FileAccess.Read);
            fileStream.Position = 0;
            using (StreamReader reader = new StreamReader(fileStream))
            {
                values.Text += "\n" + reader.ReadToEnd();
            }
        }
    }
</code>
Answer: I copy-pasted your code and it works fine for me.
Try resizing the values textblock and setting the textwrapping property to wrap, maybe that is the reason you dont see them
Also I wouldnt use a new Dispatchertimer object every time, initalizing, and starting, you could have just one for the whole app
hope that helps you!
Comment: The code is working fine but the values that are read are not correct. Either it shows the last value recorded multiple times or simply shows the first value.
Comment: Problem solved. I was not using the Isolated storage properly.


How to access the nth line of a multiline variable in python

Question: Given a multiple line variables
var="""this is line 1
this is line 2
this is line 3
this is line 4"""

How can I assign to a variable a specific line, say line 2?
Comment: Possible duplicate of [How do I split a multi-line string into multiple lines?](https://stackoverflow.com/questions/172439/how-do-i-split-a-multi-line-string-into-multiple-lines)
Answer: >>> var="""this is line 1
... this is line 2
... this is line 3
... this is line 4"""
>>>
>>> line3 = var.splitlines()[3 - 1]
>>> line3
'this is line 3'

str.splitlines splits your multiline-string into distinct lines. line n will be at index n - 1.
Answer: you can try to split with "\n" char like that
>>> a = """this is line1
... this is line2
... this is line3"""
>>> a
'this is line1\nthis is line2\nthis is line3'
>>> a.split("\n")[1]
'this is line2'

Answer: You will have n-1 new line character between n lines. Suppose you have 3 lines so you have 2 new line characters.
multiple_lines ="""this is line 1
... this is line 2
... this is line 3
... this is line 4"""
ans=multiple_lines.split("\n")[m-1]

suppose you want to take the mth string from that multiple strings.  m-1 because indexing starts from 0, so you if you want to access the 3rd element you will have to do ans[2]