问:
How can I conditionally change the values of a dropdown in a Kendo Grid?
I'm developing a project with ASP MVC 5, Kendo UI, and some layers. The main idea is that after I chose a value from a dropdown column in a Kendo Grid for example:

```<code>columns.Bound(b => b.Country).ClientTemplate("#=Country.Name#");
</code>```

It should update a second and third column based on the previous selection:

```<code>columns.Bound(b => b.Category).ClientTemplate("#=Category.Name#");
columns.Bound(b => b.Client).ClientTemplate("#=Client.Name#");
</code>```

I haven't been able to find any example or idea in the Telerik documentation or forums:

Grid/Events

Grid / Editing custom editor

Refresh/Replace DataSource of Foreignkey DropDown List

I read this example too with a normal dropdown:

Kendo UI DropDownList on a change to trigger event

Has anyone experienced something like this? My current idea is to create N number of Editor Templates:

```<code>@model Kendo.Mvc.Examples.Models.CategoryViewModel

@(Html.Kendo().DropDownListFor(m => m)
    .DataValueField("CategoryID")
    .DataTextField("CategoryName")
    .BindTo((System.Collections.IEnumerable)ViewData["categories"])
)
</code>```

With each of the possible Countries, however, it could be really inefficient and I still don't know how to trigger the on Change event.

答:
After a long research, I was able to find a solution in this example:

Grid InLine and PopUp Editing using Cascading DropDownLists

However, it wasn't just copy and paste, I still don't know why this example is not available in the official FAQ Telerik page, but I'd like to provide the key point in order to do it:

1) You must select the InLine or PopUp edit mode:

```<code>.Editable(editable => editable.Mode(GridEditMode.InLine))
</code>```

Why? Because when you are going to edit or add the line:

The cascade Drop downs are fully linked to the ID, for example:

2) Next, your new column in the grid is going to look this one:

```<code>columns.Bound(b => b.CategoryID).ClientTemplate("#=Category.Name#");
</code>```

Be careful, before I we used the class as Category instead of the CategoryID, the ID is the crucial point.

3) You need to change the previous approach from adding the hint to the class to the ID of the it, for example:

Non-cascade approach:

```<code>[UIHint("ClientStatus")]
public Statuses Status { get; set; }

public int StatusID { get; set; }
</code>```

Cascade approach:

```<code>public Statuses Status { get; set; }

[UIHint("ClientStatus")]
public int StatusID { get; set; }
</code>```

3) The editor template from the cascade approaches should look like this:

Basic one:

```<code>@model int

@(Html.Kendo().DropDownListFor(m => m)
        .AutoBind(false)
        .DataValueField("CategoriesID")
        .DataTextField("Name")
        .DataSource(dataSource =>
        {
            dataSource.Read(read => read.Action("PopulateCategories", "FullView"))
            .ServerFiltering(true);
        })
)
@Html.ValidationMessageFor(m => m)
</code>```

Cascade ones:

```<code>@model int

@(Html.Kendo().DropDownListFor(m => m)
        .AutoBind(false)
        .DataValueField("ID")
        .DataTextField("Name")
        .DataSource(dataSource =>
        {
            dataSource.Read(read => read.Action("PopulateStatuses", "FullView").Data("filterCategories"))
            .ServerFiltering(true);
        })
        .CascadeFrom("CategoriesID")
)
@Html.ValidationMessageFor(m => m)
</code>```

4) The cascade is calling a JavaScript function that looks like this:

```<code>function filterCategories() {
    return {
        categoriesID: $("#CategoriesID").data("kendoDropDownList").value()
    };
}
</code>```

Where CategoriesID is the ID of the first drop down, which is generated when we edit or add a new line.

4) Finally, we need to share a JSON as a result:

First drop down:

```<code>public JsonResult PopulateCategories()
{
        return Json(CategoriesData.GetCategories(), JsonRequestBehavior.AllowGet);
}
</code>```

Second and further drop downs:

```<code>public JsonResult PopulateStatuses(int categoryID)
{
        return Json(StatusesData.GetStatuses(categoryID), JsonRequestBehavior.AllowGet);
}
</code>```

Body:
I'm developing a project with ASP MVC 5, Kendo UI, and some layers. The main idea is that after I chose a value from a dropdown column in a Kendo Grid for example:

columns.Bound(b => b.Country).ClientTemplate("#=Country.Name#");

It should update a second and third column based on the previous selection:

columns.Bound(b => b.Category).ClientTemplate("#=Category.Name#");
columns.Bound(b => b.Client).ClientTemplate("#=Client.Name#");

I haven't been able to find any example or idea in the Telerik documentation or forums:

Grid/Events

Grid / Editing custom editor

Refresh/Replace DataSource of Foreignkey DropDown List

I read this example too with a normal dropdown:

Kendo UI DropDownList on a change to trigger event

Has anyone experienced something like this? My current idea is to create N number of Editor Templates:

@model Kendo.Mvc.Examples.Models.CategoryViewModel

@(Html.Kendo().DropDownListFor(m => m)
    .DataValueField("CategoryID")
    .DataTextField("CategoryName")
    .BindTo((System.Collections.IEnumerable)ViewData["categories"])
)

With each of the possible Countries, however, it could be really inefficient and I still don't know how to trigger the on Change event.

Body:
After a long research, I was able to find a solution in this example:

Grid InLine and PopUp Editing using Cascading DropDownLists

However, it wasn't just copy and paste, I still don't know why this example is not available in the official FAQ Telerik page, but I'd like to provide the key point in order to do it:

1) You must select the InLine or PopUp edit mode:

.Editable(editable => editable.Mode(GridEditMode.InLine))

Why? Because when you are going to edit or add the line:

The cascade Drop downs are fully linked to the ID, for example:

2) Next, your new column in the grid is going to look this one:

columns.Bound(b => b.CategoryID).ClientTemplate("#=Category.Name#");

Be careful, before I we used the class as Category instead of the CategoryID, the ID is the crucial point.

3) You need to change the previous approach from adding the hint to the class to the ID of the it, for example:

Non-cascade approach:

[UIHint("ClientStatus")]
public Statuses Status { get; set; }

public int StatusID { get; set; }

Cascade approach:

public Statuses Status { get; set; }

[UIHint("ClientStatus")]
public int StatusID { get; set; }

3) The editor template from the cascade approaches should look like this:

Basic one:

@model int

@(Html.Kendo().DropDownListFor(m => m)
        .AutoBind(false)
        .DataValueField("CategoriesID")
        .DataTextField("Name")
        .DataSource(dataSource =>
        {
            dataSource.Read(read => read.Action("PopulateCategories", "FullView"))
            .ServerFiltering(true);
        })
)
@Html.ValidationMessageFor(m => m)

Cascade ones:

@model int

@(Html.Kendo().DropDownListFor(m => m)
        .AutoBind(false)
        .DataValueField("ID")
        .DataTextField("Name")
        .DataSource(dataSource =>
        {
            dataSource.Read(read => read.Action("PopulateStatuses", "FullView").Data("filterCategories"))
            .ServerFiltering(true);
        })
        .CascadeFrom("CategoriesID")
)
@Html.ValidationMessageFor(m => m)

4) The cascade is calling a JavaScript function that looks like this:

function filterCategories() {
    return {
        categoriesID: $("#CategoriesID").data("kendoDropDownList").value()
    };
}

Where CategoriesID is the ID of the first drop down, which is generated when we edit or add a new line.

4) Finally, we need to share a JSON as a result:

First drop down:

public JsonResult PopulateCategories()
{
        return Json(CategoriesData.GetCategories(), JsonRequestBehavior.AllowGet);
}

Second and further drop downs:

public JsonResult PopulateStatuses(int categoryID)
{
        return Json(StatusesData.GetStatuses(categoryID), JsonRequestBehavior.AllowGet);
}


来源: stackexchange

问:
React Native setInterval doubles it self after restarting app
All the time setInterval acts as I am expecting except for one instance. If user leaves the app by clicking 'home button' and restarts app by clicking the icon (not by selecting from overview), the old setInterval haven't stopped. It starts over again, and there are now running 2 setIntervals. It goes on and on if I repeat this process and user can end up running hundreds of intervals at the same time.

How do I prevent this? I want to run only one instance of seInterval at the time.

Here's my code:

```<code>import React, { Component } from 'react';
import  {
    AsyncStorage,
    Text,
    View,
    AppState,
} from 'react-native';

import timer from'react-native-timer';

class Code_temp extends Component {

    redirect(routeName){
        this.props.navigator.push({
            name: routeName
        });
    }

    constructor(props){
        super(props);

        this.state = {
            appState:           AppState.currentState,
        };
    }

    componentDidMount() {

        AppState.addEventListener('change', this._handleAppStateChange);

        this.setState({showMsg: true}, () => timer.setInterval(
            this, 'hideMsg', () =>{
                console.log( 1 );
            }, 1000
        ));
    }

    componentWillUnmount() {

        AppState.removeEventListener('change', this._handleAppStateChange);
    }

    _handleAppStateChange = (nextAppState) => {
        if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {

        }
        this.setState({appState: nextAppState});
    };

    componentWillMount() {

    }

    render() {
        return (
            <View>
                <Text>
                    Test
                </Text>
            </View>
        );
    }
}

export default Code_temp
</code>```

答:
That's because you are not clearing the setInterval when the component is unmounted, also remove 'this' from setinterval arguments</p>

