问:
C++ Partial Template Specialization: Member Functions
I have a template

```<code>template <int a, int b>
class MyTemplateClass
{
    // ....
    void computeSomething();
};
</code>```

which i would like to partially specialize for two special cases of b:

```<code>template<int a>
void MyTemplateClass<a, 2> :: computeSomething()
{
    // Special case for b=2 here
}

template<int a>
void MyTemplateClass<a, 3> :: computeSomething()
{
    // Special case for b=3 here
}
</code>```

However, as far as i know, partial specialization is invalid for member functions. How can i achieve what i want? Is there any other solution? Thank you!

答:
One approach is to extract the computation from this class into a separate one.

Then you can specialise only that computation class:

```<code>template <int a, int b>
class MyTemplateClass
{
    // ....
    void computeSomething() {
        Computation<a, b> c;
        c.compute();
    }
};
template <int a, int b>
struct Computation { void compute () {} };
template <int a>
struct Computation<a, 2> { void compute () {} };
template <int a>
struct Computation<a, 3> { void compute () {} };
</code>```

Though IMO it's better to not use specialisation, but instead different (descriptive!) names and a compile time conditional to choose between them:

```<code>template<bool Condition,
         typename Then,
         typename Else>
using if_t = typename std:: conditional<
    Condition, Then, Else>:: type;

template <int a, int b>
class MyTemplateClass
{
    // ....
    using Computation =
        if_t<b == 2,
             B2Comp<a>,
             if_t<b == 3,
                  B3Comp<a>,
                  DefaultComp<a, b> > >;
    void computeSomething() {
        Computation c;
        c.compute();
    }
};
// Add  (template) classes, B3Comp and DefaultComp
</code>```

If you can already try C++17, then above can be rewritten to:

```<code>template <int a, int b>
class MyTemplateClass
{
    // ....
    void computeSomething() {
        if constexpr (b == 2) {
            B2Comp<a> comp;
            comp.compute();
        } else if constexpr (b == 3) {
            B3Comp<a> comp;
            comp.compute();
        } else {
            DefaultComp<a, b> comp;
            comp.compute();
            // Or just put the code here, if it's short
        }
    }
};
</code>```

Instead of template classes you could also use template functions.

In contrast to using a normal if this avoids evaluation of the "unneeded" code paths, thus making it possible to place otherwise ill-formed code there (like a recursive instantiation of the same template).

Body:
I have a template

template <int a, int b>
class MyTemplateClass
{
    // ....
    void computeSomething();
};

which i would like to partially specialize for two special cases of b:

template<int a>
void MyTemplateClass :: computeSomething()
{
    // Special case for b=2 here
}

template<int a>
void MyTemplateClass :: computeSomething()
{
    // Special case for b=3 here
}

However, as far as i know, partial specialization is invalid for member functions. How can i achieve what i want? Is there any other solution? Thank you!

Body:
One approach is to extract the computation from this class into a separate one.

Then you can specialise only that computation class:

template <int a, int b>
class MyTemplateClass
{
    // ....
    void computeSomething() {
        Computation<a, b> c;
        c.compute();
    }
};
template <int a, int b>
struct Computation { void compute () {} };
template <int a>
struct Computation<a, 2> { void compute () {} };
template <int a>
struct Computation<a, 3> { void compute () {} };

Though IMO it's better to not use specialisation, but instead different (descriptive!) names and a compile time conditional to choose between them:

template<bool Condition,
         typename Then,
         typename Else>
using if_t = typename std:: conditional<
    Condition, Then, Else>:: type;

template <int a, int b>
class MyTemplateClass
{
    // ....
    using Computation =
        if_t<b == 2,
             B2Comp<a>,
             if_t<b == 3,
                  B3Comp<a>,
                  DefaultComp<a, b> > >;
    void computeSomething() {
        Computation c;
        c.compute();
    }
};
// Add  (template) classes, B3Comp and DefaultComp

If you can already try C++17, then above can be rewritten to:

template <int a, int b>
class MyTemplateClass
{
    // ....
    void computeSomething() {
        if constexpr (b == 2) {
            B2Comp<a> comp;
            comp.compute();
        } else if constexpr (b == 3) {
            B3Comp<a> comp;
            comp.compute();
        } else {
            DefaultComp<a, b> comp;
            comp.compute();
            // Or just put the code here, if it's short
        }
    }
};

Instead of template classes you could also use template functions.

In contrast to using a normal if this avoids evaluation of the "unneeded" code paths, thus making it possible to place otherwise ill-formed code there (like a recursive instantiation of the same template).


来源: stackexchange

问:
How to handle shared data between the controller and the view in ASP.NET MVC?
We have a model (say, List<string>). The function that builds the list is non-deterministic and the output is needed to be referenced in both controller and the view during the lifetime of the request. Since it's per-request, it cannot be static or singleton.

It's a common structure and it can be referenced from any view or controller.