```<code>  componentDidMount() {
        timer.clearInterval('hideMsg');
        AppState.addEventListener('change', this._handleAppStateChange);
    this.setState({showMsg: true}, () => timer.setInterval(
        'hideMsg', () =>{
            console.log( 1 );
        }, 1000
    ));
}

componentWillUnmount() {

  timer.clearInterval('hideMsg');

};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
All the time setInterval acts as I am expecting except for one instance. If user leaves the app by clicking 'home button' and restarts app by clicking the icon (not by selecting from overview), the old setInterval haven't stopped. It starts over again, and there are now running 2 setIntervals. It goes on and on if I repeat this process and user can end up running hundreds of intervals at the same time.

How do I prevent this? I want to run only one instance of seInterval at the time.

Here's my code:

import React, { Component } from 'react';
import  {
    AsyncStorage,
    Text,
    View,
    AppState,
} from 'react-native';

import timer from'react-native-timer';

class Code_temp extends Component {

    redirect(routeName){
        this.props.navigator.push({
            name: routeName
        });
    }

    constructor(props){
        super(props);

        this.state = {
            appState:           AppState.currentState,
        };
    }

    componentDidMount() {

        AppState.addEventListener('change', this._handleAppStateChange);

        this.setState({showMsg: true}, () => timer.setInterval(
            this, 'hideMsg', () =>{
                console.log( 1 );
            }, 1000
        ));
    }

    componentWillUnmount() {

        AppState.removeEventListener('change', this._handleAppStateChange);
    }

    _handleAppStateChange = (nextAppState) => {
        if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {

        }
        this.setState({appState: nextAppState});
    };

    componentWillMount() {

    }

    render() {
        return (
            <View>
                <Text>
                    Test
                </Text>
            </View>
        );
    }
}

export default Code_temp

Body:
That's because you are not clearing the setInterval when the component is unmounted, also remove 'this' from setinterval arguments

  componentDidMount() {
        timer.clearInterval('hideMsg');
        AppState.addEventListener('change', this._handleAppStateChange);
    this.setState({showMsg: true}, () => timer.setInterval(
        'hideMsg', () =>{
            console.log( 1 );
        }, 1000
    ));
}

componentWillUnmount() {

  timer.clearInterval('hideMsg');

};


问:
How to get the right channel while encoding AAC-HE-V1 by fdk on iOS?
I use the fdk v2.0.101 to encode the AAC-HE-V1 on iOS by xcode Version 8.0 (8A218a), but i always got the stereo channel aac data even if i set mono as the channel.

How to get the right channel while encoding AAC-HE-V1 by fdk?

PS: AAC-LC is OK. Tested on iPhone 6 with iOS 9.3.

The following is the code snippet:

initialization part

```<code>    UINT channels = 1;
    HANDLE_AACENCODER encoder_handle;
    AACENC_InfoStruct encoder_info;

    int HE_AACv1 = 5;

    TRANSPORT_TYPE transport_type = TT_MP4_ADTS;

    CHANNEL_MODE mode;

    switch (channels) {
        case 1: mode = MODE_1;       break;
        case 2: mode = MODE_2;       break;
        case 3: mode = MODE_1_2;     break;
        case 4: mode = MODE_1_2_1;   break;
        case 5: mode = MODE_1_2_2;   break;
        case 6: mode = MODE_1_2_2_1; break;
    }

    CheckError(aacEncOpen(&encoder_handle, 0, channels), @"Unable to open encoder : %i");
    CheckError(aacEncoder_SetParam(encoder_handle, AACENC_AOT, HE_AACv1), @"Unable to set the AOT : %i");
    CheckError(aacEncoder_SetParam(encoder_handle, AACENC_SAMPLERATE, 44100),
               @"Unable to set the sample rate : %i");
    CheckError(aacEncoder_SetParam(encoder_handle, AACENC_CHANNELMODE, mode),
               @"Unable to set the channel mode : %i");
    CheckError(aacEncoder_SetParam(encoder_handle, AACENC_CHANNELORDER, 1),
               @"Unable to set the wav channel order : %i");
    CheckError(aacEncoder_SetParam(encoder_handle, AACENC_BITRATE, 90000),
               @"Unable to set the bitrate : %i");
    CheckError(aacEncoder_SetParam(encoder_handle, AACENC_TRANSMUX, transport_type),
               @"Unable to set the ADTS transmux : %i");
    CheckError(aacEncoder_SetParam(encoder_handle, AACENC_AFTERBURNER, 1),
               @"Unable to set the afterburner mode : %i");
    CheckError(aacEncEncode(encoder_handle, NULL, NULL, NULL, NULL),
               @"Unable to initialize the encoder : %i");
    CheckError(aacEncInfo(encoder_handle, &encoder_info), @"Unable to get the encoder info : %i");
</code>```

Enocoding part:

```<code>  AudioBuffer originBuffer = ...;

  AACENC_OutArgs out_args = { 0 };
  AACENC_ERROR err;

  int out_identifier = OUT_BITSTREAM_DATA;

  uint8_t *output_data = calloc(encoder_info.maxOutBufBytes, 1);

  int read = originBuffer.mDataByteSize;

  void *in_ptr = originBuffer.mData;
  int in_size = read;
  int in_elem_size = _sampleBytes;

  int in_identifier = IN_AUDIO_DATA;

  AACENC_InArgs in_args = { 0 };
  in_args.numInSamples = read / _sampleBytes;

  AACENC_BufDesc in_buf = { 0 }, out_buf = { 0 };
  in_buf.numBufs = 1;
  in_buf.bufs = &in_ptr;
  in_buf.bufferIdentifiers = &in_identifier;
  in_buf.bufSizes = &in_size;
  in_buf.bufElSizes = &in_elem_size;

  void *out_ptr;
  int out_size, out_elem_size;

  out_ptr = output_data;
  out_size = _encoder_info.maxOutBufBytes;
  out_elem_size = _sampleBytes;
  out_buf.numBufs = 1;
  out_buf.bufs = &out_ptr;
  out_buf.bufferIdentifiers = &out_identifier;
  out_buf.bufSizes = &out_size;
  out_buf.bufElSizes = &out_elem_size;

  AACENC_ERROR result = aacEncEncode(_encoder_handle, &in_buf, &out_buf, &in_args, &out_args);

  if (result != AACENC_OK) {
      free(output_data);
      NSLog(@"FDK-AAC encode fail %i", result);
      return;
  }
  if (out_args.numOutBytes > 0) {

      // handle output_data

  } else {
      free(output_data);
  }
</code>```

答:
I think the CHANNEL_MODE is the original audio mode. not the aac mode

iOS don't support AAC-HE-V2.

You don't have to use fdk to convert the audio.

Here is the sample code.

https://developer.apple.com/library/content/samplecode/iPhoneACFileConvertTest/Introduction/Intro.html

I need some help too about fdk-aac ios. Here is the link. Hope you can take a look at it.
ios fdk-aac pcm to aac sample

Body:
I use the fdk v2.0.101 to encode the AAC-HE-V1 on iOS by xcode Version 8.0 (8A218a), but i always got the stereo channel aac data even if i set mono as the channel.

How to get the right channel while encoding AAC-HE-V1 by fdk?

PS: AAC-LC is OK. Tested on iPhone 6 with iOS 9.3.

The following is the code snippet:

initialization part

    UINT channels = 1;
    HANDLE_AACENCODER encoder_handle;
    AACENC_InfoStruct encoder_info;

    int HE_AACv1 = 5;

    TRANSPORT_TYPE transport_type = TT_MP4_ADTS;

    CHANNEL_MODE mode;

    switch (channels) {
        case 1: mode = MODE_1;       break;
        case 2: mode = MODE_2;       break;
        case 3: mode = MODE_1_2;     break;
        case 4: mode = MODE_1_2_1;   break;
        case 5: mode = MODE_1_2_2;   break;
        case 6: mode = MODE_1_2_2_1; break;
    }

    CheckError(aacEncOpen(&encoder_handle, 0, channels), @"Unable to open encoder : %i");
    CheckError(aacEncoder_SetParam(encoder_handle, AACENC_AOT, HE_AACv1), @"Unable to set the AOT : %i");
    CheckError(aacEncoder_SetParam(encoder_handle, AACENC_SAMPLERATE, 44100),
               @"Unable to set the sample rate : %i");
    CheckError(aacEncoder_SetParam(encoder_handle, AACENC_CHANNELMODE, mode),
               @"Unable to set the channel mode : %i");
    CheckError(aacEncoder_SetParam(encoder_handle, AACENC_CHANNELORDER, 1),
               @"Unable to set the wav channel order : %i");
    CheckError(aacEncoder_SetParam(encoder_handle, AACENC_BITRATE, 90000),
               @"Unable to set the bitrate : %i");
    CheckError(aacEncoder_SetParam(encoder_handle, AACENC_TRANSMUX, transport_type),
               @"Unable to set the ADTS transmux : %i");
    CheckError(aacEncoder_SetParam(encoder_handle, AACENC_AFTERBURNER, 1),
               @"Unable to set the afterburner mode : %i");
    CheckError(aacEncEncode(encoder_handle, NULL, NULL, NULL, NULL),
               @"Unable to initialize the encoder : %i");
    CheckError(aacEncInfo(encoder_handle, &encoder_info), @"Unable to get the encoder info : %i");

Enocoding part:

  AudioBuffer originBuffer = ...;

  AACENC_OutArgs out_args = { 0 };
  AACENC_ERROR err;

  int out_identifier = OUT_BITSTREAM_DATA;

  uint8_t *output_data = calloc(encoder_info.maxOutBufBytes, 1);

  int read = originBuffer.mDataByteSize;

  void *in_ptr = originBuffer.mData;
  int in_size = read;
  int in_elem_size = _sampleBytes;

  int in_identifier = IN_AUDIO_DATA;

  AACENC_InArgs in_args = { 0 };
  in_args.numInSamples = read / _sampleBytes;

  AACENC_BufDesc in_buf = { 0 }, out_buf = { 0 };
  in_buf.numBufs = 1;
  in_buf.bufs = &in_ptr;
  in_buf.bufferIdentifiers = &in_identifier;
  in_buf.bufSizes = &in_size;
  in_buf.bufElSizes = &in_elem_size;

  void *out_ptr;
  int out_size, out_elem_size;

  out_ptr = output_data;
  out_size = _encoder_info.maxOutBufBytes;
  out_elem_size = _sampleBytes;
  out_buf.numBufs = 1;
  out_buf.bufs = &out_ptr;
  out_buf.bufferIdentifiers = &out_identifier;
  out_buf.bufSizes = &out_size;
  out_buf.bufElSizes = &out_elem_size;

  AACENC_ERROR result = aacEncEncode(_encoder_handle, &in_buf, &out_buf, &in_args, &out_args);

  if (result != AACENC_OK) {
      free(output_data);
      NSLog(@"FDK-AAC encode fail %i", result);
      return;
  }
  if (out_args.numOutBytes > 0) {

      // handle output_data

  } else {
      free(output_data);
  }


问:
How to merge rows to one row in R based on a value in a Column
Firstoff I tried looking for a solution for this on stackoverflow. I might have missed it but I couldn't find or work out a code to do the following:

I want to merge the rows without NA's to one row based on column X1.

```<code>X1  Sex Age Language

1487252709  NA  22  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  male    NA  NA
1487252709  NA  NA  Nederlands
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252715  NA  32  NA
1487252715  NA  NA  NA
1487252715  NA  NA  NA
1487252715  male    NA  NA
1487252715  NA  NA  Nederlands
</code>```

My final result should show like this:

```<code>1487252709  male 22 Nederlands
1487252715  male 32 Nederlands
</code>```

It should be simple right? I think I'm overthinking or something but I just can't figure it out. I tried different functions like rbind and merge but it didn't gave the result that I wanted.

ps: this is my first post, so I hope it's informative enough.

答:
We can use summarise_each with na.omit after grouping by 'X1'

```<code>library(dplyr)
df1 %>%
    group_by(X1) %>%
    summarise_each(funs(na.omit))
# A tibble: 2 × 4
#          X1   Sex   Age   Language
#       <int> <chr> <int>      <chr>
#1 1487252709  male    22 Nederlands
#2 1487252715  male    32 Nederlands
</code>```

As @Uwe mentioned, the summarise_each would be deprecated, so in place use summarise_all

Body:
Firstoff I tried looking for a solution for this on stackoverflow. I might have missed it but I couldn't find or work out a code to do the following:

I want to merge the rows without NA's to one row based on column X1.

X1  Sex Age Language

1487252709  NA  22  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  male    NA  NA
1487252709  NA  NA  Nederlands
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252709  NA  NA  NA
1487252715  NA  32  NA
1487252715  NA  NA  NA
1487252715  NA  NA  NA
1487252715  male    NA  NA
1487252715  NA  NA  Nederlands

My final result should show like this:

1487252709  male 22 Nederlands
1487252715  male 32 Nederlands

It should be simple right? I think I'm overthinking or something but I just can't figure it out. I tried different functions like rbind and merge but it didn't gave the result that I wanted.

ps: this is my first post, so I hope it's informative enough.

Body:
We can use summarise_each with na.omit after grouping by 'X1'

library(dplyr)
df1 %>%
    group_by(X1) %>%
    summarise_each(funs(na.omit))
# A tibble: 2 × 4
#          X1   Sex   Age   Language
#       <int> <chr> <int>      <chr>
#1 1487252709  male    22 Nederlands
#2 1487252715  male    32 Nederlands

As @Uwe mentioned, the summarise_each would be deprecated, so in place use summarise_all


问:
System.Data.Entity.Infrastructure.DbUpdateException error even when i am not updating the id column
I am working on a project where I am using Entity framework to manipulate a DB on sql server 2014.
My code is the following:

```<code>private void BtnAddUser(object sender, EventArgs e)
    {
        var u = new User();
        u.username = txtBoxNewUser.Text;
        u.password = txtBoxNewPass.Text;
        u.rank = cmbBoxRank.GetItemText(this.cmbBoxRank.SelectedItem);
        using (var db = new ProjetPooEntities2())
        {
            db.Users.Add(u);
            db.SaveChanges();
        }

    }
</code>```

Please note that the code runs perfectly but it when i press the Add button to add the created user to the db an error shows on "db.saveChanges()" and it says:

System.Data.Entity.Infrastructure.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.'
  And the inner exception is:
  SqlException: Cannot insert explicit value for identity column in table 'User' when IDENTITY_INSERT is set to OFF.

I have set the identity column in the db to "id" and it is set to auto-increment by 1 starting from 1.
I have tried searching a lot for a solution but i found nothing.
Any help will be appreciated!!

答:
Try this:

SET IDENTITY_INSERT sometableWithIdentity ON

Body:
I am working on a project where I am using Entity framework to manipulate a DB on sql server 2014.
My code is the following:

private void BtnAddUser(object sender, EventArgs e)
    {
        var u = new User();
        u.username = txtBoxNewUser.Text;
        u.password = txtBoxNewPass.Text;
        u.rank = cmbBoxRank.GetItemText(this.cmbBoxRank.SelectedItem);
        using (var db = new ProjetPooEntities2())
        {
            db.Users.Add(u);
            db.SaveChanges();
        }

    }

Please note that the code runs perfectly but it when i press the Add button to add the created user to the db an error shows on "db.saveChanges()" and it says:

System.Data.Entity.Infrastructure.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.'
  And the inner exception is:
  SqlException: Cannot insert explicit value for identity column in table 'User' when IDENTITY_INSERT is set to OFF.

I have set the identity column in the db to "id" and it is set to auto-increment by 1 starting from 1.
I have tried searching a lot for a solution but i found nothing.
Any help will be appreciated!!


问:
Copy and paste format including colour of cells VBA Excel
```<code>wbTarget.Sheets("Sheet1").Range("A1:W79").Value = wb.Sheets(wsSource.Name).Range("A1:W79").Value
</code>```

I have this code which works pasting the values of wb.Sheets(wsSource.Name) to wbTarget sheets. However, it only pastes the value and not the format/color. How do I paste it including the fonts, color of cell.

答:
You need to use Copy, and PasteSpecial xlValues and PasteSpecial xlFormats.

```<code>' Copy
wb.Sheets(wsSource.Name).Range("A1:W79").Copy
' Paste Special
wbTarget.Sheets("Sheet1").Range("A1:W79").PasteSpecial xlValues
wbTarget.Sheets("Sheet1").Range("A1:W79").PasteSpecial xlFormats
</code>```

Read about Range.PasteSpecial here MSDN

ContentLicense: CC BY-SA 4.0

Body:
wbTarget.Sheets("Sheet1").Range("A1:W79").Value = wb.Sheets(wsSource.Name).Range("A1:W79").Value

I have this code which works pasting the values of wb.Sheets(wsSource.Name) to wbTarget sheets. However, it only pastes the value and not the format/color. How do I paste it including the fonts, color of cell.

Body:
You need to use Copy, and PasteSpecial xlValues and PasteSpecial xlFormats.

' Copy
wb.Sheets(wsSource.Name).Range("A1:W79").Copy
' Paste Special
wbTarget.Sheets("Sheet1").Range("A1:W79").PasteSpecial xlValues
wbTarget.Sheets("Sheet1").Range("A1:W79").PasteSpecial xlFormats

Read about Range.PasteSpecial here MSDN


问:
How to compare a string with the user's password?
I am trying to make an AppleScript program that asks the user to input their password and check if the text returned of the variable is equal to their real password. I am not trying to gain administrator privilege, just trying to retrieve the user's password and store it in a string. The reason why I bother to check the variable against the real user password is I don't want the user just enter something random. Are there any ways to do this?
Thank you!</p>

答:
In short, you can't. I have looked into this quite a bit, and there is no way you can get the users pass. If you could, you could destroy their computer with a simple script. The "Keychain Application" keeps the passwords far away from any kind of script. Sorry to disapoint. :(

if you could, it would be like this:

set realPassword to administrator password of (get system info)
set theirPassword to null
if realPassword is theirPassword then
say "yay"
else
say "nope"
end if


问:
HTML input arrays
```<code><input name="foo[]" ... >
</code>```

I've used these before, but I'm wondering what it is called and if there is a specification for it?

I couldn't find it in the HTML 4.01 Spec and results in various Google results only call it an "array" along with many PHP examples of processing the form data.

答:
Follow it...</p>

```<code><form action="index.php" method="POST">
<input type="number" name="array[]" value="1">
<input type="number" name="array[]" value="2">
<input type="number" name="array[]" value="3"> <!--taking array input by input name array[]-->
<input type="number" name="array[]" value="4">
<input type="submit" name="submit">
</form>
<?php
$a=$_POST['array'];
echo "Input :" .$a[3];  // Displaying Selected array Value
foreach ($a as $v) {
    print_r($v); //print all array element.
}
?>
</code>```

ContentLicense: CC BY-SA 2.5

Title: HTML input arrays

Body:
<input name="foo[]" ... >

I've used these before, but I'm wondering what it is called and if there is a specification for it?

I couldn't find it in the HTML 4.01 Spec and results in various Google results only call it an "array" along with many PHP examples of processing the form data.

Body:
Follow it...

<form action="index.php" method="POST">
<input type="number" name="array[]" value="1">
<input type="number" name="array[]" value="2">
<input type="number" name="array[]" value="3"> <!--taking array input by input name array[]-->
<input type="number" name="array[]" value="4">
<input type="submit" name="submit">
</form>
<?php
$a=$_POST['array'];
echo "Input :" .$a[3];  // Displaying Selected array Value
foreach ($a as $v) {
    print_r($v); //print all array element.
}
?>


问:
Any reason for a new project to use log4j instead of Logback?
I know that the common opinion is that Logback > log4j. Still, is there anything log4j does better than Logback? Any reason to use log4j over logback? How about the fact it only has 60 questions on stack overflow, so I presume a much smaller user base?</p>

答:
No matter what logging backend you choose, I suggest using slf4j as a frontend to it.  It may seem like overkill, but in these times of dependency injection and abstraction, having a simple layer between you and the logging impl isn't so crazy.

As noted by Ceki, Logback's public API actually is slf4j, so if you choose Logback and use it in the recommended way, you are already using slf4j.


问:
grouping images in a profile
I have a profile that shows profiles in a list. as shown in the image below.

users table

```<code> id    |  email  |  full_name  |  job_title  | bio |  profile_photo
</code>```

images table

```<code> image_id  | id  | artist_img
</code>```

CODE

```<code><?php