Since we can't access controller from the view (by principle, and we agree), we cannot keep it in the controller. We're currently keeping it in the ViewData dictionary and initialize it in the controller, or the view (if the controller didn't need it).

We think that using ViewData for this purpose may not be ideal since it's not created to be consumed by a controller in the first place. Is there a better way to share common per-request data between Controller and the View? If not we'll stick with ViewData.

There is HttpContext.Items dictionary but I'm not sure if it fits to this purpose.

答:
Controller action should always be called be first. If you have multiple controllers calling the same view/partial view then you should be refactoring the code to one method and call that.

ViewData is the solution to do this, if your really wanting "once access" type information then maybe TempData but ViewData is designed for this.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
my jquery tabs are not working after load
My default jquery tabs are not working after load, what can i do?</p>

```<code>$('#tabs').tabs();
$('#a').tabs();

var section = $("#header a");
section.on('click', function() {
    $('#load').load(this.id + ' #load');
    window.history.pushState(this.id, this.id, this.id);

    if (this.id == '/p/sign-out') {
        window.location.assign("/p");
    }
});
</code>```

答:
```<code>var section = $("#header a");
section.click(function(){
    $('#load').load(this.id + ' #load', function() {
        $('.tabs').tabs();
    });
    window.history.pushState(this.id, this.id, this.id);
    if (this.id == '/p/sign-out') {
        window.location.assign("/p/sign-out");
    }
});
</code>```

Body:
My default jquery tabs are not working after load, what can i do?

$('#tabs').tabs();
$('#a').tabs();

var section = $("#header a");
section.on('click', function() {
    $('#load').load(this.id + ' #load');
    window.history.pushState(this.id, this.id, this.id);

    if (this.id == '/p/sign-out') {
        window.location.assign("/p");
    }
});


问:
Uno choice plugin in jenkins doesn't existe any more?
I'm trying to build a job but i have this error:

Processing DSL script jenkinsFile Warning: (jenkinsFile, line 128)   activeChoiceParam is deprecated Warning: (jenkinsFile, line 128)    version 1.2 or later of plugin 'uno-choice' needs to be installed    Warning: (jenkinsFile, line 136) activeChoiceReactiveParam is    deprecated Warning: (jenkinsFile, line 136) version 1.2 or later of  plugin 'uno-choice' needs to be installed Warning: (jenkinsFile, line    145) activeChoiceReactiveParam is deprecated Warning: (jenkinsFile,    line 145) version 1.2 or later of plugin 'uno-choice' needs to be    installed Warning: (jenkinsFile, line 128) activeChoiceParam is    deprecated Warning: (jenkinsFile, line 128) version 1.2 or later of    plugin 'uno-choice' needs to be installed Warning: (jenkinsFile, line    136) activeChoiceReactiveParam is deprecated Warning: (jenkinsFile,    line 136) version 1.2 or later of plugin 'uno-choice' needs to be    installed Warning: (jenkinsFile, line 145) activeChoiceReactiveParam is deprecated

i searched in plugins but i can't find uno choice plugin !!
it worked before, i just face this error today !!

答:
Yes, the Active Choices Plugin was pulled out of the update center for security reasons.

The answer at Jenkins :: Dynamic String Parameter describes how to install it anyway if you hate security.


问:
Replacing values within a column using if not condition
I have  following data farme,

```<code>head(df)
    Sample type
    AA01   ph
    AA02   RH
    AA03   CH
    AA04   TCH
</code>```

and I need to replace the values in column type if the value is not equal to ph to others.
And so I tried as following,

```<code>df$type[which(df$type != "ph")] = "others"
</code>```

But its throwing warning as,

```<code>Warning message:
In `[<-.factor`(`*tmp*`, which(df$type != "ph"), value = c(NA,  :
  invalid factor level, NA generated
</code>```

Any solutions or suggestions would be great

答:
Try this:</p>

```<code>Sample = c("AA01", "AA02", "AA03", "AA04")
type = c("ph", "RH", "CH", "TCH")

df = as.data.frame(cbind(Sample, type))
df$type = as.character(df$type)
df$type = ifelse(df$type == "ph", "others", df$type)
df
</code>```

Body:
I have  following data farme,

head(df)
    Sample type
    AA01   ph
    AA02   RH
    AA03   CH
    AA04   TCH

and I need to replace the values in column type if the value is not equal to ph to others.
And so I tried as following,

df$type[which(df$type != "ph")] = "others"

But its throwing warning as,

Warning message:
In `[<-.factor`(`*tmp*`, which(df$type != "ph"), value = c(NA,  :
  invalid factor level, NA generated

Any solutions or suggestions would be great

Body:
Try this:

Sample = c("AA01", "AA02", "AA03", "AA04")
type = c("ph", "RH", "CH", "TCH")

df = as.data.frame(cbind(Sample, type))
df$type = as.character(df$type)
df$type = ifelse(df$type == "ph", "others", df$type)
df


问:
Many to many query MySQL
I have two tables: users [id, email] and roles [id, name] with many-to-many connection table user_has_roles [user_id, role_id].
I'm trying to get table which showing which user has particular role and if not then null (or 0) similar to following:

```<code>            | role 1 | role 2 | role 3
---------------------------------------
user1@email | 1      | null   | 1
user2@email | null   | null   | 1
---------------------------------------
</code>```

Much appreciate any help on this.

答:
```<code>select u.email,
       case when sum(r.name = 'role 1') > 0 then 1 else null end as `role 1`,
       case when sum(r.name = 'role 2') > 0 then 1 else null end as `role 2`,
       case when sum(r.name = 'role 3') > 0 then 1 else null end as `role 3`
from users u
left join user_has_roles ur on ur.user_id = u.id
left join roles r on ur.role_id = r.id
group by u.email
</code>```

Title: Many to many query MySQL

Body:
I have two tables: users [id, email] and roles [id, name] with many-to-many connection table user_has_roles [user_id, role_id].
I'm trying to get table which showing which user has particular role and if not then null (or 0) similar to following:

            | role 1 | role 2 | role 3
---------------------------------------
user1@email | 1      | null   | 1
user2@email | null   | null   | 1
---------------------------------------

Much appreciate any help on this.


问:
Deep Neural Networks vs. Big Data Analytics
I'm a prospective PhD (CS) student. I've worked in the area of Anomaly Detection during my MS Research. Now, I've got two major and recently emerging areas to choose, i.e., Deep Neural Networks and Big Data Analytics. However, I've to chose one as my future area to work on.

I want to relate one of these fields to my previous work that was about Anomaly Detection. Moreover, I've to ask two questions here:

Deep Neural Networks vs. Big Data Analytics, which is more
relevant to Anomaly Detection?

Deep Neural Networks vs. Big Data
    Analytics, which has more scope in future?

答:
The question is hard to answer, because

(1) Deep Neural Networks may be/become a feasible tool in Big Data Analytics, of which anomaly detection -AFAIK- is a part.

(2) Both, big data and NN will have their scope in the future.

in the end it's a question of taste. From my limited understanding, Big Data Analytics would be the broader subject, as it might comprise NN. On the other side NN is as subject, whose relevance goes far beyond Big Data Analytics, as it is the core technology to all kind of contemporary and future AI (artificial intelligence).

By the way there are different kind of NN models and approaches. Assert you will learn about all of them. Multi layered feed forward (the classic ones), Hopfield networks, Kohonen networks and so on ...

From my very personal view I would decide for neural networks, but you should not let yourself influence by that.


问:
How to bind a combo box to a collection asynchronously where the objects gets updated WPF
I have created a WPF binding it was working fine but then I realised I needed a refresh button show when I call the SetUpData function I am getting this error:

Additional information: This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.

C#:

```<code>public async void GetShows(string serviceDocUri)
{

    await Task.Run(() => _Shows = new ObservableCollection<Show>());

    await Task.Run(() => GetAllShowsWithPath("", directoryShowDoc)); //Error shows on this line
}
</code>```

More C#:

```<code>public MainWindow()
{
    InitializeComponent();
    this.DataContext = Workspace.This;

    //Awaits the list of shows
    SetUpData();
}
</code>```

More C#:

```<code>private async void SetUpData()
{
    await Task.Run(() => _VizManager.GetShows(_TrioLocalHost));

    //This is binded to my WPF combobox
    Workspace.This.TrioShow = _VManager._Shows;

}
</code>```

More C#:

```<code>private async Task GetAllShowsWithPath(string directoryPath, XmlDocument xmlDoc)
{
    string siteRoot = "http://";
    foreach (XmlNode showNode in xmlDoc.SelectNodes("//atom:feed/atom:entry[atom:category/@term='show']/atom:title", nameSpaceManager_))
    {
        _Shows.Add(new Show { Title = "showTitle", ShowLink = "showLink", FullPath = "fullPath" });
    }

    foreach (XmlNode dirNode in xmlDoc.SelectNodes("//atom:feed/atom:entry[atom:category/@term='directory' and not(atom:category/@term='show')]/atom:title", nameSpaceManager_))
    {
        string dir = dirNode.InnerText;
        XmlDocument xmlDoc1 = new XmlDocument();
        string directoryPath1 = directoryPath + "/" + dir;
        string xml = "";
        string page = siteRoot + "/directory/shows" + directoryPath1 + "/";
        using (HttpClient client = new HttpClient())
        using (HttpResponseMessage response = await client.GetAsync(page))
        {
            response.Headers.Add("Accepts", "application/atomsvc+xml");
            using (HttpContent content = response.Content)
            {
                string data = await content.ReadAsStringAsync();
                if (data != null)
                {
                    xml = data;
                }
            }
        }
        xmlDoc1.LoadXml(xml);
        await this.GetAllShowsWithPath(directoryPath1, xmlDoc1);
    }
}
</code>```

答:
Actually, you are trying to access an UI element from another thread probably here:

```<code>//..Function body
//Recurring function
</code>```

UI element created on a thread is accessible only to that thread, and
  is not available to other threads

Take a look at Dispatcher

[Edit]:

```<code>public async Task GetShows(string serviceDocUri)
{
    _Shows = new ObservableCollection<Show>();
    await Task.Run(
        () =>
            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,
                new Action(() => GetAllShowsWithPath("", directoryShowDoc))));
}

private async Task SetUpData()
{
    await _VizManager.GetShows(_TrioLocalHost);

    //This is binded to my WPF combobox
    Workspace.This.TrioShow = _VManager._Shows;
}
</code>```

Body:
I have created a WPF binding it was working fine but then I realised I needed a refresh button show when I call the SetUpData function I am getting this error:

Additional information: This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.

C#:

public async void GetShows(string serviceDocUri)
{

    await Task.Run(() => _Shows = new ObservableCollection<Show>());

    await Task.Run(() => GetAllShowsWithPath("", directoryShowDoc)); //Error shows on this line
}

More C#:

public MainWindow()
{
    InitializeComponent();
    this.DataContext = Workspace.This;

    //Awaits the list of shows
    SetUpData();
}

More C#:

private async void SetUpData()
{
    await Task.Run(() => _VizManager.GetShows(_TrioLocalHost));

    //This is binded to my WPF combobox
    Workspace.This.TrioShow = _VManager._Shows;

}

More C#:

private async Task GetAllShowsWithPath(string directoryPath, XmlDocument xmlDoc)
{
    string siteRoot = "http://";
    foreach (XmlNode showNode in xmlDoc.SelectNodes("//atom:feed/atom:entry[atom:category/@term='show']/atom:title", nameSpaceManager_))
    {
        _Shows.Add(new Show { Title = "showTitle", ShowLink = "showLink", FullPath = "fullPath" });
    }

    foreach (XmlNode dirNode in xmlDoc.SelectNodes("//atom:feed/atom:entry[atom:category/@term='directory' and not(atom:category/@term='show')]/atom:title", nameSpaceManager_))
    {
        string dir = dirNode.InnerText;
        XmlDocument xmlDoc1 = new XmlDocument();
        string directoryPath1 = directoryPath + "/" + dir;
        string xml = "";
        string page = siteRoot + "/directory/shows" + directoryPath1 + "/";
        using (HttpClient client = new HttpClient())
        using (HttpResponseMessage response = await client.GetAsync(page))
        {
            response.Headers.Add("Accepts", "application/atomsvc+xml");
            using (HttpContent content = response.Content)
            {
                string data = await content.ReadAsStringAsync();
                if (data != null)
                {
                    xml = data;
                }
            }
        }
        xmlDoc1.LoadXml(xml);
        await this.GetAllShowsWithPath(directoryPath1, xmlDoc1);
    }
}

Body:
Actually, you are trying to access an UI element from another thread probably here:

//..Function body
//Recurring function

UI element created on a thread is accessible only to that thread, and
  is not available to other threads

Take a look at Dispatcher

[Edit]:

public async Task GetShows(string serviceDocUri)
{
    _Shows = new ObservableCollection<Show>();
    await Task.Run(
        () =>
            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,
                new Action(() => GetAllShowsWithPath("", directoryShowDoc))));
}

private async Task SetUpData()
{
    await _VizManager.GetShows(_TrioLocalHost);

    //This is binded to my WPF combobox
    Workspace.This.TrioShow = _VManager._Shows;
}


问:
How to check that systemtime on web server is configured OR not?
How do I check that system time is configured OR not correctly on the web host server? I need to check its sync with twitter server time. How do I do that? I checked by running "strftime('%c')" on web server that its time is either -7 hours OR +5 different hours my systemtime.

EDIT

OK, I checked time zone as Piskvor mentioned & Web server has 'UTC/GMT -5 hours' while my system is in 'UTC/GMT +2 hours'. my problem is that I need to sure the clock on the server is properly synced with NTP. How do I do that ?
I am using Windows XP.

答:
```<code>ntpq -p
</code>```

You should see a list of your configured clock sources, with "*" indicating a clock source selected as the source for synchronisation.

Body:
ntpq -p

You should see a list of your configured clock sources, with "*" indicating a clock source selected as the source for synchronisation.


问:
Error message with the function melt
I am new to R and I really need your help. I stumped for days on this matter but no clue. I need to convert a wide data set into the long format. I have 63 observations and 146 variables. That means I will end up with 9072 rows.

The long data set I am trying to get should look like this:

Participant group Item  ratings
1             1     1       2
1             1     2       3
                   144
etc..

Here is the structure of the data set.

```<code>str (age_ratings_wide)
'data.frame':   63 obs. of  146 variables:
 $ participant    : Factor w/ 63 levels "E1","E10","E11",..: 49 50 51 52 53 54 55 56 57 58 ...
 $ group          : Factor w/ 3 levels "1-6","7-13","NS": 3 3 3 3 3 3 3 3 3 3 ...
 $ M1_5_adv_g1    : int  2 4 5 5 4 5 5 5 4 5 ...
 $ M1_17_adv_g2   : int  5 5 5 5 5 5 5 5 5 5 ...

  [list output truncated]
</code>```

The problem is that I first managed to convert it as I want but failed to save. Then it stopped working for me. I use RStudio and reshape2 with melt as a function.Here is my command line:

```<code>age_ratings_long <-melt(age_ratings_wide[c(3:146)],id.vars = c("participant","group"),value.name = "ratings",varaible.name="item")
</code>```

Error: id variables not found in data: participant, group

I continue to get this error message even when I tried to shorten the number of columns I want to stack up.

Kholoud

答:
Try this:

```<code>age_ratings_long = melt(age_ratings_wide,id.vars=c("participant","group"))
</code>```

If this run, I think you have deleted your id.vars with age_ratings_wide[c(3:146)] command.

Title: Error message with the function melt

Body:
I am new to R and I really need your help. I stumped for days on this matter but no clue. I need to convert a wide data set into the long format. I have 63 observations and 146 variables. That means I will end up with 9072 rows.

The long data set I am trying to get should look like this:

Participant group Item  ratings
1             1     1       2
1             1     2       3
                   144
etc..

Here is the structure of the data set.

str (age_ratings_wide)
'data.frame':   63 obs. of  146 variables:
 $ participant    : Factor w/ 63 levels "E1","E10","E11",..: 49 50 51 52 53 54 55 56 57 58 ...
 $ group          : Factor w/ 3 levels "1-6","7-13","NS": 3 3 3 3 3 3 3 3 3 3 ...
 $ M1_5_adv_g1    : int  2 4 5 5 4 5 5 5 4 5 ...
 $ M1_17_adv_g2   : int  5 5 5 5 5 5 5 5 5 5 ...

  [list output truncated]

The problem is that I first managed to convert it as I want but failed to save. Then it stopped working for me. I use RStudio and reshape2 with melt as a function.Here is my command line:

age_ratings_long <-melt(age_ratings_wide[c(3:146)],id.vars = c("participant","group"),value.name = "ratings",varaible.name="item")

Error: id variables not found in data: participant, group

I continue to get this error message even when I tried to shorten the number of columns I want to stack up.

Kholoud

Body:
Try this:

age_ratings_long = melt(age_ratings_wide,id.vars=c("participant","group"))

If this run, I think you have deleted your id.vars with age_ratings_wide[c(3:146)] command.


问:
Plotting FFT fails due to vectors not having the same length
I have a csv data of time(1st column) and current amplitude(2nd column). I want to plot FFT of the current. This is actually simulation data over 30ns and data step was 1ps. I can plot the current vs Time in MATLAB. But while doing FFT function, It is not plotting at all as it says

```<code>Error using plot
Vectors must be the same length.

Error in FFT_Ideal_current_maxstep_1ps (line 25).
plot(f,Y)
</code>```

Can anyone help me? I have attached the MATLAB code and the CSV file as well.

I also want to plot the power spectral density. It would be nice if anyone can help. I want to get the FFT and psd over 2GHz or more frequency spectrum range

MATLAB code1:

```<code>% open data file
fid = fopen('current_maxstep_1ps.csv');

% Read data in from csv file
readData = textscan(fid,'%f %f','Headerlines',1,'Delimiter',',');

% Extract data from readData
t = readData{1,1}(:,1);
x = readData{1,2}(:,1);

N = length(x);
ts = 0.000000000001;
Fs = 1/ts;
tmax = (N-1)*ts;
tm = 0:ts:tmax;
f = 0:Fs/(N-1):Fs/2;
y = fftshift(fft(x));
Y = abs(y);
plot(f,Y)
</code>```

Also there is another MATLAB code I tried which plots (here is the picture: FFT picture of code 2) but showing in time domain and I want frequency spectrum like spikes of apmlitudes along the frequency spectrum.

MATLAB Code2:

```<code>% open data file
fid = fopen('Ideal_current_maxstep_1ps.csv');

% Read data in from csv file
readData = textscan(fid,'%f %f','Headerlines',1,'Delimiter',',');

% Extract data from readData
xData = readData{1,1}(:,1);
yData = readData{1,2}(:,1);

Ts = 1e-12;
Fs = 1/Ts;
%Fs = 1000;
%Ts = 1/Fs;

X = fft(yData);
plot(xData, abs(X))
</code>```

答:
The problem is that the length of f and Y are not the same. You can check it using length(f) and length(Y). The reason is that fft also calculates the negative frequencies. Therefore, you should define f as follows:

```<code>f = -Fs/2:Fs/(N-1):Fs/2;
</code>```

Note that the fft is conjugate symmetric, because the input data is real.

You can limit the plotted frequency range using the xlim command as follows:

```<code>xlim([0 3*10^9]) % limit x range between 0Hz and 3GHz
</code>```

Body:
I have a csv data of time(1st column) and current amplitude(2nd column). I want to plot FFT of the current. This is actually simulation data over 30ns and data step was 1ps. I can plot the current vs Time in MATLAB. But while doing FFT function, It is not plotting at all as it says

Error using plot
Vectors must be the same length.

Error in FFT_Ideal_current_maxstep_1ps (line 25).
plot(f,Y)

Can anyone help me? I have attached the MATLAB code and the CSV file as well.

I also want to plot the power spectral density. It would be nice if anyone can help. I want to get the FFT and psd over 2GHz or more frequency spectrum range

MATLAB code1:

% open data file
fid = fopen('current_maxstep_1ps.csv');

% Read data in from csv file
readData = textscan(fid,'%f %f','Headerlines',1,'Delimiter',',');

% Extract data from readData
t = readData{1,1}(:,1);
x = readData{1,2}(:,1);

N = length(x);
ts = 0.000000000001;
Fs = 1/ts;
tmax = (N-1)*ts;
tm = 0:ts:tmax;
f = 0:Fs/(N-1):Fs/2;
y = fftshift(fft(x));
Y = abs(y);
plot(f,Y)

Also there is another MATLAB code I tried which plots (here is the picture: FFT picture of code 2) but showing in time domain and I want frequency spectrum like spikes of apmlitudes along the frequency spectrum.

MATLAB Code2:

% open data file
fid = fopen('Ideal_current_maxstep_1ps.csv');

% Read data in from csv file
readData = textscan(fid,'%f %f','Headerlines',1,'Delimiter',',');

% Extract data from readData
xData = readData{1,1}(:,1);
yData = readData{1,2}(:,1);

Ts = 1e-12;
Fs = 1/Ts;
%Fs = 1000;
%Ts = 1/Fs;

X = fft(yData);
plot(xData, abs(X))

Body:
The problem is that the length of f and Y are not the same. You can check it using length(f) and length(Y). The reason is that fft also calculates the negative frequencies. Therefore, you should define f as follows:

f = -Fs/2:Fs/(N-1):Fs/2;

Note that the fft is conjugate symmetric, because the input data is real.

You can limit the plotted frequency range using the xlim command as follows:

xlim([0 3*10^9]) % limit x range between 0Hz and 3GHz


问:
I need Propel 1.3.0. From where I can download the same?
I need Propel 1.3.0 for my existing php and mysql versions to create model classes. From where I can download Propel generator 1.3.0?
Your help is appreciated
Thanks</p>

答:
The oldest I could find was 1.7.1
https://github.com/propelorm/Propel

I have a copy of 1.6.7 but that's the oldest I have

Up to 1.7.1 does have a lot of backward compatibility, it was only when they went to Propel 2 that things really started to break.  There were changes at 1.5, but they were relatively minor.


问:
Return List of T where T is one of x classes (where x is greater than zero)
Please see the two classes below:

```<code>public class Person
    {
        int ID;
        string Name;
        string Address;
    }

    public class PersonModel
    {
        int ID;
        string Name;
        string Address;
    }
</code>```

I am trying to create a function that will return a List of PersonModel or a List of Person depending what parameter is passed to the class:

Here is the client side function:

```<code>public static List<T> BuildList<T>()
        {
            //Populate list of T where T is wither a Person or PersonModel.
            //Return List of T
        }
</code>```

Can this be done?

答:
To answer the question in the conditions it has been asked. Yes, it is possible, and you nearly gave the answer yourself. You just need to initialize your list in your function with the template type, and then to fill it the way you need.

```<code>public static List<T> BuildList<T>() where T : new()
{
    List<T> ownList = new List<T>();

    // Populate your list the way you want.

    return ownList;
}
</code>```

To populate your list, you can either create default class objets and add them to your list, like this:

```<code>T myObject = new T();
ownList.Add(myObject);
</code>```

Or if you want to fill your list in a specific way depending on the type of T, you can use typeof.

```<code>if(typeof(T) == typeof(Person))
{
    // Initialize your Person objets in a specific way.
}
</code>```

But I would avoid going for this option. I would either go for a specific declaration of your function for each one of your classes, or to use an interface which would reunite the elements of each one of your classes, make those classes implement this interface, and initialize your objects through your interface. Evk's answer is a good example of such an implementation.

Body:
Please see the two classes below:

public class Person
    {
        int ID;
        string Name;
        string Address;
    }

    public class PersonModel
    {
        int ID;
        string Name;
        string Address;
    }

I am trying to create a function that will return a List of PersonModel or a List of Person depending what parameter is passed to the class:

Here is the client side function:

public static List<T> BuildList<T>()
        {
            //Populate list of T where T is wither a Person or PersonModel.
            //Return List of T
        }

Can this be done?

Body:
To answer the question in the conditions it has been asked. Yes, it is possible, and you nearly gave the answer yourself. You just need to initialize your list in your function with the template type, and then to fill it the way you need.

public static List<T> BuildList<T>() where T : new()
{
    List<T> ownList = new List<T>();

    // Populate your list the way you want.

    return ownList;
}

To populate your list, you can either create default class objets and add them to your list, like this:

T myObject = new T();
ownList.Add(myObject);

Or if you want to fill your list in a specific way depending on the type of T, you can use typeof.

if(typeof(T) == typeof(Person))
{
    // Initialize your Person objets in a specific way.
}

But I would avoid going for this option. I would either go for a specific declaration of your function for each one of your classes, or to use an interface which would reunite the elements of each one of your classes, make those classes implement this interface, and initialize your objects through your interface. Evk's answer is a good example of such an implementation.


问:
React native project won't run on mac
I'm trying to run react native on mac, I run the android emulator in the background and run react-native run-android and I get:

```<code>=> react-native run-android
Scanning 564 folders for symlinks in /Users/sao/Conv/Conv2/node_modules (19ms)
Starting JS server...
Building and installing the app on the device (cd android && ./gradlew installDebug)...
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html
</code>```

The react awesome project (react-native init) works fine on this machine and this project run fine on windows.

It says check error above for details but there's no error above...

Any ideas on how to make it work?

答: try running adb devices in terminal, if its blank run adb kill-server then follow it up with adb start-server

Title: React native project won't run on mac

Body:
I'm trying to run react native on mac, I run the android emulator in the background and run react-native run-android and I get:

=> react-native run-android
Scanning 564 folders for symlinks in /Users/sao/Conv/Conv2/node_modules (19ms)
Starting JS server...
Building and installing the app on the device (cd android && ./gradlew installDebug)...
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html

The react awesome project (react-native init) works fine on this machine and this project run fine on windows.

It says check error above for details but there's no error above...

Any ideas on how to make it work?


问:
Abstract classes/traits and invariant functions
Given a trait T

```<code>trait T {
  def v: Int
  def +(t: T): T
}
</code>```

the following class A

```<code>case class A(v: Int) extends T {
  def +(a: A) = A(v + a.v)
}
</code>```

is not a valid subtype of T. The implementation of A.+ is too restrictive, because it only accepts elements of type A whereas the signature of T.+ requires all implementations to be able to accept objects of type T and not just objects of type A.
So far, so reasonable.

If I'd like to allow implementations of T to be that restrictive I can modify the declarations of T and A as follows

```<code>trait T[This <: T[This]] {
  def v: Int
  def +(t: This): This
}

case class A(v: Int) extends T[A] {
  def +(a: A) = A(v + a.v)
}
</code>```

which obviously blows up the type signature.

Is there another way to declare that implementations of T only need to be compatible with objects of their own type?

1st EDIT In reply to Landei's answer below:

While self-types indeed shorten the current signature they don't shorten other signatures where T occurs, e.g.

```<code>trait C[D <: T[D], S] { self: S =>
  def +(perm: D): S
  def matches(other: S): Boolean
}
</code>```

答:
You can use self-types:</p>

```<code>trait T[S] {
  self:S =>
  def v: Int
  def +(t: S): S
}

case class A(v: Int) extends T[A] {
  def +(a: A) = A(v + a.v)
}
</code>```

Body:
Given a trait T

trait T {
  def v: Int
  def +(t: T): T
}

the following class A

case class A(v: Int) extends T {
  def +(a: A) = A(v + a.v)
}

is not a valid subtype of T. The implementation of A.+ is too restrictive, because it only accepts elements of type A whereas the signature of T.+ requires all implementations to be able to accept objects of type T and not just objects of type A.
So far, so reasonable.

If I'd like to allow implementations of T to be that restrictive I can modify the declarations of T and A as follows

trait T[This <: T[This]] {
  def v: Int
  def +(t: This): This
}

case class A(v: Int) extends T[A] {
  def +(a: A) = A(v + a.v)
}

which obviously blows up the type signature.

Is there another way to declare that implementations of T only need to be compatible with objects of their own type?

1st EDIT In reply to Landei's answer below:

While self-types indeed shorten the current signature they don't shorten other signatures where T occurs, e.g.

trait C[D <: T[D], S] { self: S =>
  def +(perm: D): S
  def matches(other: S): Boolean
}

Body:
You can use self-types:

trait T[S] {
  self:S =>
  def v: Int
  def +(t: S): S
}

case class A(v: Int) extends T[A] {
  def +(a: A) = A(v + a.v)
}


答:
You can introduce an interface which will share common properties of those two classes, then restrict your T parameter to this interface:

```<code>public interface IPerson {
    int ID { get; set; }
    string Name { get; set; }
    string Address { get; set; }
}

public class Person : IPerson {
    public int ID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}

public class PersonModel : IPerson {
    public int ID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}

public static List<T> BuildList<T>() where T : IPerson, new() {
    var result = new List<T>();
    for (int i = 0; i < 10; i++) {
        result.Add(new T() {
            ID = i,
            Address = "address" + i
        });
    }
    return result;
}
</code>```

Title: Return List of T where T is one of x classes (where x is greater than zero)

Body:
You can introduce an interface which will share common properties of those two classes, then restrict your T parameter to this interface:

public interface IPerson {
    int ID { get; set; }
    string Name { get; set; }
    string Address { get; set; }
}

public class Person : IPerson {
    public int ID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}

public class PersonModel : IPerson {
    public int ID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}

public static List<T> BuildList<T>() where T : IPerson, new() {
    var result = new List<T>();
    for (int i = 0; i < 10; i++) {
        result.Add(new T() {
            ID = i,
            Address = "address" + i
        });
    }
    return result;
}


问:
How to keep the aspect ratio of image window in opencv?
From documantation, it says that we can keep the image ratio by CV_WINDOW_KEEPRATIO but the windows still lost aspect ratio after I adjust it. Would anyone kindly help?

Example code:

```<code>import cv2

# load the image, clone it, and setup the mouse callback function
image = cv2.imread('1.jpg')
cv2.namedWindow('image', cv2.WINDOW_KEEPRATIO)
# keep looping until the 'q' key is pressed
while True:
    # display the image and wait for a keypress
    cv2.imshow('image', image)
    key = cv2.waitKey()

    if key == 27:
        break

# close all open windows
cv2.destroyAllWindows()
</code>```

答:
Are you trying to constrain the window or the image? You cannot constrain the window size, only the image size.

Note that in the documentation for namedWindow it says at the bottom

By default, flags == CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO | CV_GUI_EXPANDED

So setting cv2.WINDOW_KEEPRATIO will not affect ratio scaling (as it does not affect ratio by default).

I imagine that what you want to accomplish is to be able to move the window size and have that affect your displayed image size. Is that correct? If so, that is not possible with OpenCV, at least not built-in. Image windows are simply containers to show your image, and thus they will not affect your image at all. You can, of course, adjust your image size prior to display with cv2.resize().

Edit: Okay, so I'm not even sure if the above is what you want, but I said resizing the window is impossible with current OpenCV. In fact, it is kind of possible. You can create a trackbar, which will put a slider on your image. Then when you move the slider, it will call a function that you define with the slider's position as the argument. You could then take that position, convert it to a number between 0 and 1, and then multiply your image size by that number to get a smaller image size. Then you could resize your image by that scale, and redisplay it to your window. I'm pretty sure this is way overkill for what you need, but it was interesting so I decided to try it.

```<code>import cv2

def trackbar_change(pos):
    pos = pos/100 # get a scaling factor from trackbar pos
    image = cv2.imread('image.jpg') # read image
    h = int(image.shape[0]*pos) # scale h
    w = int(image.shape[1]*pos) # scale w
    rsz_image = cv2.resize(image, (w, h)) # resize image
    cv2.resizeWindow('image_window', w, h) # resize window
    cv2.imshow('image_window', rsz_image) # display resized image
    return

image = cv2.imread('image.jpg')
cv2.namedWindow('image_window', cv2.WINDOW_NORMAL)
starting_trackbar_val = 100
quant_trackbar_vals = 100
cv2.createTrackbar('Image scale', 'image_window', \
    starting_trackbar_val, quant_trackbar_vals, trackbar_change)

cv2.imshow('image_window', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Body:
From documantation, it says that we can keep the image ratio by CV_WINDOW_KEEPRATIO but the windows still lost aspect ratio after I adjust it. Would anyone kindly help?

Example code:

import cv2

# load the image, clone it, and setup the mouse callback function
image = cv2.imread('1.jpg')
cv2.namedWindow('image', cv2.WINDOW_KEEPRATIO)
# keep looping until the 'q' key is pressed
while True:
    # display the image and wait for a keypress
    cv2.imshow('image', image)
    key = cv2.waitKey()

    if key == 27:
        break

# close all open windows
cv2.destroyAllWindows()

Body:
Are you trying to constrain the window or the image? You cannot constrain the window size, only the image size.

Note that in the documentation for namedWindow it says at the bottom

By default, flags == CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO | CV_GUI_EXPANDED

So setting cv2.WINDOW_KEEPRATIO will not affect ratio scaling (as it does not affect ratio by default).

I imagine that what you want to accomplish is to be able to move the window size and have that affect your displayed image size. Is that correct? If so, that is not possible with OpenCV, at least not built-in. Image windows are simply containers to show your image, and thus they will not affect your image at all. You can, of course, adjust your image size prior to display with cv2.resize().

Edit: Okay, so I'm not even sure if the above is what you want, but I said resizing the window is impossible with current OpenCV. In fact, it is kind of possible. You can create a trackbar, which will put a slider on your image. Then when you move the slider, it will call a function that you define with the slider's position as the argument. You could then take that position, convert it to a number between 0 and 1, and then multiply your image size by that number to get a smaller image size. Then you could resize your image by that scale, and redisplay it to your window. I'm pretty sure this is way overkill for what you need, but it was interesting so I decided to try it.

import cv2

def trackbar_change(pos):
    pos = pos/100 # get a scaling factor from trackbar pos
    image = cv2.imread('image.jpg') # read image
    h = int(image.shape[0]*pos) # scale h
    w = int(image.shape[1]*pos) # scale w
    rsz_image = cv2.resize(image, (w, h)) # resize image
    cv2.resizeWindow('image_window', w, h) # resize window
    cv2.imshow('image_window', rsz_image) # display resized image
    return

image = cv2.imread('image.jpg')
cv2.namedWindow('image_window', cv2.WINDOW_NORMAL)
starting_trackbar_val = 100
quant_trackbar_vals = 100
cv2.createTrackbar('Image scale', 'image_window', \
    starting_trackbar_val, quant_trackbar_vals, trackbar_change)

cv2.imshow('image_window', image)
cv2.waitKey(0)
cv2.destroyAllWindows()


问:
Binding Angular component with specific type
I'm currently working with Angular and TypeScript and I want to know if it's possible to bind component @Inputs to use specific types?

Example

```<code>@Component({selector: 'foobar'})
export class FooComponent {
    @Input() foo: number;
    @Input() bar: boolean;
}

<foobar foo="123" bar="true"></foobar>
</code>```

When the component is bound, both foo and bar are string. Does angular provide a way to enforce the specified type?

I tried this, but I don't like it...(it seems dirty and not very elegant)

```<code>@Component({selector: 'foobar'})
export class FooComponent {
    foo: number;
    bar: boolean;

    @Input('foo') set _foo(value: string) {
        this.foo = Number(value);
    }

    @Input('bar') set _bar(value: string) {
        this.bar = value === 'true';
    }
}
</code>```

It would be nice if there was something in Angular's Input that could act as a binding delegate; For example:

```<code>@Input('foo', (value: string) => Number(value)) foo: number = 123;
</code>```

答:
When you write

```<code>foo="123"
</code>```

you use one-time string initialization. Angular sets value to foo property as string and forgets about it.

If you want to use something other than string then use the brackets

```<code>[foo]="123"
</code>```

When writing a binding, be aware of a template statement's execution context. The identifiers in a template statement belong to a specific context object, usually the Angular component controlling the template.

When you use property binding then value is passes as it is

```<code>[foo]="isValid"

...
@Component({...})
class MyComponent {
  isValid: boolean = true;
</code>```

if you want to have enum then you should write something like this

```<code>[foo]="MyEnum"

...

enum MyEnum {
  one,
  two,
  three
}

@Component({...})
class MyComponent {
  MyEnum = MyEnum;
}
</code>```

Other examples

```<code>[foo]="445" => number
[foo]="'445'" => string
[foo]="x" => typeof x or undefined
</code>```

Body:
I'm currently working with Angular and TypeScript and I want to know if it's possible to bind component @Inputs to use specific types?

Example

@Component({selector: 'foobar'})
export class FooComponent {
    @Input() foo: number;
    @Input() bar: boolean;
}

<foobar foo="123" bar="true"></foobar>

When the component is bound, both foo and bar are string. Does angular provide a way to enforce the specified type?

I tried this, but I don't like it...(it seems dirty and not very elegant)

@Component({selector: 'foobar'})
export class FooComponent {
    foo: number;
    bar: boolean;

    @Input('foo') set _foo(value: string) {
        this.foo = Number(value);
    }

    @Input('bar') set _bar(value: string) {
        this.bar = value === 'true';
    }
}

It would be nice if there was something in Angular's Input that could act as a binding delegate; For example:

@Input('foo', (value: string) => Number(value)) foo: number = 123;

Body:
When you write

foo="123"

you use one-time string initialization. Angular sets value to foo property as string and forgets about it.

If you want to use something other than string then use the brackets

[foo]="123"

When writing a binding, be aware of a template statement's execution context. The identifiers in a template statement belong to a specific context object, usually the Angular component controlling the template.

When you use property binding then value is passes as it is

[foo]="isValid"

...
@Component({...})
class MyComponent {
  isValid: boolean = true;

if you want to have enum then you should write something like this

[foo]="MyEnum"

...

enum MyEnum {
  one,
  two,
  three
}

@Component({...})
class MyComponent {
  MyEnum = MyEnum;
}

Other examples

[foo]="445" => number
[foo]="'445'" => string
[foo]="x" => typeof x or undefined


问:
How to maximize a desktop application using TestStack.White after it is minimized
I have a code to minimize a desktop application using a minimize button at the top right button of the application.

But once it is minimized i have to do some operations with the browser and again switch back to desktop application. I face code issue here, where i need to click the application button in the task bar to maximize it.

Can anyone please help me on this or any other way to maximize the minimized application? i shouldn't close or reopen it, as some uploading will be in-progress.

答:
So after looking into how White exposes the WindowPattern I was able to find a public property on the Window class called WinPattern which returns a WindowPattern. After getting the window pattern you should be able to call WindowPattern.SetWindowVisualState.

The link to the WindowPattern.SetWindowVisualState has some good example code for how to use this pattern. I added the code that is most relevant with the use of White here since White handles getting the pattern for you.

```<code>///--------------------------------------------------------------------
/// <summary>
/// Calls the WindowPattern.SetVisualState() method for an associated
/// automation element.
/// </summary>
/// <param name="windowPattern">
/// The WindowPattern control pattern obtained from
/// an automation element.
/// </param>
/// <param name="visualState">
/// The specified WindowVisualState enumeration value.
/// </param>
///--------------------------------------------------------------------
private void SetVisualState(WindowPattern windowPattern,
    WindowVisualState visualState)
{
    try
    {
        if (windowPattern.Current.WindowInteractionState ==
            WindowInteractionState.ReadyForUserInteraction)
        {
            switch (visualState)
            {
                case WindowVisualState.Maximized:
                    // Confirm that the element can be maximized
                    if ((windowPattern.Current.CanMaximize) &&
                        !(windowPattern.Current.IsModal))
                    {
                        windowPattern.SetWindowVisualState(
                            WindowVisualState.Maximized);
                        // TODO: additional processing
                    }
                    break;
                case WindowVisualState.Minimized:
                    // Confirm that the element can be minimized
                    if ((windowPattern.Current.CanMinimize) &&
                        !(windowPattern.Current.IsModal))
                    {
                        windowPattern.SetWindowVisualState(
                        WindowVisualState.Minimized);
                        // TODO: additional processing
                    }
                    break;
                case WindowVisualState.Normal:
                    windowPattern.SetWindowVisualState(
                    WindowVisualState.Normal);
                    break;
                default:
                    windowPattern.SetWindowVisualState(
                    WindowVisualState.Normal);
                    // TODO: additional processing
                    break;
            }
        }
    }
    catch (InvalidOperationException)
    {
        // object is not able to perform the requested action
        return;
    }
}
</code>```

Body:
So after looking into how White exposes the WindowPattern I was able to find a public property on the Window class called WinPattern which returns a WindowPattern. After getting the window pattern you should be able to call WindowPattern.SetWindowVisualState.

The link to the WindowPattern.SetWindowVisualState has some good example code for how to use this pattern. I added the code that is most relevant with the use of White here since White handles getting the pattern for you.

///--------------------------------------------------------------------
/// <summary>
/// Calls the WindowPattern.SetVisualState() method for an associated
/// automation element.
/// </summary>
/// <param name="windowPattern">
/// The WindowPattern control pattern obtained from
/// an automation element.
/// </param>
/// <param name="visualState">
/// The specified WindowVisualState enumeration value.
/// </param>
///--------------------------------------------------------------------
private void SetVisualState(WindowPattern windowPattern,
    WindowVisualState visualState)
{
    try
    {
        if (windowPattern.Current.WindowInteractionState ==
            WindowInteractionState.ReadyForUserInteraction)
        {
            switch (visualState)
            {
                case WindowVisualState.Maximized:
                    // Confirm that the element can be maximized
                    if ((windowPattern.Current.CanMaximize) &&
                        !(windowPattern.Current.IsModal))
                    {
                        windowPattern.SetWindowVisualState(
                            WindowVisualState.Maximized);
                        // TODO: additional processing
                    }
                    break;
                case WindowVisualState.Minimized:
                    // Confirm that the element can be minimized
                    if ((windowPattern.Current.CanMinimize) &&
                        !(windowPattern.Current.IsModal))
                    {
                        windowPattern.SetWindowVisualState(
                        WindowVisualState.Minimized);
                        // TODO: additional processing
                    }
                    break;
                case WindowVisualState.Normal:
                    windowPattern.SetWindowVisualState(
                    WindowVisualState.Normal);
                    break;
                default:
                    windowPattern.SetWindowVisualState(
                    WindowVisualState.Normal);
                    // TODO: additional processing
                    break;
            }
        }
    }
    catch (InvalidOperationException)
    {
        // object is not able to perform the requested action
        return;
    }
}


问:
Phalcon logger / fileAdapter not working
I am trying to make a logger working in PhalconPHP for debugging purposes.

But no matter what code I try to use, it gives me this error when loading the browser:

```<code>Can't open log file at 'app/logs/test.log'
#0 /home/myuser/public_html/demo1/app/controllers/UsersController.php(6): Phalcon\Logger\Adapter\File->__construct('app/logs/test.l...')
#1 [internal function]: unknown()
#2 [internal function]: Phalcon\Loader->autoLoad('UsersController')
#3 [internal function]: spl_autoload_call('UsersController')
#4 [internal function]: Phalcon\Dispatcher->_dispatch()
#5 [internal function]: Phalcon\Dispatcher->dispatch()
#6 /home/myuser/public_html/demo1/public/index.php(42): Phalcon\Mvc\Application->handle()
#7 {main}

<?php

use Phalcon\Logger\Adapter\File as FileAdapter;

// Create the file logger in 'w' mode
$logger = new FileAdapter("app/logs/test.log", array(
    'mode' => 'w'
));
</code>```

FYI: All the logger codes are tested in a Phalcon controller.

```<code>$logger = new \Phalcon\Logger\Adapter\File("app/logs/test.log");

$logger->log("This is a message");
$logger->log(\Phalcon\Logger::ERROR, "This is an error");
$logger->error("This is another error");

$logger->close();
</code>```

```<code>use Phalcon\Logger;
use Phalcon\Logger\Adapter\File as FileAdapter;

$logger = new FileAdapter("app/logs/test.log");

$logger->log(
    "This is a message"
);
</code>```

答:
First of all, I recommend not using relative path, but absolute.

In your case it seems like absolute path is:
/home/myuser/public_html/demo1/app/logs/test.log

Secondly check if the php user (commonly in web server it is www-data) has the rights to write to logs directory (for example make www-data own dir logs).

And last thing that I encounter sometimes is, when you use cli, the log file is owned by shell user, then www-data user cannot write to that file. Make either different logs for cli or just delete logs.

Hope it helps

Body:
I am trying to make a logger working in PhalconPHP for debugging purposes.

But no matter what code I try to use, it gives me this error when loading the browser:

Can't open log file at 'app/logs/test.log'
#0 /home/myuser/public_html/demo1/app/controllers/UsersController.php(6): Phalcon\Logger\Adapter\File->__construct('app/logs/test.l...')
#1 [internal function]: unknown()
#2 [internal function]: Phalcon\Loader->autoLoad('UsersController')
#3 [internal function]: spl_autoload_call('UsersController')
#4 [internal function]: Phalcon\Dispatcher->_dispatch()
#5 [internal function]: Phalcon\Dispatcher->dispatch()
#6 /home/myuser/public_html/demo1/public/index.php(42): Phalcon\Mvc\Application->handle()
#7 {main}

<?php

use Phalcon\Logger\Adapter\File as FileAdapter;

// Create the file logger in 'w' mode
$logger = new FileAdapter("app/logs/test.log", array(
    'mode' => 'w'
));

FYI: All the logger codes are tested in a Phalcon controller.

$logger = new \Phalcon\Logger\Adapter\File("app/logs/test.log");

$logger->log("This is a message");
$logger->log(\Phalcon\Logger::ERROR, "This is an error");
$logger->error("This is another error");

$logger->close();

use Phalcon\Logger;
use Phalcon\Logger\Adapter\File as FileAdapter;

$logger = new FileAdapter("app/logs/test.log");

$logger->log(
    "This is a message"
);


问:
Calling WCF service using VBA code in Excel 2010
I'm trying to call an ASP.Net WCF service in XML from VBA in Excel 2010.

I read this question:
calling web service using VBA code in excel 2010
but I can't use a third party library, XML or JSON.

Is there a way to do it natively with VBA working with web services?

EDIT
I've installed SOAP Toolkit 3.0 and SOAP Toolkit 3.0 Software Update.

I've added these libraries to my workbook:

Microsoft XML, v3.0

Microsoft Soap Type Library v3.0

WinHttp Soap Connector Type Library

WinInet Soap Connector Type Library

Microsoft Soap WSDL File Generator v3.0

I think I have to add a web reference to my service into my workbook by "Tools->Add a web reference" menu, but this option doesn't appear. What should I do to see it ?

答:
This is an example routine that fetches data from a webservice using the Microsoft XML 3.0 library:

```<code>Sub DoIt()
    Dim sURL As String
    Dim sEnv As String
    Dim xmlHtp As New MSXML2.XMLHTTP
    Dim xmlDoc As New DOMDocument
    Dim oValueNodes As MSXML2.IXMLDOMNodeList
    sURL = "http://webservices.gama-system.com/exchangerates.asmx?op=CurrentConvertToEUR"

    sEnv = "<?xml version=""1.0"" encoding=""utf-8""?>"
    sEnv = sEnv & "<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">"
    sEnv = sEnv & "  <soap:Body>"
    sEnv = sEnv & "    <CurrentConvertToEUR xmlns=""http://www.gama-system.com/webservices"">"
    sEnv = sEnv & "      <dcmValue>100</dcmValue>"
    sEnv = sEnv & "      <strBank>BS</strBank>"
    sEnv = sEnv & "      <strCurrency>USD</strCurrency>"
    sEnv = sEnv & "      <intRank>1</intRank>"
    sEnv = sEnv & "    </CurrentConvertToEUR>"
    sEnv = sEnv & "  </soap:Body>"
    sEnv = sEnv & "</soap:Envelope>"

    With xmlHtp
        .Open "post", sURL, False
        .setRequestHeader "Host", "webservices.gama-system.com"
        .setRequestHeader "Content-Type", "text/xml; charset=utf-8"
        .setRequestHeader "soapAction", "http://www.gama-system.com/webservices/CurrentConvertToEUR"
        .send sEnv
        xmlDoc.loadXML .responseText
        Set oValueNodes = xmlDoc.getElementsByTagName("CurrentConvertToEURResponse")
        MsgBox oValueNodes.Item(0).nodeTypedValue
    End With
     'xmlDoc.Save ThisWorkbook.Path & "\WebQueryResult.xml"
End Sub
</code>```

Key thing you need is the exact structure of the SOAP envelope the webservice is expecting.

Body:
This is an example routine that fetches data from a webservice using the Microsoft XML 3.0 library:

Sub DoIt()
    Dim sURL As String
    Dim sEnv As String
    Dim xmlHtp As New MSXML2.XMLHTTP
    Dim xmlDoc As New DOMDocument
    Dim oValueNodes As MSXML2.IXMLDOMNodeList
    sURL = "http://webservices.gama-system.com/exchangerates.asmx?op=CurrentConvertToEUR"

    sEnv = "<?xml version=""1.0"" encoding=""utf-8""?>"
    sEnv = sEnv & "<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">"
    sEnv = sEnv & "  <soap:Body>"
    sEnv = sEnv & "    <CurrentConvertToEUR xmlns=""http://www.gama-system.com/webservices"">"
    sEnv = sEnv & "      <dcmValue>100</dcmValue>"
    sEnv = sEnv & "      <strBank>BS</strBank>"
    sEnv = sEnv & "      <strCurrency>USD</strCurrency>"
    sEnv = sEnv & "      <intRank>1</intRank>"
    sEnv = sEnv & "    </CurrentConvertToEUR>"
    sEnv = sEnv & "  </soap:Body>"
    sEnv = sEnv & "</soap:Envelope>"

    With xmlHtp
        .Open "post", sURL, False
        .setRequestHeader "Host", "webservices.gama-system.com"
        .setRequestHeader "Content-Type", "text/xml; charset=utf-8"
        .setRequestHeader "soapAction", "http://www.gama-system.com/webservices/CurrentConvertToEUR"
        .send sEnv
        xmlDoc.loadXML .responseText
        Set oValueNodes = xmlDoc.getElementsByTagName("CurrentConvertToEURResponse")
        MsgBox oValueNodes.Item(0).nodeTypedValue
    End With
     'xmlDoc.Save ThisWorkbook.Path & "\WebQueryResult.xml"
End Sub

Key thing you need is the exact structure of the SOAP envelope the webservice is expecting.


问:
C# - Conversion while calling method with output parameter
Disclaimer: Not a professional developer

We're using SSIS to pull messages RabbitMQ, and I've managed to build a C# script component that pulls and pops messages off our queue for us using Queue.Dequeue(). So far, so good. However, we want to have some form of automatic check in place so our SSIS component won't be running continuously, but rather can be scheduled to run every n minutes.

I found the Dequeue(int timeout, out object result) method for this, and have managed to implement it like so: (we'd like the BasiocDeliverEventArgs result in order to process the body of the message)

```<code>object message;
myConsumer.Queue.Dequeue(millisecondsTimeout: 500, result:out message);
BasicDeliverEventArgs ea = (BasicDeliverEventArgs)message;
</code>```

This seems to work, but somehow feel somewhat redundant to me. This, for example, seems more intuitive to me:

```<code>myConsumer.Queue.Dequeue(millisecondsTimeout: 500
     , result:out (BasicDeliverEventArgs)message)
</code>```

But that yields an error specifying invalid arguments. Could someone please explain why it would throw that error, and why that syntax is invalid?

答:
The Dequeue method accepts object type in the 2nd parameter. But you are passing it a BasicDeliverEventArgs type. That is why you are getting the error. What if there are Employee, or SomeotherType in the queue, the method will not be able to assign it to the BasicDeliverEventArgs reference.

The owness is on the caller to convert it after the method has returned.

Also read this quote from MSDN:

The out keyword causes arguments to be passed by reference. It is like the ref keyword, except that ref requires that the variable be initialized before it is passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword

In c# nearly everything inherits object so the method you have called can store any type in an object reference (so long as they inherit object) and return it to you. However it CANNOT store any type in BasicDeliverEventArgs reference and that's why it is not allowing it.

Body:
Disclaimer: Not a professional developer

We're using SSIS to pull messages RabbitMQ, and I've managed to build a C# script component that pulls and pops messages off our queue for us using Queue.Dequeue(). So far, so good. However, we want to have some form of automatic check in place so our SSIS component won't be running continuously, but rather can be scheduled to run every n minutes.

I found the Dequeue(int timeout, out object result) method for this, and have managed to implement it like so: (we'd like the BasiocDeliverEventArgs result in order to process the body of the message)

object message;
myConsumer.Queue.Dequeue(millisecondsTimeout: 500, result:out message);
BasicDeliverEventArgs ea = (BasicDeliverEventArgs)message;

This seems to work, but somehow feel somewhat redundant to me. This, for example, seems more intuitive to me:

myConsumer.Queue.Dequeue(millisecondsTimeout: 500
     , result:out (BasicDeliverEventArgs)message)

But that yields an error specifying invalid arguments. Could someone please explain why it would throw that error, and why that syntax is invalid?


问:
Wordpress/PHP: Shorten title if title characters are more than 8 characters
I am trying to learn how to shorten a title only if it is over 8 characters long. If it is longer than 8 characters, then echo the first 8 characters and put an ellipse after it.

Here is how I am getting the title:

<?php echo $post->post_title ?>

Any help would be greatly appreciated. This will be a great learning lesson for me so I can replicate this in the future, so again any help would be amazing.

答:
You can use mb_strimwidth

```<code>echo mb_strimwidth('Your Title', 0, 8, '…');
</code>```

If you want to truncate with respect to word boundaries, see

Truncate a multibyte String to n chars

Body:
You can use mb_strimwidth

echo mb_strimwidth('Your Title', 0, 8, '…');

If you want to truncate with respect to word boundaries, see

Truncate a multibyte String to n chars


问:
Creating Jars without Main() method
I have downloaded a project from  SVN and have imported the same in my Eclipse IDE.The project have several .java files but none of them have any main() method.

It is required to make some minor changes in one of the file and then create a new version of the jar. And replace the old jar with the new version in the server.

Ours is a big project and the tool is running on Weblogic. But while creating the newer version of the jar through Eclipse ( Export>Jar) it is asking to provide the class which contains main() method or any entry point.

Please let me know how should I proceed to create the jar?

答:
eclipse supports the creation of different JAR file types.

You went for creating a "runnable" JAR. But in order to run ... a JAR needs a main().

Thus: simply export as "ordinary" JAR. See the documentation for further reading; and follow the instructions for "Creating a New JAR File".

Title: Creating Jars without Main() method


问:
How to check if a java project has only interfaces and enum
I am trying to build a core module to be used across services, its collection of enum and interfaces with(without) default implementation only. Wanted to know if its possible to impose this rule either as part of mvn build or ci flow to check if someone has pushed a class in it. Being able to done at mvn would be preferred though.

Is this even possible? If yes can someone point me how?

答:
Not sure which is the best way but I would suggest a custom rule on sonar/findbugs/checkstyle/pmd with the appropriate plugin.

Or a custom annotation processor that you use at compile time.


问:
How to timing process in php for request Timeout
My PHP code is timing out with the following error:

This request takes too long to process, it is timed out by the server. If it should not be timed out, please contact administrator of this web site to increase 'Connection Timeout'

I'm not sure why this is happening. This is my code:

```<code>if(!in_array($name,$names)){
    mysql_query("INSERT INTO `tbl` (`name`, `time`, `link`) VALUES ( '$name', '$time', '$link');");
} else {
    mysql_query("UPDATE `tbl` SET `time` = '$time', `link` = '$link' WHERE `pishkhan`.`name` = $name;");
    echo $name.'<br/>';
}
file_put_contents('test/albums/news/'.$name.".jpg", fopen($link, 'r'));
</code>```

答:
As I stated in my answer here, this particular error message is generated by the LiteSpeed web server (a faster replacement for Apache).  It has a special feature whereby it cancels long-running scripts (even those that use set_time_limit()). To disable this, you need to put the following in your .htaccess file in the root of your site.

```<code>RewriteEngine On
RewriteRule .* - [E=noabort:1]
RewriteRule .* - [E=noconntimeout:1]
</code>```

Body:
My PHP code is timing out with the following error:

This request takes too long to process, it is timed out by the server. If it should not be timed out, please contact administrator of this web site to increase 'Connection Timeout'

I'm not sure why this is happening. This is my code:

if(!in_array($name,$names)){
    mysql_query("INSERT INTO `tbl` (`name`, `time`, `link`) VALUES ( '$name', '$time', '$link');");
} else {
    mysql_query("UPDATE `tbl` SET `time` = '$time', `link` = '$link' WHERE `pishkhan`.`name` = $name;");
    echo $name.'
';
}
file_put_contents('test/albums/news/'.$name.".jpg", fopen($link, 'r'));

Body:
As I stated in my answer here, this particular error message is generated by the LiteSpeed web server (a faster replacement for Apache).  It has a special feature whereby it cancels long-running scripts (even those that use set_time_limit()). To disable this, you need to put the following in your .htaccess file in the root of your site.

RewriteEngine On
RewriteRule .* - [E=noabort:1]
RewriteRule .* - [E=noconntimeout:1]


问:
Containers and divs in CSS
Good day,
I'm not new to CSS or DIVs but have been out of touch for long enough. Trying to work out with Containers and nested DIVs but not getting much success in doing what I'm trying to do. Have already searched enough on SO and Goog but, hopefully you can help me.

Here's the representation of what I wish to achieve.

Screenshot of the layout

And here is what I have done so far ..

.dealsglobal {
    width: 45%;
    display: inline-block;
    float: left;
    margin-right:20px;
    height: auto;
    overflow: auto;
}

.dealsglobal h2 {
    margin-left: 10px;
}

.dealsindia {
    width: 45%;
    height: auto;
    overflow: auto;
}

.dealsindia h2 {
    margin-left: 10px;
}

.dealsleft {
    margin: 0px 25px 10px 0px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    float: left;
    display: inline-block;
    overflow: auto;
}

.dealsleft img {
    border: 1px solid #ddd;
    background: #fff;
    border-radius: 4px;
    margin-left: auto;
    margin-right: auto;
    width: 100px;
}

.dealsright {
    margin-bottom: 10px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    display: inline-block;
    overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dealsglobal">
<h2>Global Coupons</h2>
    <div class="dealsleft">
 <img src="thumb-heavengifts.jpg" alt="HeavenGifts.com Web Store" align="middle" />
    </div>
    <div class="dealsright">
    Test
    </div>
</div>

<div class="dealsindia">
<h2>Indian Coupons</h2>
    <div class="dealsleft">
    Test
    </div>
    <div class="dealsright">
 Test
    </div>
</div></code>```

The image just wont center, no matter what I do. I believe, somewhere I have set the property to align left or something. Can anyone please point me to the correct direction? Thanks for your help!

答:
You are probably looking for any of these 2:

```<code>parentSelector {
  display: block; /* can also be an inline-block, with set width */
  text-align: center;
}
childSelector {
  width: 60%; /* generic. Change it */
  display: block;
  margin: 0 auto;
}
</code>```

... or:

```<code>parentSelector {
  display: flex;
  flex-direction: column;
  align-items: center;
}
childSelector {
  max-width: 60%;    /* optional. Change it.
                      * You don't need to set width here and,
                      * it's OK not to limit max-width, either
                      */
}
</code>```

Title: Containers and divs in CSS

Body:
Good day,
I'm not new to CSS or DIVs but have been out of touch for long enough. Trying to work out with Containers and nested DIVs but not getting much success in doing what I'm trying to do. Have already searched enough on SO and Goog but, hopefully you can help me.

Here's the representation of what I wish to achieve.

Screenshot of the layout

And here is what I have done so far ..

.dealsglobal {
    width: 45%;
    display: inline-block;
    float: left;
    margin-right:20px;
    height: auto;
    overflow: auto;
}

.dealsglobal h2 {
    margin-left: 10px;
}

.dealsindia {
    width: 45%;
    height: auto;
    overflow: auto;
}

.dealsindia h2 {
    margin-left: 10px;
}

.dealsleft {
    margin: 0px 25px 10px 0px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    float: left;
    display: inline-block;
    overflow: auto;
}

.dealsleft img {
    border: 1px solid #ddd;
    background: #fff;
    border-radius: 4px;
    margin-left: auto;
    margin-right: auto;
    width: 100px;
}

.dealsright {
    margin-bottom: 10px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    display: inline-block;
    overflow: auto;
}

Global Coupons

    Test

Indian Coupons

    Test

 Test

The image just wont center, no matter what I do. I believe, somewhere I have set the property to align left or something. Can anyone please point me to the correct direction? Thanks for your help!

Body:
You are probably looking for any of these 2:

parentSelector {
  display: block; /* can also be an inline-block, with set width */
  text-align: center;
}
childSelector {
  width: 60%; /* generic. Change it */
  display: block;
  margin: 0 auto;
}

... or:

parentSelector {
  display: flex;
  flex-direction: column;
  align-items: center;
}
childSelector {
  max-width: 60%;    /* optional. Change it.
                      * You don't need to set width here and,
                      * it's OK not to limit max-width, either
                      */
}


问:
C# - Could not load type FirefoxDriverService
I have the following code:

```<code>    FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(currentDir.Remove(0, 6), "geckodriver.exe");
    //service.HideCommandPromptWindow = true;
    service.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox (x86)\firefox.exe";
    driver = new FirefoxDriver(service);
    driver.Manage().Window.Maximize();
</code>```

But I get the following error:

Error message: System.TypeLoadException : Could not load type
  'OpenQA.Selenium.Firefox.FirefoxDriverService' from assembly
  'WebDriver, Version=2.45.0.0, Culture=neutral, PublicKeyToken=null'.

Why is this happening?

答:
I worked it out.
The thing was that Webdriver.dll was pointing to "PahntomJS.Xplatform.2.45.0.1" instead of "Selenium.WebDriver.3.4.0". The referense was bad.

What I did was removed Phantom from NuGet and reinstall Webdriver 3.4.0 and it worked!

In "project.csproj" it was displayed:

Reference Include="WebDriver, Version=2.45.0.0, Culture=neutral,
  processorArchitecture=MSIL"

..\packages\Selenium.WebDriver.PhantomJS.Xplatform.2.45.0.1\lib\net40\WebDriver.dll

And now it displays:

Reference Include="WebDriver, Version=3.4.0.0, Culture=neutral,
  processorArchitecture=MSIL"

..\packages\Selenium.WebDriver.3.4.0\lib\net40\WebDriver.dll

Body:
I have the following code:

    FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(currentDir.Remove(0, 6), "geckodriver.exe");
    //service.HideCommandPromptWindow = true;
    service.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox (x86)\firefox.exe";
    driver = new FirefoxDriver(service);
    driver.Manage().Window.Maximize();

But I get the following error:

Error message: System.TypeLoadException : Could not load type
  'OpenQA.Selenium.Firefox.FirefoxDriverService' from assembly
  'WebDriver, Version=2.45.0.0, Culture=neutral, PublicKeyToken=null'.

Why is this happening?


问:
JPA Single Table Inheritance: Not a managed type
I have a Spring Boot application (embedded Tomcat, Thymeleaf template...) using

```<code>spring-boot-starter-data-jpa
</code>```

I use Inheritance strategies with JPA and Hibernate

I have this class:

```<code>@Entity
@Table(name="t_alarm_notification")
@Inheritance (strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name= "ALARM_TYPE")
public abstract class AlarmNotification  implements Serializable {
..
}
</code>```

and this other one:

```<code>   @MappedSuperclass
    public class BookAlarmNotification extends AlarmNotification {

        /**
         *
         */
        private static final long serialVersionUID = 1L;

        private Book book;

..
}
</code>```

and this other one

```<code>public interface BookAlarmNotificationRepository extends CrudRepository<BookAlarmNotification, Long> {

}
</code>```

but running an integration test or just starting the String Boot app. I got this error:

```<code> java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookAlarmNotificationService': Unsatisfied dependency expressed through field 'bookAlarmNotificationRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookAlarmNotificationRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.nicinc.persistence.domain.backend.BookAlarmNotification
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 25 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookAlarmNotificationRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.nicinc.persistence.domain.backend.BookAlarmNotification
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
    ... 43 more
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.nicinc.persistence.domain.backend.BookAlarmNotification
    at org.hibernate.jpa.internal.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:210)
    at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:70)
    at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:68)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:153)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:100)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:82)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:199)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:101)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    ... 53 more
</code>```

答:
In the JPA 2.1 specification document we find in Section 11.1.38 (PDF page 471):

The MappedSuperclass annotation designates a class whose mapping information is applied to the entities that inherit from it. A mapped superclass has no separate table defined for it.

...

A class designated with the MappedSuperclass annotation can be mapped in the same way as an entity except that the mappings will apply only to its subclasses since no table exists for the mapped
  superclass itself.

So the problem originates from the fact, that your Entity class AlarmNotification is incorrectly used as a base class for BookAlarmNotification. As noted in the comment of "Abdullah Khan", the correct way of annotating would be:

Annotate the abstract base class AlarmNotification like:

```<code>@MappedSuperclass
@Inheritance (strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name= "ALARM_TYPE")
public abstract class AlarmNotification  implements Serializable {
   //..
}
</code>```

Use the @Entity annotation for the class that inherit from it:

```<code>@Entity
@Table(name="t_book_alarm_notification")
public class BookAlarmNotification extends AlarmNotification {
   //..
}
</code>```

Thus, the UnsatisfiedDependencyException / IllegalArgumentException

Not a managed type: class com.nicinc.persistence.domain.backend.BookAlarmNotification

shouldn't occur any longer as it now exists as managed Entity in your application.

Hope it helps.

Body:
I have a Spring Boot application (embedded Tomcat, Thymeleaf template...) using

spring-boot-starter-data-jpa

I use Inheritance strategies with JPA and Hibernate

I have this class:

@Entity
@Table(name="t_alarm_notification")
@Inheritance (strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name= "ALARM_TYPE")
public abstract class AlarmNotification  implements Serializable {
..
}

and this other one:

   @MappedSuperclass
    public class BookAlarmNotification extends AlarmNotification {

        /**
         *
         */
        private static final long serialVersionUID = 1L;

        private Book book;

..
}

and this other one

public interface BookAlarmNotificationRepository extends CrudRepository<BookAlarmNotification, Long> {

}

but running an integration test or just starting the String Boot app. I got this error:

 java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookAlarmNotificationService': Unsatisfied dependency expressed through field 'bookAlarmNotificationRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookAlarmNotificationRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.nicinc.persistence.domain.backend.BookAlarmNotification
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 25 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookAlarmNotificationRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.nicinc.persistence.domain.backend.BookAlarmNotification
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
    ... 43 more
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.nicinc.persistence.domain.backend.BookAlarmNotification
    at org.hibernate.jpa.internal.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:210)
    at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:70)
    at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:68)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:153)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:100)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:82)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:199)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:101)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    ... 53 more

Body:
In the JPA 2.1 specification document we find in Section 11.1.38 (PDF page 471):

The MappedSuperclass annotation designates a class whose mapping information is applied to the entities that inherit from it. A mapped superclass has no separate table defined for it.

...

A class designated with the MappedSuperclass annotation can be mapped in the same way as an entity except that the mappings will apply only to its subclasses since no table exists for the mapped
  superclass itself.

So the problem originates from the fact, that your Entity class AlarmNotification is incorrectly used as a base class for BookAlarmNotification. As noted in the comment of "Abdullah Khan", the correct way of annotating would be:

Annotate the abstract base class AlarmNotification like:

@MappedSuperclass
@Inheritance (strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name= "ALARM_TYPE")
public abstract class AlarmNotification  implements Serializable {
   //..
}

Use the @Entity annotation for the class that inherit from it:

@Entity
@Table(name="t_book_alarm_notification")
public class BookAlarmNotification extends AlarmNotification {
   //..
}

Thus, the UnsatisfiedDependencyException / IllegalArgumentException

Not a managed type: class com.nicinc.persistence.domain.backend.BookAlarmNotification

shouldn't occur any longer as it now exists as managed Entity in your application.

Hope it helps.