$db = dbconnect();
$stmt = $db->prepare('SELECT
 users.email,
 users.full_name,
 users.job_title,
 users.bio,
 users.profile_photo,
 images.id,
 images.artist_img
FROM users
INNER JOIN images ON users.id=images.id GROUP BY images.id');
$stmt->execute();
$result = $stmt->get_result();

while (($row = mysqli_fetch_assoc($result)) != false) {

        $id = $row['id'];
        $full_name = $row['full_name'];
        $email = $row['email'];
        $job_title = $row['job_title'];
        $bio = $row['bio'];
        $ProfilePhoto = $row['profile_photo'];
        $artist_img = $row['artist_img'];

        if (isset($ProfilePhoto) && ! empty($ProfilePhoto)) {
            $image = "$ProfilePhoto";
        } else {
            $image = "avatar.jpg";
       }

   echo "<div class='container team-wrap'>
           <div class='row'>
             <div class='col-md-6'>
                <img class='img-responsive' src='artist/$image'>
               </div>
                 <div class=\"col-md-6\">
                    <strong>$full_name<br>$job_title</strong>
                      <br>
                      <p>$bio</p>
                      <a href='mailto:$email' class='btn btn-info'>Contact Me</a>
                </div>
             </div>
          </div>

          <div class=\"container space team-wrap\">
           <div class=\"row\">
              <div class=\"col-lg-12\">
                    <div id=\"gallery-slider\" class=\"slider responsive\">
                      <div>";

                          echo"
                        <img src=\"gallery/$artist_img\" alt=\"\"></a>";

                      echo "</div>
                    </div>
                  <hr>
               </div>
            </div>
        </div>";
    }
 ?>
</code>```

Problem area

```<code>echo"<img src=\"gallery/$artist_img\" alt=\"\"></a>";
</code>```

The issue I am having is that it repeats the profile for each image if the user has 5 images  it will add 5 profiles 1 for each img.

and does not show the other users profile at all. show how it shows up is look at the image for example its got 4 images under profile 1 and it shows there profile pic.. well it repats all that info for each image I want the pics that have the same id as the user to show up as a slider like below..

and it also refuses to show the other profiles of other users.

答:
Change two lines you will get the result as expected

prepare('SELECT
    users.email,
    users.full_name,
    users.job_title,
    users.bio,
    users.profile_photo,
    images.id,
     GROUP_CONCAT(images.artist_img SEPARATOR '|') as artist_img
    FROM users
    INNER JOIN images ON users.id=images.id GROUP BY images.id');
    $stmt->execute();
    $result = $stmt->get_result();

    while (($row = mysqli_fetch_assoc($result)) != false) {

        $id = $row['id'];
        $full_name = $row['full_name'];
        $email = $row['email'];
        $job_title = $row['job_title'];
        $bio = $row['bio'];
        $ProfilePhoto = $row['profile_photo'];
        // Spliting as array
        $artist_imgs  = explode("|",$row['artist_img']);

        if (isset($ProfilePhoto) && ! empty($ProfilePhoto)) {
            $image = "$ProfilePhoto";
        } else {
            $image = "avatar.jpg";
       }

       echo "

                    $full_name
$job_title

$bio

                      Contact Me

                      ";

                          foreach($artist_imgs as $artist_img){
                          echo"";
                           }

                      echo "

        ";
    }
    ?>

Title: grouping images in a profile

Body:
I have a profile that shows profiles in a list. as shown in the image below.

users table

 id    |  email  |  full_name  |  job_title  | bio |  profile_photo

images table

 image_id  | id  | artist_img

CODE

<?php

$db = dbconnect();
$stmt = $db->prepare('SELECT
 users.email,
 users.full_name,
 users.job_title,
 users.bio,
 users.profile_photo,
 images.id,
 images.artist_img
FROM users
INNER JOIN images ON users.id=images.id GROUP BY images.id');
$stmt->execute();
$result = $stmt->get_result();

while (($row = mysqli_fetch_assoc($result)) != false) {

        $id = $row['id'];
        $full_name = $row['full_name'];
        $email = $row['email'];
        $job_title = $row['job_title'];
        $bio = $row['bio'];
        $ProfilePhoto = $row['profile_photo'];
        $artist_img = $row['artist_img'];

        if (isset($ProfilePhoto) && ! empty($ProfilePhoto)) {
            $image = "$ProfilePhoto";
        } else {
            $image = "avatar.jpg";
       }

   echo "

                    $full_name
$job_title

$bio

                      Contact Me

";

                          echo"
                        ";

                      echo "

";
    }
 ?>

Problem area

echo"";

The issue I am having is that it repeats the profile for each image if the user has 5 images  it will add 5 profiles 1 for each img.

and does not show the other users profile at all. show how it shows up is look at the image for example its got 4 images under profile 1 and it shows there profile pic.. well it repats all that info for each image I want the pics that have the same id as the user to show up as a slider like below..

and it also refuses to show the other profiles of other users.


问:
Clicked 2 Button At Once
Hello :) I Actually want to ask something
So my aim here is "If I click the button 1, the button 2 will be clicked too "

"Is it possible ? Click a one button so the other button will be clicked ?"

Here is my Code:

```<code>Button btn1 = sender as Button;

if (btn1 == button1){
    button2.PerformClick();
}
</code>```

It actually does not work it seems there is something wrong

答:
I suggest extracting methods.

Before:

```<code>private void button1_Click(object sender, EventArgs e)
{
  Routine 1 code ...
  Routine 2 code ... // <- do not copy yourself; copy + paste is evil!
}

private void button2_Click(object sender, EventArgs e)
{
  Routine 2 code ...
}
</code>```

After:

```<code>//TODO: think over the right name
private void Routine1()
{
  Routine 1 code ...
}

//TODO: think over the right name
private void Routine2()
{
  Routine 2 code ...
}

...

private void button1_Click(object sender, EventArgs e)
{
  Routine1();
  Routine2();
}

private void button2_Click(object sender, EventArgs e)
{
  Routine2();
}
</code>```

Title: Clicked 2 Button At Once

Body:
Hello :) I Actually want to ask something
So my aim here is "If I click the button 1, the button 2 will be clicked too "

"Is it possible ? Click a one button so the other button will be clicked ?"

Here is my Code:

Button btn1 = sender as Button;

if (btn1 == button1){
    button2.PerformClick();
}

It actually does not work it seems there is something wrong

Body:
I suggest extracting methods.

Before:

private void button1_Click(object sender, EventArgs e)
{
  Routine 1 code ...
  Routine 2 code ... // <- do not copy yourself; copy + paste is evil!
}

private void button2_Click(object sender, EventArgs e)
{
  Routine 2 code ...
}

After:

//TODO: think over the right name
private void Routine1()
{
  Routine 1 code ...
}

//TODO: think over the right name
private void Routine2()
{
  Routine 2 code ...
}

...

private void button1_Click(object sender, EventArgs e)
{
  Routine1();
  Routine2();
}

private void button2_Click(object sender, EventArgs e)
{
  Routine2();
}


答:
Unless you have a weird reason for doing this, don't!

You should prefer something like this :

```<code>void button1_Click(object sender, EventArgs e)
{
    DoWork1();
    DoWork2();
}

void button2_Click(object sender, EventArgs e)
{
    DoWork2();
}
</code>```

Title: Clicked 2 Button At Once

Body:
Unless you have a weird reason for doing this, don't!

You should prefer something like this :

void button1_Click(object sender, EventArgs e)
{
    DoWork1();
    DoWork2();
}

void button2_Click(object sender, EventArgs e)
{
    DoWork2();
}


问:
The following sections have been defined but have not been rendered for the layout page
This is an ASP.NET MVC 3 exception message. What it says? What should I do?

OK, I have this code:

```<code>@{
     Layout = "~/_Layout.cshtml";
     Page.Title = "Home";
}

@section meta{
    <meta name="keywords" content="" />
    <meta name="description" content="" />
}

<h2>Html Content Here</h2>

@section footer {
    <script src="http://code.jquery.com/jquery-latest.min.js" charset="utf-8"></script>
    <script type="text/javascript">
        $(document).ready(function() {
    });
    </script>
}
</code>```

答:
When I received this error I was trying to conditionally include a section in my layout when it was defined by the view. Here is the layout:

```<code>@if (IsSectionDefined("header"))
{
    RenderSection("header");
}
else
{
    Html.RenderPartial("_Header");
}
</code>```

I think @Jaider mentions this in his answer too, but you cannot place a RenderSection inside an if statement. The way to achieve my goal was to inverse the if and set the required parameter to false on the RenderSection method:

```<code>@RenderSection("header", false);
@if (!IsSectionDefined("header"))
{
    Html.RenderPartial("_Header");
}
</code>```

If no setion is defined, the first line wont do anything and the If statement ensures a default header is rendered when no section is defined.

Body:
This is an ASP.NET MVC 3 exception message. What it says? What should I do?

OK, I have this code:

@{
     Layout = "~/_Layout.cshtml";
     Page.Title = "Home";
}

@section meta{
    <meta name="keywords" content="" />
    <meta name="description" content="" />
}

Html Content Here

@section footer {

}

Body:
When I received this error I was trying to conditionally include a section in my layout when it was defined by the view. Here is the layout:

@if (IsSectionDefined("header"))
{
    RenderSection("header");
}
else
{
    Html.RenderPartial("_Header");
}

I think @Jaider mentions this in his answer too, but you cannot place a RenderSection inside an if statement. The way to achieve my goal was to inverse the if and set the required parameter to false on the RenderSection method:

@RenderSection("header", false);
@if (!IsSectionDefined("header"))
{
    Html.RenderPartial("_Header");
}

If no setion is defined, the first line wont do anything and the If statement ensures a default header is rendered when no section is defined.


问:
Call a method of the object which is created in another class
I have a little problem.

I have a 3 classes looks "like" this:

```<code>public class Gun{
    public void Shot(){
        // shoot code
    }

    public void RenderGun()
    {
        // render code
    }

    // more methods
}

public class GameManager
{
    Gun gun;

    public GameManager()
    {
        gun = new Gun();
    }

    // methods using GunClass methods.
}

public class HudScreen
{
    Gun gun;

    public HudScreen()
    {
        gun = new Gun();
    }

    public void GunShotButton()
    {
        gun.Shoot();
    }
}
</code>```

The problem is I have two Gun objects and i want to have one but use it in both classes HudScreen and GameManager.

So, if I create a new Gun object in GameManager, how to "call" this object from the HudScreen class?

Thanks, MM.

答:
GameManager constructor

```<code> public GameManager(Gun gun){
     this.gun = gun;
 }
</code>```

HudScreen constructor

```<code>public HudScreen(Gun gun){
      this.gun = gun;
 }
</code>```

From the main method where you create the Gun object you can pass it to the constructors of GameManager and HudScreen

```<code> public static void main() {
      Gun gun = new Gun();
      HudScreen hudScreen = new HudScreen(gun);
      GameManager gameManager = new GameManager(gun)
   }
</code>```

If you do not want to create GameManager and HudScreen in same method but still want to use same Gun object then you can do it this way
1. Initialize Gun object
2. on the GameManager and Hudscreen you can either pass it on constructor or you can directly pass it to method in theses classes.
e.g. Assume you want to keep the GameManager constructor receive the newly created Gun and pass the same gun to Hudscreen.GunShotButton. I hope you got a clue here -

```<code>public class Gun{
    public void Shot(){
        // shoot code
    }

    public void RenderGun()
    {
        // render code
    }

    // more methods
}

public class GameManager
{
    Gun gun;

    public GameManager(Gun gun)
    {
        this.gun =gun;
    }

    // methods using GunClass methods.
}

public class HudScreen
{
    public HudScreen()
    {
    }

    public void GunShotButton(Gun gun)
    {
        gun.Shoot();
    }
}
</code>```

Body:
I have a little problem.

I have a 3 classes looks "like" this:

public class Gun{
    public void Shot(){
        // shoot code
    }

    public void RenderGun()
    {
        // render code
    }

    // more methods
}

public class GameManager
{
    Gun gun;

    public GameManager()
    {
        gun = new Gun();
    }

    // methods using GunClass methods.
}

public class HudScreen
{
    Gun gun;

    public HudScreen()
    {
        gun = new Gun();
    }

    public void GunShotButton()
    {
        gun.Shoot();
    }
}

The problem is I have two Gun objects and i want to have one but use it in both classes HudScreen and GameManager.

So, if I create a new Gun object in GameManager, how to "call" this object from the HudScreen class?

Thanks, MM.

Body:
GameManager constructor

 public GameManager(Gun gun){
     this.gun = gun;
 }

HudScreen constructor

public HudScreen(Gun gun){
      this.gun = gun;
 }

From the main method where you create the Gun object you can pass it to the constructors of GameManager and HudScreen

 public static void main() {
      Gun gun = new Gun();
      HudScreen hudScreen = new HudScreen(gun);
      GameManager gameManager = new GameManager(gun)
   }

If you do not want to create GameManager and HudScreen in same method but still want to use same Gun object then you can do it this way
1. Initialize Gun object
2. on the GameManager and Hudscreen you can either pass it on constructor or you can directly pass it to method in theses classes.
e.g. Assume you want to keep the GameManager constructor receive the newly created Gun and pass the same gun to Hudscreen.GunShotButton. I hope you got a clue here -

public class Gun{
    public void Shot(){
        // shoot code
    }

    public void RenderGun()
    {
        // render code
    }

    // more methods
}

public class GameManager
{
    Gun gun;

    public GameManager(Gun gun)
    {
        this.gun =gun;
    }

    // methods using GunClass methods.
}

public class HudScreen
{
    public HudScreen()
    {
    }

    public void GunShotButton(Gun gun)
    {
        gun.Shoot();
    }
}


问:
Tomcat vs Jetty JNDI Lookup
I use Spring to configure my Java Web App and in my Spring configuration I obtain a datasource via JNDI for Jetty as follows:

<jee:jndi-lookup id="dataSource" jndi-name="jdbc/myDataSource" />

but this won't work with Tomcat.  With Tomcat I have to do this:

<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/myDataSource" />

Whats the best way to solve this?  I am already using JNDI as a way to externalize configuration, so I can't externalize my externalized configuration!  At the same time I absolutely loath the idea of having two separate Spring configuration files. HELP!!!

答:
After some experimenting, I figured out I could just force Jetty to use the same JNDI path as Tomcat.  The following snippet is from my jetty-env.xml file:

```<code> <New id="myDataSource" class="org.mortbay.jetty.plus.naming.Resource">
  <!-- We MUST specify the entire JNDI path here to force compliance with the Tomcat/J2EE convention -->
  <Arg>java:comp/env/jdbc/myDataSource</Arg>
  <Arg>
   <New class="com.atomikos.jdbc.nonxa.AtomikosNonXADataSourceBean">
    <Set name="uniqueResourceName">sbeDatabase</Set>
                 ...............
   </New>
  </Arg>
 </New>
</code>```

Not sure if this is ideal, but it works.

Update:

It works if you put your jetty-env.xml file inside the WAR...but for whatever reason, one you move this configuration outside the WAR and into a context fragment file in Jetty's "contexts" directory then it throws an exception:

Check it out:  http://jira.codehaus.org/browse/JETTY-273

Title: Tomcat vs Jetty JNDI Lookup

Body:
After some experimenting, I figured out I could just force Jetty to use the same JNDI path as Tomcat.  The following snippet is from my jetty-env.xml file:

 <New id="myDataSource" class="org.mortbay.jetty.plus.naming.Resource">
  <!-- We MUST specify the entire JNDI path here to force compliance with the Tomcat/J2EE convention -->
  <Arg>java:comp/env/jdbc/myDataSource</Arg>
  <Arg>
   <New class="com.atomikos.jdbc.nonxa.AtomikosNonXADataSourceBean">
    <Set name="uniqueResourceName">sbeDatabase</Set>
                 ...............
   </New>
  </Arg>
 </New>

Not sure if this is ideal, but it works.

Update:

It works if you put your jetty-env.xml file inside the WAR...but for whatever reason, one you move this configuration outside the WAR and into a context fragment file in Jetty's "contexts" directory then it throws an exception:

Check it out:  http://jira.codehaus.org/browse/JETTY-273


问:
jQuery get meta content in div
I need to get some data stored in a div and in a meta tag.

Here the div:

```<code><div id="qtip-0" class="qtip simcal-default-calendar simcal-event-bubble qtip-pos-tc qtip-fixed qtip-focus" tracking="false" role="alert" aria-live="polite" aria-atomic="false" aria-describedby="qtip-0-content" aria-hidden="false" data-qtip-id="0" >
<div class="qtip-tip">
    <canvas width="16" height="16" style="background-color: transparent !important; border: 0px !important; width: 8px; height: 8px;"></canvas>
</div>
<div class="qtip-content" id="qtip-0-content" aria-atomic="true">
    <div class="simcal-event-details simcal-tooltip-content" style="display: block; visibility: visible;">
        <div class="col-xs-12 title-event-container">
            <span class="simcal-event-title" itemprop="name">Riunione intenra Scali ferroviari</span>
        </div>
        <p><label>Luogo:</label><br>
        <span class="simcal-event-address simcal-event-start-location" itemprop="location" itemscope="" itemtype="http://schema.org/Place"><meta itemprop="name" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia"><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia</span></p>
        <div id="map">Mappa</div>
        <p>
            <a href="//maps.google.com?q=Palazzo+Marino+-+Comune+di+MilanoPiazza+della+Scala+2%2C+20121+Milano%2C+Italia" target="_blank">Vedi mappa ingrandita</a>
        </p>
    </div>
</div>
</code>```

I need to access to:

```<code><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">
</code>```

to get the content attribute.

Here what I have tried:

```<code>var currentEventAddress = $('#qtip-0 span').find('meta[itemprop="address"]').attr('content');

console.log(currentEventAddress);
</code>```

But I get undefined

答:
Find meta tag and its attr content direct.

var currentEventAddress = $('#qtip-0 span').find('meta').attr('content');
alert(currentEventAddress)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="qtip-0" class="qtip simcal-default-calendar simcal-event-bubble qtip-pos-tc qtip-fixed qtip-focus" tracking="false" role="alert" aria-live="polite" aria-atomic="false" aria-describedby="qtip-0-content" aria-hidden="false" data-qtip-id="0">
  <div class="qtip-tip">
    <canvas width="16" height="16" style="background-color: transparent !important; border: 0px !important; width: 8px; height: 8px;"></canvas>
  </div>
  <div class="qtip-content" id="qtip-0-content" aria-atomic="true">
    <div class="simcal-event-details simcal-tooltip-content" style="display: block; visibility: visible;">
      <div class="col-xs-12 title-event-container">
        <span class="simcal-event-title" itemprop="name">Riunione intenra Scali ferroviari</span>
      </div>
      <p>
        <label>Luogo:</label>
        <br>
        <span class="simcal-event-address simcal-event-start-location" itemprop="location" itemscope="" itemtype="http://schema.org/Place"><meta itemprop="name" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia"><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia</span></p>
      <div id="map">Mappa</div>
      <p>
        Vedi mappa ingrandita
      </p>
    </div>
  </div></code>```

Title: jQuery get meta content in div

Body:
I need to get some data stored in a div and in a meta tag.

Here the div:

    <canvas width="16" height="16" style="background-color: transparent !important; border: 0px !important; width: 8px; height: 8px;"></canvas>

            Riunione intenra Scali ferroviari

Luogo:

        <meta itemprop="name" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia"><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia

Mappa

            Vedi mappa ingrandita

I need to access to:

<meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">

to get the content attribute.

Here what I have tried:

var currentEventAddress = $('#qtip-0 span').find('meta[itemprop="address"]').attr('content');

console.log(currentEventAddress);

But I get undefined

Body:
Find meta tag and its attr content direct.

var currentEventAddress = $('#qtip-0 span').find('meta').attr('content');
alert(currentEventAddress)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="qtip-0" class="qtip simcal-default-calendar simcal-event-bubble qtip-pos-tc qtip-fixed qtip-focus" tracking="false" role="alert" aria-live="polite" aria-atomic="false" aria-describedby="qtip-0-content" aria-hidden="false" data-qtip-id="0">
  <div class="qtip-tip">
    <canvas width="16" height="16" style="background-color: transparent !important; border: 0px !important; width: 8px; height: 8px;"></canvas>
  </div>
  <div class="qtip-content" id="qtip-0-content" aria-atomic="true">
    <div class="simcal-event-details simcal-tooltip-content" style="display: block; visibility: visible;">
      <div class="col-xs-12 title-event-container">
        <span class="simcal-event-title" itemprop="name">Riunione intenra Scali ferroviari</span>
      </div>
      <p>
        <label>Luogo:</label>
        <br>
        <span class="simcal-event-address simcal-event-start-location" itemprop="location" itemscope="" itemtype="http://schema.org/Place"><meta itemprop="name" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia"><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia</span></p>
      <div id="map">Mappa</div>
      <p>
        <a href="//maps.google.com?q=Palazzo+Marino+-+Comune+di+MilanoPiazza+della+Scala+2%2C+20121+Milano%2C+Italia" target="_blank">Vedi mappa ingrandita</a>
      </p>
    </div>
  </div>


问:
PDF generated in Linux does not open in Windows - using enscript
My professor and I both use Linux to run some CFD codes, but both our PDF outputs from enscript do not open on Windows (which the TA uses to correct my assignment). The pdf's open without a problem in Linux however (my prof uses native Fedora and I use Ubuntu 16.04 on a virtual machine.

Here is the command line that I used:

```<code>enscript --color --pretty-print=cpp Assignment5.cpp --line-numbers -p Assignment5.pdf
</code>```

And I got this error when trying to open the PDF in windows:

Thanks!

答:
enscript actually creates a postscript file, not a PDF file. Most likely the PDF viewer used on the Linux systems in question also can display postscript files and, therefore, did not complain while the PDF viewer used on Windows can not. To actually create a PDF run ps2pdf on the enscript output.

On enscript

enscript (at least the GNU version) does not output PDF but a choice of other formats:

GNU Enscript converts ASCII files to PostScript, HTML, or RTF and stores generated output to a file or sends it directly to the printer.

According to its man page the actual output format is selected using the -W / --language option:

```<code>-W [lang], --language[=lang]
               Generate output for the language lang.  The possible values for
               lang are:

               PostScript
                       generate PostScript (default)

               html    generate HTML

               overstrike
                       generate overstrikes (line printers, less)

               rtf     generate RTF (Rich Text Format)

               ansi    generate ANSI terminal control codes
</code>```

Your enscript call does not include this option. Thus, by default postscript is generated.

How to create PDF

A common tool on Linux systems is ps2pdf which you can use to generate a PDF from your enscript postscript output:

ps2pdf - Convert PostScript to PDF using ghostscript

ps2pdf12 - Convert PostScript to PDF 1.2 (Acrobat 3-and-later compatible) using ghostscript

ps2pdf13 - Convert PostScript to PDF 1.3 (Acrobat 4-and-later compatible) using ghostscript

According to its man page it can be called with merely the source postscript and target PDF file names on the command line:

```<code>ps2pdf  [options...] {input.[e]ps|-} [output.pdf|-]
ps2pdf12  [options...] {input.[e]ps|-} [output.pdf|-]
ps2pdf13  [options...] {input.[e]ps|-} [output.pdf|-]
</code>```

You may have yet to install ghostscript to run it.

Body:
My professor and I both use Linux to run some CFD codes, but both our PDF outputs from enscript do not open on Windows (which the TA uses to correct my assignment). The pdf's open without a problem in Linux however (my prof uses native Fedora and I use Ubuntu 16.04 on a virtual machine.

Here is the command line that I used:

enscript --color --pretty-print=cpp Assignment5.cpp --line-numbers -p Assignment5.pdf

And I got this error when trying to open the PDF in windows:

Thanks!

Body:
enscript actually creates a postscript file, not a PDF file. Most likely the PDF viewer used on the Linux systems in question also can display postscript files and, therefore, did not complain while the PDF viewer used on Windows can not. To actually create a PDF run ps2pdf on the enscript output.

On enscript

enscript (at least the GNU version) does not output PDF but a choice of other formats:

GNU Enscript converts ASCII files to PostScript, HTML, or RTF and stores generated output to a file or sends it directly to the printer.

According to its man page the actual output format is selected using the -W / --language option:

-W [lang], --language[=lang]
               Generate output for the language lang.  The possible values for
               lang are:

               PostScript
                       generate PostScript (default)

               html    generate HTML

               overstrike
                       generate overstrikes (line printers, less)

               rtf     generate RTF (Rich Text Format)

               ansi    generate ANSI terminal control codes

Your enscript call does not include this option. Thus, by default postscript is generated.

How to create PDF

A common tool on Linux systems is ps2pdf which you can use to generate a PDF from your enscript postscript output:

ps2pdf - Convert PostScript to PDF using ghostscript

ps2pdf12 - Convert PostScript to PDF 1.2 (Acrobat 3-and-later compatible) using ghostscript

ps2pdf13 - Convert PostScript to PDF 1.3 (Acrobat 4-and-later compatible) using ghostscript

According to its man page it can be called with merely the source postscript and target PDF file names on the command line:

ps2pdf  [options...] {input.[e]ps|-} [output.pdf|-]
ps2pdf12  [options...] {input.[e]ps|-} [output.pdf|-]
ps2pdf13  [options...] {input.[e]ps|-} [output.pdf|-]

You may have yet to install ghostscript to run it.


问:
List passed by ref - help me explain this behaviour
Take a look at the following program:

```<code>class Test
{
    List<int> myList = new List<int>();

    public void TestMethod()
    {
        myList.Add(100);
        myList.Add(50);
        myList.Add(10);

        ChangeList(myList);

        foreach (int i in myList)
        {
            Console.WriteLine(i);
        }
    }

    private void ChangeList(List<int> myList)
    {
        myList.Sort();

        List<int> myList2 = new List<int>();
        myList2.Add(3);
        myList2.Add(4);

        myList = myList2;
    }
}
</code>```

I assumed myList would have passed by ref, and the output would

```<code>3
4
</code>```

The list is indeed "passed by ref", but only the sort function takes effect. The following statement myList = myList2; has no effect.

So the output is in fact:

```<code>10
50
100
</code>```

Can you help me explain this behavior? If indeed myList is not passed-by-ref (as it appears from myList = myList2 not taking effect), how does myList.Sort() take effect?

I was assuming even that statement to not take effect and the output to be:

```<code>100
50
10
</code>```

答:
You are passing a reference to the list, but your aren't passing the list variable by reference - so when you call ChangeList the value of the variable (i.e. the reference - think "pointer") is copied - and changes to the value of the parameter inside ChangeList aren't seen by TestMethod.

try:

```<code>private void ChangeList(ref List<int> myList) {...}
...
ChangeList(ref myList);
</code>```

This then passes a reference to the local-variable myRef (as declared in TestMethod); now, if you reassign the parameter inside ChangeList you are also reassigning the variable inside TestMethod.

Body:
Take a look at the following program:

class Test
{
    List<int> myList = new List<int>();

    public void TestMethod()
    {
        myList.Add(100);
        myList.Add(50);
        myList.Add(10);

        ChangeList(myList);

        foreach (int i in myList)
        {
            Console.WriteLine(i);
        }
    }

    private void ChangeList(List<int> myList)
    {
        myList.Sort();

        List<int> myList2 = new List<int>();
        myList2.Add(3);
        myList2.Add(4);

        myList = myList2;
    }
}

I assumed myList would have passed by ref, and the output would

3
4

The list is indeed "passed by ref", but only the sort function takes effect. The following statement myList = myList2; has no effect.

So the output is in fact:

10
50
100

Can you help me explain this behavior? If indeed myList is not passed-by-ref (as it appears from myList = myList2 not taking effect), how does myList.Sort() take effect?

I was assuming even that statement to not take effect and the output to be:

100
50
10

Body:
You are passing a reference to the list, but your aren't passing the list variable by reference - so when you call ChangeList the value of the variable (i.e. the reference - think "pointer") is copied - and changes to the value of the parameter inside ChangeList aren't seen by TestMethod.

try:

private void ChangeList(ref List<int> myList) {...}
...
ChangeList(ref myList);

This then passes a reference to the local-variable myRef (as declared in TestMethod); now, if you reassign the parameter inside ChangeList you are also reassigning the variable inside TestMethod.


问:
node js app calls the same function multiple times
Okay, so i have developing an application which will run 24/7. I only have one problem, if I write like this:

```<code>    setInterval(getWCProducts  , 1000*intervall);

    function getWCProducts(){
      //code
    }

    function test(){
        console.log("Hello!")
    }
    test()
</code>```

It will call test over and over again. It will print "Hello!" about every each secound. Why is the app behaving like this? Obviously the "real" function isn't just going to print "hello!". The real one is a "setup-function" which prepares the app before it starts looping and I can't have it running the setup function over and over again .

答:
Just don't start the loop until you complete the setup.

```<code>function main() {
     console.log("doing my main thing");
}

function setup() {
    console.log("doing my setup stuff ");
    setInterval(main, 1000);
}
</code>```

I'd like to point out that for most real-world applications of setInterval, you don't want to start the function calls one Interval apart, you really want to start each function one Interval after the previous call ended. If that's the case for you the modified code would look like this:

```<code>function main() {
     console.log("doing my main thing");
     setTimeout(main, 1000);
}

function setup() {
    console.log("doing my setup stuff ");
    main();
}
</code>```

Body:
Okay, so i have developing an application which will run 24/7. I only have one problem, if I write like this:

    setInterval(getWCProducts  , 1000*intervall);

    function getWCProducts(){
      //code
    }

    function test(){
        console.log("Hello!")
    }
    test()

It will call test over and over again. It will print "Hello!" about every each secound. Why is the app behaving like this? Obviously the "real" function isn't just going to print "hello!". The real one is a "setup-function" which prepares the app before it starts looping and I can't have it running the setup function over and over again .

Body:
Just don't start the loop until you complete the setup.

function main() {
     console.log("doing my main thing");
}

function setup() {
    console.log("doing my setup stuff ");
    setInterval(main, 1000);
}

I'd like to point out that for most real-world applications of setInterval, you don't want to start the function calls one Interval apart, you really want to start each function one Interval after the previous call ended. If that's the case for you the modified code would look like this:

function main() {
     console.log("doing my main thing");
     setTimeout(main, 1000);
}

function setup() {
    console.log("doing my setup stuff ");
    main();
}


问:
why is the enhanced for loop more efficient than the normal for loop
I read that the enhanced for loop is more efficient than the normal for loop here:

http://developer.android.com/guide/practices/performance.html#foreach

When I searched for the difference between their efficiency, all I found is: In case of normal for loop we need an extra step to find out the length of the array or size etc.,

```<code>for(Integer i : list){
   ....
}

int n = list.size();
for(int i=0; i < n; ++i){
  ....
}
</code>```

But is this the only reason, the enhanced for loop is better than the normal for loop?  In that case better use the normal for loop because of the slight complexity in understanding the enhanced for loop.

Check this for an interesting issue: http://www.coderanch.com/t/258147/java-programmer-SCJP/certification/Enhanced-Loop-Vs-Loop

Can any one please explain the internal implementation of these two types of for loops, or explain other reasons to use the enhanced for loop?

答:
all answers are good,and I think no more answers are needed, but I just want to point out that:

The enhanced for statement can be used only to obtain array elements

it cannot be used to modify elements.

If your program needs to modify elements, use the traditional counter-controlled for statement.

take a look

```<code>int[] array = { 1, 2, 3, 4, 5 };
for (int counter = 0; counter < array.length; counter++)
    array[counter] *= 2;
</code>```

We could not use the enhanced for statement because we’re modifying the array’s elements.

Body:
I read that the enhanced for loop is more efficient than the normal for loop here:

http://developer.android.com/guide/practices/performance.html#foreach

When I searched for the difference between their efficiency, all I found is: In case of normal for loop we need an extra step to find out the length of the array or size etc.,

for(Integer i : list){
   ....
}

int n = list.size();
for(int i=0; i < n; ++i){
  ....
}

But is this the only reason, the enhanced for loop is better than the normal for loop?  In that case better use the normal for loop because of the slight complexity in understanding the enhanced for loop.

Check this for an interesting issue: http://www.coderanch.com/t/258147/java-programmer-SCJP/certification/Enhanced-Loop-Vs-Loop

Can any one please explain the internal implementation of these two types of for loops, or explain other reasons to use the enhanced for loop?

Body:
all answers are good,and I think no more answers are needed, but I just want to point out that:

The enhanced for statement can be used only to obtain array elements

it cannot be used to modify elements.

If your program needs to modify elements, use the traditional counter-controlled for statement.

take a look

int[] array = { 1, 2, 3, 4, 5 };
for (int counter = 0; counter < array.length; counter++)
    array[counter] *= 2;

We could not use the enhanced for statement because we’re modifying the array’s elements.


问:
C# get cmd output just as shown in real cmd window
I have a BackgroundWorker thread that runs a cmd process and writes multiple commands to it. Some of the commands may take a while to complete so I want to show the user the cmd output of the progress.
My code for running the cmd commands looks like this:

```<code>private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    var startInfo = new ProcessStartInfo("cmd.exe")
    {
        UseShellExecute = false,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    };

    cmd = new Process { StartInfo = startInfo };

    cmd.OutputDataReceived += Cmd_OutputDataReceived;
    cmd.Start();
    cmd.BeginOutputReadLine();

    cmd.StandardInput.WriteLine($"cd {baseFolder}\\External Resources\\img files\\uboot");

    string[] commands = CmdCommands.GetUbootFlashCommands();
    foreach (var command in commands)
        cmd.StandardInput.WriteLine(command);

    cmd.StandardInput.WriteLine($"cd {baseFolder}\\External Resources\\img files\\android");
    commands = CmdCommands.GetKernelFlashCommands();
    foreach (var command in commands)
        cmd.StandardInput.WriteLine(command);

    cmd.StandardInput.WriteLine("exit");
    cmd.WaitForExit();
}

private void Cmd_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    Invoke(new Action(() =>
    {
        txtCmd.Text += e.Data + Environment.NewLine;
    }));
}
</code>```

But the cmd output loos nothing the real output as shown in a regular cmd window.
Here is how my output looks like:

```<code>Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\>cd C:\img files\uboot

C:\img files\uboot>fastboot flash XXX.bin

C:\img files\uboot>fastboot flash XXX.bin

C:\img files\uboot>cd C:\img files\android

C:\img files\android>fastboot flash kernel

C:\img files\android>fastboot flash system XXX.img

C:\img files\android>fastboot flash userdata XXX.img

C:\img files\android>fastboot flash cache XXX.img

C:\img files\android>exit
</code>```

And here is how output looks like when I open a cmd window and type in the commands:

```<code>Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\WINDOWS\system32>cd C:\img files\uboot

C:\img files\uboot>fastboot flash bl2 bl2.bin
target didn't report max-download-size
sending 'bl2' (14 KB)...
OKAY [  0.006s]
writing 'bl2'...
OKAY [  0.042s]
finished. total time: 0.052s

C:\img files\uboot>fastboot flash bootloader u-boot.bin
target didn't report max-download-size
sending 'bootloader' (275 KB)...
OKAY [  0.049s]
writing 'bootloader'...
OKAY [  0.046s]
finished. total time: 0.098s

C:\img files\uboot>cd C:\img files\android

C:\img files\android>fastboot flash kernel zImage-dtb
target didn't report max-download-size
sending 'kernel' (5099 KB)...
OKAY [  0.839s]
writing 'kernel'...
OKAY [  0.145s]
finished. total time: 0.988s

C:\img files\android>fastboot flash system system.img
target didn't report max-download-size
sending 'system' (426874 KB)...
OKAY [ 70.327s]
writing 'system'...
OKAY [ 30.963s]
finished. total time: 101.295s

C:\img files\android>fastboot flash userdata userdata.img
target didn't report max-download-size
sending 'userdata' (35680 KB)...
OKAY [  5.895s]
writing 'userdata'...
OKAY [  2.301s]
finished. total time: 8.200s

C:\img files\android>fastboot flash cache cache.img
target didn't report max-download-size
sending 'cache' (6248 KB)...
OKAY [  1.036s]
writing 'cache'...
OKAY [  0.380s]
finished. total time: 1.422s

C:\img files\android>
</code>```

How do I get this output in my my C# code???

答:
if the missing information is defined as an error in fastboot from some reason, RedirectStandardError should solve it

```<code> var startInfo = new ProcessStartInfo("cmd.exe")
    {
        UseShellExecute = false,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        CreateNoWindow = true,
        RedirectStandardError = true,
    };
</code>```

after that you would need to use the event of ErrorDataReceived to get the error messages.

```<code>cmd.ErrorDataReceived+=Cmd_OutputDataReceived
cmd.BeginErrorReadLine();
</code>```

Body:
I have a BackgroundWorker thread that runs a cmd process and writes multiple commands to it. Some of the commands may take a while to complete so I want to show the user the cmd output of the progress.
My code for running the cmd commands looks like this:

private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    var startInfo = new ProcessStartInfo("cmd.exe")
    {
        UseShellExecute = false,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    };

    cmd = new Process { StartInfo = startInfo };

    cmd.OutputDataReceived += Cmd_OutputDataReceived;
    cmd.Start();
    cmd.BeginOutputReadLine();

    cmd.StandardInput.WriteLine($"cd {baseFolder}\\External Resources\\img files\\uboot");

    string[] commands = CmdCommands.GetUbootFlashCommands();
    foreach (var command in commands)
        cmd.StandardInput.WriteLine(command);

    cmd.StandardInput.WriteLine($"cd {baseFolder}\\External Resources\\img files\\android");
    commands = CmdCommands.GetKernelFlashCommands();
    foreach (var command in commands)
        cmd.StandardInput.WriteLine(command);

    cmd.StandardInput.WriteLine("exit");
    cmd.WaitForExit();
}

private void Cmd_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    Invoke(new Action(() =>
    {
        txtCmd.Text += e.Data + Environment.NewLine;
    }));
}

But the cmd output loos nothing the real output as shown in a regular cmd window.
Here is how my output looks like:

Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\>cd C:\img files\uboot

C:\img files\uboot>fastboot flash XXX.bin

C:\img files\uboot>fastboot flash XXX.bin

C:\img files\uboot>cd C:\img files\android

C:\img files\android>fastboot flash kernel

C:\img files\android>fastboot flash system XXX.img

C:\img files\android>fastboot flash userdata XXX.img

C:\img files\android>fastboot flash cache XXX.img

C:\img files\android>exit

And here is how output looks like when I open a cmd window and type in the commands:

Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\WINDOWS\system32>cd C:\img files\uboot

C:\img files\uboot>fastboot flash bl2 bl2.bin
target didn't report max-download-size
sending 'bl2' (14 KB)...
OKAY [  0.006s]
writing 'bl2'...
OKAY [  0.042s]
finished. total time: 0.052s

C:\img files\uboot>fastboot flash bootloader u-boot.bin
target didn't report max-download-size
sending 'bootloader' (275 KB)...
OKAY [  0.049s]
writing 'bootloader'...
OKAY [  0.046s]
finished. total time: 0.098s

C:\img files\uboot>cd C:\img files\android

C:\img files\android>fastboot flash kernel zImage-dtb
target didn't report max-download-size
sending 'kernel' (5099 KB)...
OKAY [  0.839s]
writing 'kernel'...
OKAY [  0.145s]
finished. total time: 0.988s

C:\img files\android>fastboot flash system system.img
target didn't report max-download-size
sending 'system' (426874 KB)...
OKAY [ 70.327s]
writing 'system'...
OKAY [ 30.963s]
finished. total time: 101.295s

C:\img files\android>fastboot flash userdata userdata.img
target didn't report max-download-size
sending 'userdata' (35680 KB)...
OKAY [  5.895s]
writing 'userdata'...
OKAY [  2.301s]
finished. total time: 8.200s

C:\img files\android>fastboot flash cache cache.img
target didn't report max-download-size
sending 'cache' (6248 KB)...
OKAY [  1.036s]
writing 'cache'...
OKAY [  0.380s]
finished. total time: 1.422s

C:\img files\android>

How do I get this output in my my C# code???

Body:
if the missing information is defined as an error in fastboot from some reason, RedirectStandardError should solve it

 var startInfo = new ProcessStartInfo("cmd.exe")
    {
        UseShellExecute = false,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        CreateNoWindow = true,
        RedirectStandardError = true,
    };

after that you would need to use the event of ErrorDataReceived to get the error messages.

cmd.ErrorDataReceived+=Cmd_OutputDataReceived
cmd.BeginErrorReadLine();


问:
Batch insert causing failure
I have a task where I need to insert a lot of data into the database using hibernate. I am currently testing with inserting 500,000 entities which each have one relation, so 1,000,000 inserts in total.
Based on this guide I have created the following code which actually works. All the data is inserted and committed without errors.

```<code>import javax.annotation.Resource;
import javax.ejb.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.*;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.TransformerException;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;

@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class StackoverflowExample {
    @PersistenceContext
    private EntityManager entityManager;

    @Resource
    private SessionContext sessionContext;

    @EJB
    private XmlProcessorFactory xmlProcessorFactory;

    @EJB
    private TaskManagerBean taskManagerBean;

    public void processFile(String[] args, Task task) throws HeuristicRollbackException, RollbackException, HeuristicMixedException, SystemException, IOException, TransformerException, ParseException, XMLStreamException, NotSupportedException {
        UserTransaction tx = null;

        XmlProcessor instance = xmlProcessorFactory.getInstance(new File("data.xml"));

        XmlElement nextElement = instance.getNextElement();
        int i = 0;
        int batchSize = 50;
        entityManager.setProperty("hibernate.jdbc.batch_size", batchSize);
        tx = sessionContext.getUserTransaction();
        tx.begin();
        while (nextElement != null) {
            Entry entry = new Entry(nextElement.getUserReference(), nextElement.getXml());

            entityManager.persist(entry);

            if (i % batchSize == 0) {
                entityManager.flush();
                entityManager.clear();
            }

            nextElement = instance.getNextElement();
            i++;
        }

        task.setStatus(status);
        task.setEndTime(now());
        // This gives the OutOfMemoryError
        entityManager.merge(task);

        tx.commit();
    }
}
</code>```

This will fail in the line where I call taskManagerBean.update() with the following error:

```<code>2017-03-31 08:49:30,212 ERROR [org.jboss.as.ejb3.invocation] (EJB default - 3) WFLYEJB0034:
EJB Invocation failed on component TaskManagerBean for method public void
TaskManagerBean.update(Task,TaskStatus):
javax.ejb.EJBTransactionRolledbackException: org.hibernate.exception.GenericJDBCException:
could not load an entity: [Task#3]
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.handleInCallerTx(CMTTxInterceptor.java:159)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:256)
    ...
    at TaskManagerBean$$$view18.update(Unknown Source)
    at StoreEntriesBean.processFile(StoreEntriesBean.java:117)
    ...
    at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not load an entity: [Task#3]
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)
    ...
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:254)
    ... 104 more
Caused by: org.hibernate.exception.GenericJDBCException: could not load an entity: [Task#3]
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
    ...
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:1161)
    ... 135 more
Caused by: java.sql.SQLException: Error
    at org.jboss.jca.adapters.jdbc.WrappedConnection.checkException(WrappedConnection.java:1972)
    ...
    at org.hibernate.loader.Loader.loadEntity(Loader.java:2204)
    ... 155 more
Caused by: java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOfRange(Arrays.java:3664)
    ...
    at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)
</code>```

Runtime.getRuntime().freeMemory() returns 71540896 right before the error.

I start Wildfly with -Xmx2048m and a quick glance at memory usage shows that it only uses less than half of it.

I have tried committing the inserted Entries after every 1,000 inserts. This triggers the TaskManagerBean and it will fail the same way after a few updates.
In a few occasions I have also seen this error after I finished the huge batch job and the owning entity was to be updated.

I have tried with a file with just 5,000 entries and the entire process works fine.

Is this a bug in the MySQL driver or am I doing something wrong here?

答:
Trying to run batch processes through EJBs pretty much never works because you either run out of memory or the transaction times out.

It's one of the reasons that the "Batch Applications for
the Java Platform" (aka JSR-352) specification was developed.

WildFly 10 provides you with an implementation of this.

You can read more about it at Batch Applications in Java EE 7 - Undertanding JSR 352 Concepts: TOTD #192

Title: Batch insert causing failure

Body:
I have a task where I need to insert a lot of data into the database using hibernate. I am currently testing with inserting 500,000 entities which each have one relation, so 1,000,000 inserts in total.
Based on this guide I have created the following code which actually works. All the data is inserted and committed without errors.

import javax.annotation.Resource;
import javax.ejb.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.*;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.TransformerException;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;

@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class StackoverflowExample {
    @PersistenceContext
    private EntityManager entityManager;

    @Resource
    private SessionContext sessionContext;

    @EJB
    private XmlProcessorFactory xmlProcessorFactory;

    @EJB
    private TaskManagerBean taskManagerBean;

    public void processFile(String[] args, Task task) throws HeuristicRollbackException, RollbackException, HeuristicMixedException, SystemException, IOException, TransformerException, ParseException, XMLStreamException, NotSupportedException {
        UserTransaction tx = null;

        XmlProcessor instance = xmlProcessorFactory.getInstance(new File("data.xml"));

        XmlElement nextElement = instance.getNextElement();
        int i = 0;
        int batchSize = 50;
        entityManager.setProperty("hibernate.jdbc.batch_size", batchSize);
        tx = sessionContext.getUserTransaction();
        tx.begin();
        while (nextElement != null) {
            Entry entry = new Entry(nextElement.getUserReference(), nextElement.getXml());

            entityManager.persist(entry);

            if (i % batchSize == 0) {
                entityManager.flush();
                entityManager.clear();
            }

            nextElement = instance.getNextElement();
            i++;
        }

        task.setStatus(status);
        task.setEndTime(now());
        // This gives the OutOfMemoryError
        entityManager.merge(task);

        tx.commit();
    }
}

This will fail in the line where I call taskManagerBean.update() with the following error:

2017-03-31 08:49:30,212 ERROR [org.jboss.as.ejb3.invocation] (EJB default - 3) WFLYEJB0034:
EJB Invocation failed on component TaskManagerBean for method public void
TaskManagerBean.update(Task,TaskStatus):
javax.ejb.EJBTransactionRolledbackException: org.hibernate.exception.GenericJDBCException:
could not load an entity: [Task#3]
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.handleInCallerTx(CMTTxInterceptor.java:159)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:256)
    ...
    at TaskManagerBean$$$view18.update(Unknown Source)
    at StoreEntriesBean.processFile(StoreEntriesBean.java:117)
    ...
    at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not load an entity: [Task#3]
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)
    ...
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:254)
    ... 104 more
Caused by: org.hibernate.exception.GenericJDBCException: could not load an entity: [Task#3]
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
    ...
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:1161)
    ... 135 more
Caused by: java.sql.SQLException: Error
    at org.jboss.jca.adapters.jdbc.WrappedConnection.checkException(WrappedConnection.java:1972)
    ...
    at org.hibernate.loader.Loader.loadEntity(Loader.java:2204)
    ... 155 more
Caused by: java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOfRange(Arrays.java:3664)
    ...
    at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)

Runtime.getRuntime().freeMemory() returns 71540896 right before the error.

I start Wildfly with -Xmx2048m and a quick glance at memory usage shows that it only uses less than half of it.

I have tried committing the inserted Entries after every 1,000 inserts. This triggers the TaskManagerBean and it will fail the same way after a few updates.
In a few occasions I have also seen this error after I finished the huge batch job and the owning entity was to be updated.

I have tried with a file with just 5,000 entries and the entire process works fine.

Is this a bug in the MySQL driver or am I doing something wrong here?


问:
Get commits per branch in git "update" hook
Consider next pseudo-code thats create a required git log:

```<code>git checkout master
git checkout -b 123-test-branch-1
git commit -m "#123 b1 c1"
git commit -m "#123 b1 c2"
git push
git checkout master
git checkout -b 456-test-branch-2
git commit -m "#456 b2 c1"
git commit -m "#456 b2 c2"
git push
git checkout 123-test-branch-1
git merge 456-test-branch-2
git commit -m "#123 b1 c3"
git push
</code>```

In a real-world my update hook in remote git repository validates branch name and commit message formats. Branch name and commit message must contain issue number, for example, in 123-test-branch-1 and #123 b1 c1 the issue number is 123. When branch is pushed, hook extract issue number from branch and commit message and compare it. If they are not equal, hook exits with error.

This works great, when I push branch that has only "own" commits. But, git log example above, pushed branch 123-test-branch-1 has commits from merged branch 456-test-branch-2 so hook try to compare all commits from both branches only with pushed branch 123-test-branch-1 and exits with error because commits from 456-test-branch-2 has issue number 456, when 123 is expected.

To receive commits, I use git log --pretty=%s ${oldRef}..${newRef}, where oldRef and newRef is "update" hook arguments.

So, my question is how to solve this problem. Somehow group commits per branch, or filter commits from branch that pushed now (but if 456-test-branch-2 is local branch and never pushed and never validated, hook may skip invalid commits), or something else.

答:
The update hook does not get enough information: it cannot get a "global view" of the incoming hash IDs.  A pre- or post-receive hook does,1 and therefore does get enough information—at least for some purposes.

The biggest problem lies with new branch creation.  Suppose, for instance, an update is delivering the names refs/heads/a and refs/heads/b, where both names are new (their old hashes are the null hash), and refs/heads/a points to commit N2 and refs/heads/b points to commit N3 in this graph fragment:

```<code>                 N2   <-- A
                /
...--O--O--O--N1
                \
                 N3   <-- B
</code>```

where all the O commits are "old" (as in, were reachable from existing branch or tag names before) and the N commits are "new", as in were never reachable before, and are therefore listed by:

```<code>git rev-list refs/heads/a refs/heads/b --not \
    $(git for-each-ref --format '%(refname) |
        egrep -v '^(refs/heads/a|refs/heads/b)$')
</code>```

It's clear that these three N commits are "new", but to which branch should you assign N1?

There is no single right answer to this.  Commit N1 is on both branches, after all.

In any case, if you are more concerned with merge commits—as in, e.g.:

```<code>...O1--O2--N1--N2   <-- A
              /
...-O3--O4--N3    <-- B
</code>```

—you may want to use --first-parent traversals.  Here we can believe, based on these two branch-name updates (A moves from O2 to N2, B moves from O4 to N3)—that the first parent of N2 is N1 (it's possible, but difficult, to make this happen the other way around), so following --first-parents will "assign" commit N1 to A and not to B.  Again, if you are doing this from an update hook, rather than a pre- or post-receive hook, that may be the best you can do, since you do not get the information that both A and B are proposed to be updated.

1A post-receive hook is run after dropping all the locks, so it races against other operations that may update reference names.  A pre-receive hook gets all the proposed updates and therefore there is a big lock around reference name updates, so it's clearly safer, in some sense, to do this work there.

The drawback is that the pre-receive hook runs while holding a big lock, so anything "slow" it does, prohibits parallelism.

Body:
Consider next pseudo-code thats create a required git log:

git checkout master
git checkout -b 123-test-branch-1
git commit -m "#123 b1 c1"
git commit -m "#123 b1 c2"
git push
git checkout master
git checkout -b 456-test-branch-2
git commit -m "#456 b2 c1"
git commit -m "#456 b2 c2"
git push
git checkout 123-test-branch-1
git merge 456-test-branch-2
git commit -m "#123 b1 c3"
git push

In a real-world my update hook in remote git repository validates branch name and commit message formats. Branch name and commit message must contain issue number, for example, in 123-test-branch-1 and #123 b1 c1 the issue number is 123. When branch is pushed, hook extract issue number from branch and commit message and compare it. If they are not equal, hook exits with error.

This works great, when I push branch that has only "own" commits. But, git log example above, pushed branch 123-test-branch-1 has commits from merged branch 456-test-branch-2 so hook try to compare all commits from both branches only with pushed branch 123-test-branch-1 and exits with error because commits from 456-test-branch-2 has issue number 456, when 123 is expected.

To receive commits, I use git log --pretty=%s ${oldRef}..${newRef}, where oldRef and newRef is "update" hook arguments.

So, my question is how to solve this problem. Somehow group commits per branch, or filter commits from branch that pushed now (but if 456-test-branch-2 is local branch and never pushed and never validated, hook may skip invalid commits), or something else.

Body:
The update hook does not get enough information: it cannot get a "global view" of the incoming hash IDs.  A pre- or post-receive hook does,1 and therefore does get enough information—at least for some purposes.

The biggest problem lies with new branch creation.  Suppose, for instance, an update is delivering the names refs/heads/a and refs/heads/b, where both names are new (their old hashes are the null hash), and refs/heads/a points to commit N2 and refs/heads/b points to commit N3 in this graph fragment:

                 N2   <-- A
                /
...--O--O--O--N1
                \
                 N3   <-- B

where all the O commits are "old" (as in, were reachable from existing branch or tag names before) and the N commits are "new", as in were never reachable before, and are therefore listed by:

git rev-list refs/heads/a refs/heads/b --not \
    $(git for-each-ref --format '%(refname) |
        egrep -v '^(refs/heads/a|refs/heads/b)$')

It's clear that these three N commits are "new", but to which branch should you assign N1?

There is no single right answer to this.  Commit N1 is on both branches, after all.

In any case, if you are more concerned with merge commits—as in, e.g.:

...O1--O2--N1--N2   <-- A
              /
...-O3--O4--N3    <-- B

—you may want to use --first-parent traversals.  Here we can believe, based on these two branch-name updates (A moves from O2 to N2, B moves from O4 to N3)—that the first parent of N2 is N1 (it's possible, but difficult, to make this happen the other way around), so following --first-parents will "assign" commit N1 to A and not to B.  Again, if you are doing this from an update hook, rather than a pre- or post-receive hook, that may be the best you can do, since you do not get the information that both A and B are proposed to be updated.

1A post-receive hook is run after dropping all the locks, so it races against other operations that may update reference names.  A pre-receive hook gets all the proposed updates and therefore there is a big lock around reference name updates, so it's clearly safer, in some sense, to do this work there.

The drawback is that the pre-receive hook runs while holding a big lock, so anything "slow" it does, prohibits parallelism.


问:
Programming applications for Excel
As Excel is a great front-end UI, I want to build an application in Excel for interactive data analysis on our datasets.

On one side we can visualize the dataset or part of it using Excel. On the other hand, we can input some parameters and do sophislicated calculation and generate results.

I know that Excel is programable in VBA. The only BASIC I know is GW-BASIC. I'd more like to program in a C family language, also for performance's sake.

Could some suvery someone programming paradiams in Excel for me to choose? Thanks a lot!

答: Check out the Excel Developer Center on MSDN and Excel Solutions with Visual Studio for a starting point. </p>

Title: Programming applications for Excel


问:
How to translate labels and validation messages of forms within Django
Whenever I run:

```<code>$ ./manage.py makemessages -a -l es -e .py
</code>```

it only includes for translation, inside locale/es/LC_MESSAGES/django.po the strings I marked in MY apps, but I want to translate the strings marked as translateable in django forms, like this one: https://github.com/django/django/blob/master/django/contrib/auth/forms.py#L64-L84

Is there any way to get makemessages to translate labels and validation error messages of the Forms that come within Django without having to override such forms?

Thanks in advance for any help! :)

答:
If you are using a ModelForm, check out this answer for customizing labels and error messages:</p>

```<code>class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title', 'birth_date')
        labels = {
            'name': _('Writer'),
        }
        help_texts = {
            'name': _('Some useful help text.'),
        }
        error_messages = {
            'name': {
                'max_length': _("This writer's name is too long."),
            },
        }
</code>```

Body:
Whenever I run:

$ ./manage.py makemessages -a -l es -e .py

it only includes for translation, inside locale/es/LC_MESSAGES/django.po the strings I marked in MY apps, but I want to translate the strings marked as translateable in django forms, like this one: https://github.com/django/django/blob/master/django/contrib/auth/forms.py#L64-L84

Is there any way to get makemessages to translate labels and validation error messages of the Forms that come within Django without having to override such forms?

Thanks in advance for any help! :)

Body:
If you are using a ModelForm, check out this answer for customizing labels and error messages:

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title', 'birth_date')
        labels = {
            'name': _('Writer'),
        }
        help_texts = {
            'name': _('Some useful help text.'),
        }
        error_messages = {
            'name': {
                'max_length': _("This writer's name is too long."),
            },
        }