问:
Angular Dart build fails after upgrade Dart
I keep getting below error after I upgrade my Dart SDK. It seems webdev package has been upgraded from version 2.0.5 to 2.0.6. However I can't run my project now,

```<code>"G:\Program Files\Dart\dart-sdk\bin\pub.bat" global run webdev build --output=web:build
webdev could not run for this project.
This version of webdev does not support the `build_daemon` protocol used by your version of `build_runner`.
Please add a dev dependency on `build_daemon` with constraint: >=1.0.0 <2.0.0
Process finished with exit code 78
</code>```

I tried by following error messages hints but couldn't help!

And then, I generate a new project using Dart's project generator called stagehand, same there.

答:
I went through this last night.  Had to deactivate webdev

```<code>pub global deactivate webdev
</code>```

Then activate with a specific version (2.0.1 in my case)

```<code>pub global activate webdev 2.0.1
</code>```

I didn't try a different version as 2.0.1 was giving success and I wanted to get through completing my sample app.  There are some interesting reads about how 2.0.6 was supposed to fix some things, but it's requiring build_daemon version 1 whereas the default Angular dart sample I was using was requiring 0.5.0.

Body:
I keep getting below error after I upgrade my Dart SDK. It seems webdev package has been upgraded from version 2.0.5 to 2.0.6. However I can't run my project now,

"G:\Program Files\Dart\dart-sdk\bin\pub.bat" global run webdev build --output=web:build
webdev could not run for this project.
This version of webdev does not support the `build_daemon` protocol used by your version of `build_runner`.
Please add a dev dependency on `build_daemon` with constraint: >=1.0.0 <2.0.0
Process finished with exit code 78

I tried by following error messages hints but couldn't help!

And then, I generate a new project using Dart's project generator called stagehand, same there.

Body:
I went through this last night.  Had to deactivate webdev

pub global deactivate webdev

Then activate with a specific version (2.0.1 in my case)

pub global activate webdev 2.0.1

I didn't try a different version as 2.0.1 was giving success and I wanted to get through completing my sample app.  There are some interesting reads about how 2.0.6 was supposed to fix some things, but it's requiring build_daemon version 1 whereas the default Angular dart sample I was using was requiring 0.5.0.


来源: stackexchange

问:
SELECT query where two fields do NOT match not working
I have an VBA script which looks through a table that is a join of two different tables (a and b), where there may be fields that don't match between the table (table a is the original, table b is the same table, but a new export file).

The goal is to find which field(s) differ and update one field in the shared field with a list of fields that did not match between the two tables (a and b).

But one field is not passing its test.  I tried separately querying this table to see if I could use a simple SQL query to determine if Access was recognizing the difference.

I cannot understand why this is not working, as if I try other fields in the same manner, it returns the expected result.  I have confirmed that both fields are Short Text data type, both fields have the same "General Properties", "Lookup Properties" and the "Property Sheet" also matches not only between the two fields, but all other similar fields.

This query:

```<code>SELECT [a_Address 2], [b_Address 2]
FROM Staging_LOG_ExportDifferences
WHERE ID = 18;
</code>```

Results in:

```<code>[a_Address 2] = (NULL)
[b_Address 2] = xasdf
</code>```

But when I try this query:

```<code>SELECT *
FROM Staging_LOG_ExportDifferences
WHERE [a_Address 2] <> [b_Address 2];
</code>```

Results in:

```<code>No results
</code>```

答:
You can use this:

```<code>SELECT *
FROM Staging_LOG_ExportDifferences
WHERE Nz([a_Address 2],'') <> Nz([b_Address 2],'');
</code>```

This assumes that your addresses do not contain empty strings or at least you consider an empty string "equal" to NULL for your comparison purposes. I generally also use Trim to make sure any mistyped spaces do not cause issues:

```<code>Trim(Nz([a_Address 2],'')) <> Trim(Nz([b_Address 2],''))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an VBA script which looks through a table that is a join of two different tables (a and b), where there may be fields that don't match between the table (table a is the original, table b is the same table, but a new export file).

The goal is to find which field(s) differ and update one field in the shared field with a list of fields that did not match between the two tables (a and b).

But one field is not passing its test.  I tried separately querying this table to see if I could use a simple SQL query to determine if Access was recognizing the difference.

I cannot understand why this is not working, as if I try other fields in the same manner, it returns the expected result.  I have confirmed that both fields are Short Text data type, both fields have the same "General Properties", "Lookup Properties" and the "Property Sheet" also matches not only between the two fields, but all other similar fields.

This query:

SELECT [a_Address 2], [b_Address 2]
FROM Staging_LOG_ExportDifferences
WHERE ID = 18;

Results in:

[a_Address 2] = (NULL)
[b_Address 2] = xasdf

But when I try this query:

SELECT *
FROM Staging_LOG_ExportDifferences
WHERE [a_Address 2] <> [b_Address 2];

Results in:

No results

Body:
You can use this:

SELECT *
FROM Staging_LOG_ExportDifferences
WHERE Nz([a_Address 2],'') <> Nz([b_Address 2],'');

This assumes that your addresses do not contain empty strings or at least you consider an empty string "equal" to NULL for your comparison purposes. I generally also use Trim to make sure any mistyped spaces do not cause issues:

Trim(Nz([a_Address 2],'')) <> Trim(Nz([b_Address 2],''))


问:
How to iterate through array that is value of key in JSON
I have JSON file like this

```<code>[
 {
    "id": 1,
    "country": "Afghanistan",
    "city": ["Eshkashem","Fayzabad","Jurm","Khandud"]
 },
 {
    "id": 2,
    "country": "Italy",
    "city": ["Milano","Rome","Torino","Venezia"]
 }
</code>```

]

and I want to iterate through array placed in the city. Idea is to have two selects, where the first select is reserved for countries and the second is reserved for cities. Whenever the user selects a country, I want to populate the second select with a list of cities. Problem is that I receive only one array of all cities for that country. Here is my code:

export default class DiffCountries extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            contacts: [],
            selectedCountry: [],
            selectedCity: []
        }
    }

    onChangeHandler = (event) => {
      const test = CountriesData[event.target.value - 1];

        this.setState({
            selectedCountry: test,
            selectedCity: this.state.selectedCountry.city
        })

        console.log(this.state.selectedCity);
    }

    render() {
        const { contacts } = this.state;
        return (

            <select name="" id="" onChange={this.onChangeHandler}>
                            {CountriesData.map(item => {
                                const { id, country } = item;
                                return <option key={id} value={id}>{country}</option>
                            })}
                        </select>
                        <select name="" id="">
                            {this.state.selectedCountry !== undefined ?
                                <option value="">{this.state.selectedCountry.city}</option> :
                                null
                            }

                        </select>

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```

And here is the screenshot of my problem

Thank you in advance!

答:
Example:

const CountriesData = [
  {
    id: 1,
    country: 'Afghanistan',
    city: ['Eshkashem', 'Fayzabad', 'Jurm', 'Khandud'],
  },
  {
    id: 2,
    country: 'Italy',
    city: ['Milano', 'Rome', 'Torino', 'Venezia'],
  },
];

class DiffCountries extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedCountry: null,
    };
  }

  onChangeHandler = event => {
    const selectedCountry = CountriesData[event.target.value - 1];

    this.setState({
      selectedCountry,
    });
  };

  render() {
    const { selectedCountry } = this.state;
    return (

        <select
          name="country"
          defaultValue="country"
          onChange={this.onChangeHandler}
        >
          <option disabled value="country">
            Select country
          </option>
          {CountriesData.map(({ id, country }) => (
            <option key={id} value={id}>
              {country}
            </option>
          ))}
        </select>

        {selectedCountry && (
          <select name="city" defaultValue="city">
            <option disabled value="city">
              Select city
            </option>
            {selectedCountry.city.map(item => (
              <option key={item} value={item}>
                {item}
              </option>
            ))}
          </select>
        )}

    );
  }
}

ReactDOM.render(<DiffCountries />, document.getElementById('container'));
```

Body:
I have JSON file like this

[
 {
    "id": 1,
    "country": "Afghanistan",
    "city": ["Eshkashem","Fayzabad","Jurm","Khandud"]
 },
 {
    "id": 2,
    "country": "Italy",
    "city": ["Milano","Rome","Torino","Venezia"]
 }

]

and I want to iterate through array placed in the city. Idea is to have two selects, where the first select is reserved for countries and the second is reserved for cities. Whenever the user selects a country, I want to populate the second select with a list of cities. Problem is that I receive only one array of all cities for that country. Here is my code:

export default class DiffCountries extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            contacts: [],
            selectedCountry: [],
            selectedCity: []
        }
    }

    onChangeHandler = (event) => {
      const test = CountriesData[event.target.value - 1];

        this.setState({
            selectedCountry: test,
            selectedCity: this.state.selectedCountry.city
        })

        console.log(this.state.selectedCity);
    }

    render() {
        const { contacts } = this.state;
        return (

            <select name="" id="" onChange={this.onChangeHandler}>
                            {CountriesData.map(item => {
                                const { id, country } = item;
                                return <option key={id} value={id}>{country}</option>
                            })}
                        </select>
                        <select name="" id="">
                            {this.state.selectedCountry !== undefined ?
                                <option value="">{this.state.selectedCountry.city}</option> :
                                null
                            }

                        </select>

And here is the screenshot of my problem

Thank you in advance!

Body:
Example:

const CountriesData = [
  {
    id: 1,
    country: 'Afghanistan',
    city: ['Eshkashem', 'Fayzabad', 'Jurm', 'Khandud'],
  },
  {
    id: 2,
    country: 'Italy',
    city: ['Milano', 'Rome', 'Torino', 'Venezia'],
  },
];

class DiffCountries extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedCountry: null,
    };
  }

  onChangeHandler = event => {
    const selectedCountry = CountriesData[event.target.value - 1];

    this.setState({
      selectedCountry,
    });
  };

  render() {
    const { selectedCountry } = this.state;
    return (
      <div>
        <select
          name="country"
          defaultValue="country"
          onChange={this.onChangeHandler}
        >
          <option disabled value="country">
            Select country
          </option>
          {CountriesData.map(({ id, country }) => (
            <option key={id} value={id}>
              {country}
            </option>
          ))}
        </select>

        {selectedCountry && (
          <select name="city" defaultValue="city">
            <option disabled value="city">
              Select city
            </option>
            {selectedCountry.city.map(item => (
              <option key={item} value={item}>
                {item}
              </option>
            ))}
          </select>
        )}
      </div>
    );
  }
}

ReactDOM.render(<DiffCountries />, document.getElementById('container'));


问:
when read data from file: output {'y': array([-0.21]), 'x': array([1.63])}
I will read data from a file, I have only two number in file are(1.63 , -0.21),output :

```<code>{'y': array([-0.21]), 'x': array([1.63])}
</code>```

I need the output like this:

```<code>position = {'x':  1.63 , 'y' : -0.21}
</code>```

this my code:

```<code>import pandas as pd
import numpy as np
def read():

    data = pd.read_csv('distance.csv', skipinitialspace=True, header=None)

    x0, y0 = np.array(data.ix[:,0]), np.array(data.ix[:,1])

    position = {'x':  x0 , 'y' : y0}
    print position

if __name__ == '__main__':

    try:
        read()
    except KeyboardInterrupt:
        rospy.loginfo('Shutting down')
</code>```

please help me

Thank you in advance

答:
by this way worked but it is long

```<code>import pandas as pd
import numpy as np
import csv
def read():
    data_path = 'distance.csv'
    with open(data_path, 'r') as f:
        reader = csv.reader(f, delimiter=',')

        # get all the rows as a list
        data = list(reader)
        # transform data into numpy array
        data = np.array(data).astype(float)

    a = data[0]
    x0,y0 = a[0], a[1]

#
    position = {'x':  x0 , 'y' : y0}
    print position

if __name__ == '__main__':

    try:
        read()
    except KeyboardInterrupt:
        rospy.loginfo('Shutting down')
</code>```

output:

```<code>{'y': -0.21, 'x': 1.63}
</code>```

also this way is good:

```<code>import pandas as pd
import numpy as np
def read():

    data = np.genfromtxt('distance.csv', dtype=str, delimiter=',')

    x0, y0 = (data[0]), (data[1])

    position = {'x':  x0 , 'y' : y0}
    print position

if __name__ == '__main__':

    try:
        read()
    except KeyboardInterrupt:
        rospy.loginfo('Shutting down')
</code>```

output:

```<code>{'y': '-0.21', 'x': '1.63'}
</code>```

Body:
I will read data from a file, I have only two number in file are(1.63 , -0.21),output :

{'y': array([-0.21]), 'x': array([1.63])}

I need the output like this:

position = {'x':  1.63 , 'y' : -0.21}

this my code:

import pandas as pd
import numpy as np
def read():

    data = pd.read_csv('distance.csv', skipinitialspace=True, header=None)

    x0, y0 = np.array(data.ix[:,0]), np.array(data.ix[:,1])

    position = {'x':  x0 , 'y' : y0}
    print position

if __name__ == '__main__':

    try:
        read()
    except KeyboardInterrupt:
        rospy.loginfo('Shutting down')

please help me

Thank you in advance

Body:
by this way worked but it is long

import pandas as pd
import numpy as np
import csv
def read():
    data_path = 'distance.csv'
    with open(data_path, 'r') as f:
        reader = csv.reader(f, delimiter=',')

        # get all the rows as a list
        data = list(reader)
        # transform data into numpy array
        data = np.array(data).astype(float)

    a = data[0]
    x0,y0 = a[0], a[1]

#
    position = {'x':  x0 , 'y' : y0}
    print position

if __name__ == '__main__':

    try:
        read()
    except KeyboardInterrupt:
        rospy.loginfo('Shutting down')

output:

{'y': -0.21, 'x': 1.63}

also this way is good:

import pandas as pd
import numpy as np
def read():

    data = np.genfromtxt('distance.csv', dtype=str, delimiter=',')

    x0, y0 = (data[0]), (data[1])

    position = {'x':  x0 , 'y' : y0}
    print position

if __name__ == '__main__':

    try:
        read()
    except KeyboardInterrupt:
        rospy.loginfo('Shutting down')

output:

{'y': '-0.21', 'x': '1.63'}


问:
AutoPostBack not triggering Page_Load
I have an asp ddl setup like this:

```<code><asp:DropDownList ID="attendeeList2" runat="server" AutoPostBack="true" CssClass="tripRegistrationItem" />
</code>```

c#:

```<code>private void attendeeList2_SelectedIndexChanged(object sender, EventArgs e)
{
    _mission = new Mission(Int32.Parse(tripList.SelectedValue));
    person = new Person(int.Parse(attendeeList2.SelectedValue));
    attendeeLabel.Text = person.FullName.ToString();
    ClearInputs(tripRegistrationWizard.WizardSteps[1].Controls);
    LoadAttributes();
    SetInfo();
    }
</code>```

and:

```<code>private void InitializeComponent()
{
    attendeeList.SelectedIndexChanged += new EventHandler(attendeeList_SelectedIndexChanged);
    attendeeList2.SelectedIndexChanged += new EventHandler(attendeeList2_SelectedIndexChanged);
}
</code>```

What I am experiencing is that the attendeeList2_SelectedIndexChanged does indeed fire when the selected item of the DDL is changed, and the code within the method is executed, however a Page_Load, Page_Init, Page_PreRender... are NOT raised. It is almost like it isn't doing a true PostBack, yet it is running the code. I am needing to do some things in the Page_PreRender in that OnChange event, but can't figure out how to pull it off.

Can someone explain to me what I am doing wrong?

Thank you!

EDIT:

Here is the code that calls InitializeComponent():

```<code>override protected void OnInit(EventArgs e)
{
    //
    // CODEGEN: This call is required by the ASP.NET Web Form Designer.
    //
    InitializeComponent();
    base.OnInit(e);
}
</code>```

EDIT 2:
I just realized that the client side control I am working with is inside an Update Panel. It appears that when the control is within an Update Panel, it simply does an AJAX refresh, never raising the Page_Load, Page_Init... Once I pulled the control out of the update panel, it now triggers a full Post Back as I was expecting. Not sure why I couldn't find that tidbit of info while searching around, but now I know.

答:
Please try at the page directive to add:

```<code>autoeventwireup="true"
</code>```

some like:

```<code><%@ page language="C#" autoeventwireup="true" codefile="yourpage.aspx.cs" inherits="yourclass"%>
</code>```

ContentLicense: CC BY-SA 3.0

Title: AutoPostBack not triggering Page_Load

Body:
I have an asp ddl setup like this:

<asp:DropDownList ID="attendeeList2" runat="server" AutoPostBack="true" CssClass="tripRegistrationItem" />

c#:

private void attendeeList2_SelectedIndexChanged(object sender, EventArgs e)
{
    _mission = new Mission(Int32.Parse(tripList.SelectedValue));
    person = new Person(int.Parse(attendeeList2.SelectedValue));
    attendeeLabel.Text = person.FullName.ToString();
    ClearInputs(tripRegistrationWizard.WizardSteps[1].Controls);
    LoadAttributes();
    SetInfo();
    }

and:

private void InitializeComponent()
{
    attendeeList.SelectedIndexChanged += new EventHandler(attendeeList_SelectedIndexChanged);
    attendeeList2.SelectedIndexChanged += new EventHandler(attendeeList2_SelectedIndexChanged);
}

What I am experiencing is that the attendeeList2_SelectedIndexChanged does indeed fire when the selected item of the DDL is changed, and the code within the method is executed, however a Page_Load, Page_Init, Page_PreRender... are NOT raised. It is almost like it isn't doing a true PostBack, yet it is running the code. I am needing to do some things in the Page_PreRender in that OnChange event, but can't figure out how to pull it off.

Can someone explain to me what I am doing wrong?

Thank you!

EDIT:

Here is the code that calls InitializeComponent():

override protected void OnInit(EventArgs e)
{
    //
    // CODEGEN: This call is required by the ASP.NET Web Form Designer.
    //
    InitializeComponent();
    base.OnInit(e);
}

EDIT 2:
I just realized that the client side control I am working with is inside an Update Panel. It appears that when the control is within an Update Panel, it simply does an AJAX refresh, never raising the Page_Load, Page_Init... Once I pulled the control out of the update panel, it now triggers a full Post Back as I was expecting. Not sure why I couldn't find that tidbit of info while searching around, but now I know.

Body:
Please try at the page directive to add:

autoeventwireup="true"

some like:

<%@ page language="C#" autoeventwireup="true" codefile="yourpage.aspx.cs" inherits="yourclass"%>


问:
Migrate svn to git with space in branch name
I have a problem with a repo git that I want migrate to svn.
In this repo some branch was create with space in name. When I start command git svn cloneI have an error

```<code>fatal: Not a valid object name refs/remotes/origin/My branch
cat-file commit refs/remotes/origin/My branch: command returned error: 128
</code>```

I dump my repo with svndumpfilter exclude but problem is same.
I tried to clone in use ignore-path option, but is same !!

```<code>git svn clone --trunk=/Projet/trunk --branches=/Projet/branches --tags=/Projet/tags --authors-file=authors.txt file:///home/repo_svn/nom ../temp --ignore-path=".*(?:refs/remotes/origin/My branch|refs/remotes/origin/My%20branch)"
</code>```

Have you a solution ?
best regards

答:
This is probably too late for you, but on the off-chance anyone else hits this page, we had this problem too. The cause of the crash is indeed due to spaces in the branch name—specifically, the cmt_metadata() sub in git-svn.perl is calling cat-file with the unescaped branch name. I'd imagine it wouldn't be too hard to tweak this method to be more robust.

However.

While that was the cause of the crash, it turns out that even hitting this bit of code was a sign that we had something else wrong. Specifically, with multiple branches entries in the git config, the right-hand-sides of some of the rules were conflicting. We had something like

```<code>branches=/branches/a*:/refs/remotes/origin/*
branches=/branches/b*:/refs/remotes/origin/*
</code>```

which I think is the default config you get if you use --branches=/branches/a* --branches=/branches/b* in your init or clone command lines. Turns out the right hand side of those rules greatly prefer to be distinguishable as well as the left. So starting from scratch with a git svn init, then editing .git/config, adding:

```<code>branches=/branches/a*:/refs/remotes/origin/a/*
branches=/branches/b*:/refs/remotes/origin/b/*
</code>```

and kicking off a git svn fetch seems to have fixed it. Branches still have spaces, but no longer hit the code that doesn't like them.

Body:
I have a problem with a repo git that I want migrate to svn.
In this repo some branch was create with space in name. When I start command git svn cloneI have an error

fatal: Not a valid object name refs/remotes/origin/My branch
cat-file commit refs/remotes/origin/My branch: command returned error: 128

I dump my repo with svndumpfilter exclude but problem is same.
I tried to clone in use ignore-path option, but is same !!

git svn clone --trunk=/Projet/trunk --branches=/Projet/branches --tags=/Projet/tags --authors-file=authors.txt file:///home/repo_svn/nom ../temp --ignore-path=".*(?:refs/remotes/origin/My branch|refs/remotes/origin/My%20branch)"

Have you a solution ?
best regards

Body:
This is probably too late for you, but on the off-chance anyone else hits this page, we had this problem too. The cause of the crash is indeed due to spaces in the branch name—specifically, the cmt_metadata() sub in git-svn.perl is calling cat-file with the unescaped branch name. I'd imagine it wouldn't be too hard to tweak this method to be more robust.

However.

While that was the cause of the crash, it turns out that even hitting this bit of code was a sign that we had something else wrong. Specifically, with multiple branches entries in the git config, the right-hand-sides of some of the rules were conflicting. We had something like

branches=/branches/a*:/refs/remotes/origin/*
branches=/branches/b*:/refs/remotes/origin/*

which I think is the default config you get if you use --branches=/branches/a* --branches=/branches/b* in your init or clone command lines. Turns out the right hand side of those rules greatly prefer to be distinguishable as well as the left. So starting from scratch with a git svn init, then editing .git/config, adding:

branches=/branches/a*:/refs/remotes/origin/a/*
branches=/branches/b*:/refs/remotes/origin/b/*

and kicking off a git svn fetch seems to have fixed it. Branches still have spaces, but no longer hit the code that doesn't like them.


问:
Why does Thread.Sleep(0) fix my problems, and how to avoid it?
I'm working on a client server application.  At certain times, on certain machines, when there's more than 5 clients requesting data, it seems to reach a deadlock.  If I step in to debug the problem, then the program appears to be processing.  Simply setting a break point where I know the program is executing, and causing it to hit the breakpoint a few times causes it to finish. If I insert Thread.Sleep(0) at certain points in the code, mostly around some cpu intensive loops, it seems to pretty much totally resolve the problem.  The one problem that I have now is that if I call Thread.Sleep(0) too much, it can slow down the code.  If I don't call it enough, the code seems to be in deadlock.  Although I can verify that it isn't in deadlock because if I step into the code, it causes the problem to disappear, simply because I'm pausing a thread.

Is there a good way to track down exactly what is causing this.  It seems that it only happens on my laptop which is running Vista, but not on my desktop which is running Windows XP.  However, it's impossible to debug, because simply stepping into the code causes the problem to go away.  I've read comments that calling Thread.Sleep(0) is a bad practice, and shouldn't be necessary, and I don't like putting witchcraft type code into my applications that I don't understand why it has to be there.  Any pointers would be greatly appreciated.

[EDIT]
I can also verify that the code is still running when it is "deadlocked" because if I leave it long enough, it will finish, only the amount of time it takes is many orders of magnitude higher.  I mean like it's actually at least 100 times slower when it's in this "deadlocked" mode.  The CPU is pegged at 80-95%, so it is working, altough what it is doing is beyond me, because it's taking forever to complete the task.

[More Info]
Just because everybody here is insistent that it's a deadlock, I removed all the code that did any locking. There was only a couple lines of code that did any locking whatsoever. The threads work completely independantly for the most part, so it wasn't much work to remove the locking completely.  Still the problem persists.  There is no more synclocks in my code, no more mutex's no more stuff that I see see that would cause a deadlock, but the problem is still there.  And it's not deadlocked.  It runs, albeit very slowly, even though it's eating up all the processor resources.

答:
I think it is time for you to step away from the computer and up to the whiteboard.  Analyse how each element is locking and in what conditions it releases the lock carefully.  Five threads might be a difficult problem, so maybe see if just two threads can cause the same condition.  Something is not locking properly and you need to find where.

Unless your code is not worth this much effort, then leave the Thread.sleep() in there, because it doesnt really hurt your performance very much in the grand scheme of things.

OwnerDisplayName: Kibbee

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Kibbee

OwnerDisplayName: Karl


问:
Is an empty href valid?
One of our web developers uses the following html as a placeholder for styling a drop down list.

```<code><a href="" class="arrow"></a>
</code>```

Is this considered anchor tag valid?

Since there is no href value, it shows up as broken on some of our link checker reports.

答:
It is valid.

However, standard practice is to use href="#" or sometimes href="javascript:;".

Title: Is an empty href valid?

Body:
One of our web developers uses the following html as a placeholder for styling a drop down list.

Is this considered anchor tag valid?

Since there is no href value, it shows up as broken on some of our link checker reports.


问:
Bytes to string to bytes. Python 3
This is a simple question but I cannot seem to figure it out. I want to take the bytes outputted from a pickle.dumps() and convert it str and be able to convert it back to bytes compatible such that pickle.loads(string_thing) can recover the original object.

encoded = pickle.dumps(None)
string_encoded = to_string(encoded)
decoded = pickle.loads(safe_decoder(string_encoded))
```

I know one of the objections are going to be, "why do you need to do this?" Restrictions on allowed types.

答:
@deceze gives a good idea: use the module base64 with its functions .b64encode() and .b64decode().

Here is an example:

```<code>>>> 'Álñó@'
'Álñó@'
>>> 'Álñó@'.encode()
b'\xc3\x81l\xc3\xb1\xc3\xb3@'
>>> base64.b64encode('Álñó@'.encode())
b'w4Fsw7HDs0A='
>>> base64.b64encode('Álñó@'.encode()).decode()
'w4Fsw7HDs0A='
</code>```

Now you have a string in base64. For the reverse process:

```<code>>>> base64.b64encode('Álñó@'.encode()).decode().encode()
b'w4Fsw7HDs0A='
>>> base64.b64decode(base64.b64encode('Álñó@'.encode()).decode().encode())
b'\xc3\x81l\xc3\xb1\xc3\xb3@'
>>> base64.b64decode(base64.b64encode('Álñó@'.encode()).decode().encode()).decode()
'Álñó@'
</code>```

Would that work for you?

Example using pickle:

```<code>>>> original_obj = 456.5
>>> original_obj
456.5
>>> type(original_obj)
<class 'float'>
>>> intermediate_str = base64.b64encode(pickle.dumps(original_obj)).decode()
>>> intermediate_str
'gANHQHyIAAAAAAAu'

>>> new_obj = pickle.loads(base64.b64decode(intermediate_str.encode()))
>>> new_obj
456.5
>>> type(new_obj)
<class 'float'>

>>> original_obj == new_obj
True
</code>```

Title: Bytes to string to bytes. Python 3

Body:
This is a simple question but I cannot seem to figure it out. I want to take the bytes outputted from a pickle.dumps() and convert it str and be able to convert it back to bytes compatible such that pickle.loads(string_thing) can recover the original object.

encoded = pickle.dumps(None)
string_encoded = to_string(encoded)
decoded = pickle.loads(safe_decoder(string_encoded))

I know one of the objections are going to be, "why do you need to do this?" Restrictions on allowed types.

Body:
@deceze gives a good idea: use the module base64 with its functions .b64encode() and .b64decode().

Here is an example:

>>> 'Álñó@'
'Álñó@'
>>> 'Álñó@'.encode()
b'\xc3\x81l\xc3\xb1\xc3\xb3@'
>>> base64.b64encode('Álñó@'.encode())
b'w4Fsw7HDs0A='
>>> base64.b64encode('Álñó@'.encode()).decode()
'w4Fsw7HDs0A='

Now you have a string in base64. For the reverse process:

>>> base64.b64encode('Álñó@'.encode()).decode().encode()
b'w4Fsw7HDs0A='
>>> base64.b64decode(base64.b64encode('Álñó@'.encode()).decode().encode())
b'\xc3\x81l\xc3\xb1\xc3\xb3@'
>>> base64.b64decode(base64.b64encode('Álñó@'.encode()).decode().encode()).decode()
'Álñó@'

Would that work for you?

Example using pickle:

>>> original_obj = 456.5
>>> original_obj
456.5
>>> type(original_obj)
<class 'float'>
>>> intermediate_str = base64.b64encode(pickle.dumps(original_obj)).decode()
>>> intermediate_str
'gANHQHyIAAAAAAAu'

>>> new_obj = pickle.loads(base64.b64decode(intermediate_str.encode()))
>>> new_obj
456.5
>>> type(new_obj)
<class 'float'>

>>> original_obj == new_obj
True


问:
Nativescript angular radListView `itemSelecting` example
Is there anyone knows a link which shows an example on how to implement itemSelecting in Nativescript angular RadListViewhttps://docs.nativescript.org/ns-ui-api-reference/classes/radlistview#itemselecting?

Because I can't find any example. Thank you.

答:
HTML

```<code><RadListView class="list-group" [items]="countries" selectionBehavior="Press"
    multipleSelection="true" (itemSelecting)="onItemSelecting($event)"
    (itemDeselecting)="onItemSelecting($event)">
    <ng-template let-country="item">
        <FlexboxLayout flexDirection="row" class="list-group-item">
            <Image [src]="country.imageSrc" class="thumb img-circle"></Image>
            <Label [text]="country.name" class="list-group-item-heading"
                verticalAlignment="center" style="width: 60%"></Label>
        </FlexboxLayout>
    </ng-template>
</RadListView>
</code>```

TS

```<code>import { ListViewEventData } from "nativescript-ui-listview"
import { Component } from "@angular/core";

@Component({
    selector: "Home",
    moduleId: module.id,
    templateUrl: "./home.component.html",
    styleUrls: ["./home.component.css"]
})
export class HomeComponent {
    countries: { name: string, imageSrc: string }[] = [
        { name: "Australia", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/au.png" },
        { name: "Belgium", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/be.png" },
        { name: "Bulgaria", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/bg.png" },
        { name: "Canada", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/ca.png" },
        { name: "Switzerland", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/ch.png" },
        { name: "China", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/cn.png" },
        { name: "Czech Republic", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/cz.png" },
        { name: "Germany", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/de.png" },
        { name: "Spain", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/es.png" },
        { name: "Ethiopia", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/et.png" },
        { name: "Croatia", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/hr.png" },
        { name: "Hungary", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/hu.png" },
        { name: "Italy", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/it.png" },
        { name: "Jamaica", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/jm.png" },
        { name: "Romania", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/ro.png" },
        { name: "Russia", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/ru.png" },
        { name: "United States", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/us.png" },
    ];

    onItemSelecting(args: ListViewEventData): void {
        console.log(args.view.bindingContext.name);
        args.returnValue = args.index > 5;
    }
}
</code>```

Note: It seems to be buggy, at least on Android. Second tap fails to fire itemSelecting event and marks the item as selected. A workaround could be found at nativescript-ui-feedback/issues/181

Body:
HTML

<RadListView class="list-group" [items]="countries" selectionBehavior="Press"
    multipleSelection="true" (itemSelecting)="onItemSelecting($event)"
    (itemDeselecting)="onItemSelecting($event)">
    <ng-template let-country="item">
        <FlexboxLayout flexDirection="row" class="list-group-item">
            <Image [src]="country.imageSrc" class="thumb img-circle"></Image>
            <Label [text]="country.name" class="list-group-item-heading"
                verticalAlignment="center" style="width: 60%"></Label>
        </FlexboxLayout>
    </ng-template>
</RadListView>

TS

import { ListViewEventData } from "nativescript-ui-listview"
import { Component } from "@angular/core";

@Component({
    selector: "Home",
    moduleId: module.id,
    templateUrl: "./home.component.html",
    styleUrls: ["./home.component.css"]
})
export class HomeComponent {
    countries: { name: string, imageSrc: string }[] = [
        { name: "Australia", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/au.png" },
        { name: "Belgium", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/be.png" },
        { name: "Bulgaria", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/bg.png" },
        { name: "Canada", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/ca.png" },
        { name: "Switzerland", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/ch.png" },
        { name: "China", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/cn.png" },
        { name: "Czech Republic", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/cz.png" },
        { name: "Germany", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/de.png" },
        { name: "Spain", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/es.png" },
        { name: "Ethiopia", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/et.png" },
        { name: "Croatia", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/hr.png" },
        { name: "Hungary", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/hu.png" },
        { name: "Italy", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/it.png" },
        { name: "Jamaica", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/jm.png" },
        { name: "Romania", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/ro.png" },
        { name: "Russia", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/ru.png" },
        { name: "United States", imageSrc: "https://play.nativescript.org/dist/assets/img/flags/us.png" },
    ];

    onItemSelecting(args: ListViewEventData): void {
        console.log(args.view.bindingContext.name);
        args.returnValue = args.index > 5;
    }
}

Note: It seems to be buggy, at least on Android. Second tap fails to fire itemSelecting event and marks the item as selected. A workaround could be found at nativescript-ui-feedback/issues/181


问:
Why does this code change only some elements of the list and not the others?
I don't understand why the result of the following code is [1,[2,5]] and not [3,[2,5]]. Why is the element in the sublist changed but the element outside of the sublist isn't?

I'm new to Python so maybe I don't see something which should be very obvious. I've read about deep and shallow copies, but it didn't help.

a = [1,[2,3]]
b = a[:]
a[0] = 3
a[1][1] = 5
print(b)
```

I created the list slice on line 2. But since it has no start or end values, the slice equals the entire list, right? Then why does 3 change to 5, but 1 stays the same?

答:
Because, in Python, each list is an independent object.
You can do a deep copy using the module 'copy' to solve this specific problem.

```<code>import copy
a = [1,[2,3]]
b = copy.deepcopy(a)
a[0] = 3
a[1][1] = 5
print(b)
</code>```

Result: [1, [2, 3]]

Body:
I don't understand why the result of the following code is [1,[2,5]] and not [3,[2,5]]. Why is the element in the sublist changed but the element outside of the sublist isn't?

I'm new to Python so maybe I don't see something which should be very obvious. I've read about deep and shallow copies, but it didn't help.

a = [1,[2,3]]
b = a[:]
a[0] = 3
a[1][1] = 5
print(b)

I created the list slice on line 2. But since it has no start or end values, the slice equals the entire list, right? Then why does 3 change to 5, but 1 stays the same?

Body:
Because, in Python, each list is an independent object.
You can do a deep copy using the module 'copy' to solve this specific problem.

import copy
a = [1,[2,3]]
b = copy.deepcopy(a)
a[0] = 3
a[1][1] = 5
print(b)

Result: [1, [2, 3]]


问:
How to write data to file on starting
I am using below code to write data in a file.

```<code>public static void writeDataToFile(final String fileName, final String fileContents) {
    try {
        File file = new File(Environment.getExternalStorageDirectory() + fileName);

        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter writer = new FileWriter(file, true);
        writer.append(fileContents);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        LogUtility.logInfo(TAG, e.getMessage());
    }
}
</code>```

Here FileWriter Constructor takes boolean that means it concatenates data to file every time to the last data. What I am trying to get is to have a file that has logs of my activities I am performing. And I am achieving via above mentioned code. but the problem is it is always concatenating logs to the last of data every time. What I want is to write new log on starting ever time.By this I will not have search file to the bottom for last log. It will be on start evyer time. Any help

答:
If file does not exist, you have written code to create a new file.
Likewise, if file exists, you can delete the file, and create new one

Before deleting old file, you can copy contents into a String, and add them to content that is to be written in file before writing into file.

```<code>StringBuilder contentToWrite = new StringBuilder();
contentToWrite.append(newContent);
if (!file.exists()) {
    file.createNewFile();
} else {
    FileReader fileReader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    String line = bufferedReader.readLine();
    StringBuilder sb = new StringBuilder();
    while (line != null) {
        sb.append(line).append("\n");
        line = bufferedReader.readLine();
    }
    contentToWrite.append("\n\n" + sb);
    file.delete();
    file.createNewFile();
}
FileWriter writer = new FileWriter(file, true);
writer.append(contentToWrite);
writer.flush();
writer.close();
</code>```

PS: Don't forget to close FileReader and BufferedReader in a finally statement.

Title: How to write data to file on starting

Body:
I am using below code to write data in a file.

public static void writeDataToFile(final String fileName, final String fileContents) {
    try {
        File file = new File(Environment.getExternalStorageDirectory() + fileName);

        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter writer = new FileWriter(file, true);
        writer.append(fileContents);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        LogUtility.logInfo(TAG, e.getMessage());
    }
}

Here FileWriter Constructor takes boolean that means it concatenates data to file every time to the last data. What I am trying to get is to have a file that has logs of my activities I am performing. And I am achieving via above mentioned code. but the problem is it is always concatenating logs to the last of data every time. What I want is to write new log on starting ever time.By this I will not have search file to the bottom for last log. It will be on start evyer time. Any help

Body:
If file does not exist, you have written code to create a new file.
Likewise, if file exists, you can delete the file, and create new one

Before deleting old file, you can copy contents into a String, and add them to content that is to be written in file before writing into file.

StringBuilder contentToWrite = new StringBuilder();
contentToWrite.append(newContent);
if (!file.exists()) {
    file.createNewFile();
} else {
    FileReader fileReader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    String line = bufferedReader.readLine();
    StringBuilder sb = new StringBuilder();
    while (line != null) {
        sb.append(line).append("\n");
        line = bufferedReader.readLine();
    }
    contentToWrite.append("\n\n" + sb);
    file.delete();
    file.createNewFile();
}
FileWriter writer = new FileWriter(file, true);
writer.append(contentToWrite);
writer.flush();
writer.close();

PS: Don't forget to close FileReader and BufferedReader in a finally statement.


问:
How composer check php version?
I just wondering how composer check which php to use when check for requirements. I use MacOS and in terminal type:

```<code>composer require phpunit/phpunit
</code>```

the result is something like:

```<code>Problem 1
- phpunit/phpunit 5.0.4 requires php >=5.6 -> your PHP version (5.5.27) or "config.platform.php" value does not satisfy that requirement....
</code>```

When I check php version:

```<code>php -v
</code>```

The result is:

PHP 5.6.10 (cli) (built: Jun 12 2015 14:08:56) Copyright (c) 1997-2015
  The PHP Group Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend
  Technologies
      with Xdebug v2.2.5, Copyright (c) 2002-2014, by Derick Rethans

Which is:

```<code>which php
</code>```

php: aliased to /Applications/MAMP/bin/php/php5.6.10/bin/php

Can someone explain this. Thanks in advance!

答:
Composer can tell you what version of PHP it's running on, if you specify debug verbosity -vvv.

I like to run it with the about command, since the output is relatively short.

```<code>composer -vvv about
</code>```

Example output:

...
     Running 1.8.5 (2019-04-09 17:46:47) with PHP 7.3.5 on Darwin / 18.6.0
     ...

Edit:
This has gotten more interest than I expected, so here's a version with cleaner output:

```<code>composer -vvv about 2>&1 | grep "PHP"
</code>```

Title: How composer check php version?

Body:
I just wondering how composer check which php to use when check for requirements. I use MacOS and in terminal type:

composer require phpunit/phpunit

the result is something like:

Problem 1
- phpunit/phpunit 5.0.4 requires php >=5.6 -> your PHP version (5.5.27) or "config.platform.php" value does not satisfy that requirement....

When I check php version:

php -v

The result is:

PHP 5.6.10 (cli) (built: Jun 12 2015 14:08:56) Copyright (c) 1997-2015
  The PHP Group Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend
  Technologies
      with Xdebug v2.2.5, Copyright (c) 2002-2014, by Derick Rethans

Which is:

which php

php: aliased to /Applications/MAMP/bin/php/php5.6.10/bin/php

Can someone explain this. Thanks in advance!

Body:
Composer can tell you what version of PHP it's running on, if you specify debug verbosity -vvv.

I like to run it with the about command, since the output is relatively short.

composer -vvv about

Example output:

...
     Running 1.8.5 (2019-04-09 17:46:47) with PHP 7.3.5 on Darwin / 18.6.0
     ...

Edit:
This has gotten more interest than I expected, so here's a version with cleaner output:

composer -vvv about 2>&1 | grep "PHP"


问:
Failed to marshal EJB parameters --- IllegalArgumentException: Can not set org.apache.commons.collections.FastHashMap field
I'm getting the below error while trying to save a search results using the Remote interface for SearchFacade.java

```<code>"Failed to marshal EJB parameters"
</code>```

Can not set org.apache.commons.collections.FastHashMap field
  org.apache.commons.validator.Field.hMsgs to
  org.apache.commons.collections.FastHashMap at
  sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:146)
  at

I'm Using struts 1.1, EJB 2.1 using xdoclet 1.2.3 jars for generating the dependency files.(which is inevitable to use), Where my Local,Home interfaces are being generated using Xdoclet..

I'm also using Java 6, Jboss EAP 6.1 Alpha in my project.

Note: The same code works fine when running in Jboss 4.0

So wonder is my remote calling is correct.

Any help is welcome.

Error Logs

java.lang.RuntimeException: JBAS014154: Failed to marshal EJB parameters at org.jboss.as.ejb3.remote.LocalEjbReceiver.clone(LocalEjbReceiver.java:270) at org.jboss.as.ejb3.remote.LocalEjbReceiver.clone(LocalEjbReceiver.java:259) at org.jboss.as.ejb3.remote.LocalEjbReceiver.processInvocation(LocalEjbReceiver.java:170) at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:181) at org.jboss.ejb.client.EJBHomeCreateInterceptor.handleInvocation(EJBHomeCreateInterceptor.java:79) at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:183) at org.jboss.ejb.client.TransactionInterceptor.handleInvocation(TransactionInterceptor.java:42) at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:183) at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:125) at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:183) at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:177) at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:161) at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:124) at $Proxy25.saveSearch(Unknown Source) at com.web.history.SearchFormDelegate.saveSearch(SearchFormDelegate.java:177) at com.history.SaveSearchAction.createNewSavedSearch(SaveSearchAction.java:109) at com.history.SaveSearchAction.executeSynchronized(SaveSearchAction.java:296) at com.dispatch.SynchronizedAction.execute(SynchronizedAction.java:206) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432) at javax.servlet.http.HttpServlet.service(HttpServlet.java:754) at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:295) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) at com.security.AuthenticationFilter.doFilter(AuthenticationFilter.java:672) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) at com.planetj.servlet.filter.compression.CompressingFilter.doFilter(CompressingFilter.java:270) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:149) at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:169) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:145) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:97) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:102) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:336) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:653) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:920) at java.lang.Thread.run(Thread.java:662) Caused by: java.lang.IllegalArgumentException: Can not set org.apache.commons.collections.FastHashMap field org.apache.commons.validator.Field.hMsgs to org.apache.commons.collections.FastHashMap at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:146) at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:150) at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:63) at java.lang.reflect.Field.set(Field.java:657) at org.jboss.marshalling.cloner.SerializingCloner.storeFields(SerializingCloner.java:368) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:313) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner.cloneFields(SerializingCloner.java:348) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:309) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner$StepObjectInput.doReadObject(SerializingCloner.java:836) at org.jboss.marshalling.AbstractObjectInput.readObject(AbstractObjectInput.java:37) at org.jboss.marshalling.MarshallerObjectInputStream.readObjectOverride(MarshallerObjectInputStream.java:57) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:344) at java.util.HashMap.readObject(HashMap.java:1030) at sun.reflect.GeneratedMethodAccessor119.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.jboss.marshalling.reflect.SerializableClass.callReadObject(SerializableClass.java:218) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:302) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner.cloneFields(SerializingCloner.java:348) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:309) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner.cloneFields(SerializingCloner.java:348) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:309) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:285) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner.cloneFields(SerializingCloner.java:348) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:309) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.as.ejb3.remote.LocalEjbReceiver.clone(LocalEjbReceiver.java:268) ... 42 more

Code:

```<code>saveAction.java

protected void newSavedSearch(final SrchFrmDelegate sfd,
            final String userId, final HttpServletRequest request,
            final SaveSearchForm form) throws RemoteException,
            UsrNotFoundException {

        BseSrchValue srchValue = SrchResultsAction.retrieveSrchCriteria(request);
        FrmLayout frmLayout = (FrmLayout) request.getSession().getAttribute(
                FrmBuilderAction.FRM_LAYOUT_KEY);

        Integer resultCount = null;
        SrchResultValue srchResult = SearchResultsAction.retrieveSearchResults(request);
        if (srchResult != null) {
            resultCount = new Integer(srchResult.getTotal());
        }

        sfd.saveSearch(userGuid,
                form.getTitle(),
                form.getDesc(),
                form.getNewTtle(),
                srchValue,
                frmLayout,
                resultCount,
                form.getSearches());

    }
</code>```

SrchFrmDelegate.java

```<code>/**
 * Reference to the remote interface.
 */
private SrhFrmFacadeRemote srhFacadeRemote;

public String saveSearch(final String userId, final String srchTtle,
            final String srchDesc, final Boolean newTtle,
            final BsSearchValue srchValue, final FrmLay frmLay,
            final Integer resultCount, final List alerts)
            throws UsrNotFoundException,
            RemoteException {

        return srhFacadeRemote.saveSearch(userId, srchTtle,
                srchDesc, newTtle, srchValue, frmLay,
                resultCount, alerts);

    }

SrchFrmFacadeRemote.java

/**
 * Remote interface for SrchFrmFacade.
 */

public java.lang.String saveSearch( java.lang.String userId,java.lang.String srchTtle,java.lang.String srchDesc,java.lang.Boolean newTtle,com.common.search.BsSearchValue srchValue,com.common.search.advanced.FrmLay frmLay,java.lang.Integer resultCount,java.util.List alerts ) throws com.common.admin.UserNotFoundException, java.rmi.RemoteException;
</code>```

答: remember to add serialVersionUID to let class to be serialized and restored (generate it as getter or setter)</p>

Body:
I'm getting the below error while trying to save a search results using the Remote interface for SearchFacade.java

"Failed to marshal EJB parameters"

Can not set org.apache.commons.collections.FastHashMap field
  org.apache.commons.validator.Field.hMsgs to
  org.apache.commons.collections.FastHashMap at
  sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:146)
  at

I'm Using struts 1.1, EJB 2.1 using xdoclet 1.2.3 jars for generating the dependency files.(which is inevitable to use), Where my Local,Home interfaces are being generated using Xdoclet..

I'm also using Java 6, Jboss EAP 6.1 Alpha in my project.

Note: The same code works fine when running in Jboss 4.0

So wonder is my remote calling is correct.

Any help is welcome.

Error Logs

java.lang.RuntimeException: JBAS014154: Failed to marshal EJB parameters at org.jboss.as.ejb3.remote.LocalEjbReceiver.clone(LocalEjbReceiver.java:270) at org.jboss.as.ejb3.remote.LocalEjbReceiver.clone(LocalEjbReceiver.java:259) at org.jboss.as.ejb3.remote.LocalEjbReceiver.processInvocation(LocalEjbReceiver.java:170) at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:181) at org.jboss.ejb.client.EJBHomeCreateInterceptor.handleInvocation(EJBHomeCreateInterceptor.java:79) at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:183) at org.jboss.ejb.client.TransactionInterceptor.handleInvocation(TransactionInterceptor.java:42) at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:183) at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:125) at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:183) at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:177) at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:161) at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:124) at $Proxy25.saveSearch(Unknown Source) at com.web.history.SearchFormDelegate.saveSearch(SearchFormDelegate.java:177) at com.history.SaveSearchAction.createNewSavedSearch(SaveSearchAction.java:109) at com.history.SaveSearchAction.executeSynchronized(SaveSearchAction.java:296) at com.dispatch.SynchronizedAction.execute(SynchronizedAction.java:206) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432) at javax.servlet.http.HttpServlet.service(HttpServlet.java:754) at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:295) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) at com.security.AuthenticationFilter.doFilter(AuthenticationFilter.java:672) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) at com.planetj.servlet.filter.compression.CompressingFilter.doFilter(CompressingFilter.java:270) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:149) at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:169) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:145) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:97) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:102) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:336) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:653) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:920) at java.lang.Thread.run(Thread.java:662) Caused by: java.lang.IllegalArgumentException: Can not set org.apache.commons.collections.FastHashMap field org.apache.commons.validator.Field.hMsgs to org.apache.commons.collections.FastHashMap at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:146) at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:150) at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:63) at java.lang.reflect.Field.set(Field.java:657) at org.jboss.marshalling.cloner.SerializingCloner.storeFields(SerializingCloner.java:368) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:313) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner.cloneFields(SerializingCloner.java:348) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:309) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner$StepObjectInput.doReadObject(SerializingCloner.java:836) at org.jboss.marshalling.AbstractObjectInput.readObject(AbstractObjectInput.java:37) at org.jboss.marshalling.MarshallerObjectInputStream.readObjectOverride(MarshallerObjectInputStream.java:57) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:344) at java.util.HashMap.readObject(HashMap.java:1030) at sun.reflect.GeneratedMethodAccessor119.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.jboss.marshalling.reflect.SerializableClass.callReadObject(SerializableClass.java:218) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:302) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner.cloneFields(SerializingCloner.java:348) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:309) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner.cloneFields(SerializingCloner.java:348) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:309) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:285) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner.cloneFields(SerializingCloner.java:348) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:309) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.as.ejb3.remote.LocalEjbReceiver.clone(LocalEjbReceiver.java:268) ... 42 more

Code:

saveAction.java

protected void newSavedSearch(final SrchFrmDelegate sfd,
            final String userId, final HttpServletRequest request,
            final SaveSearchForm form) throws RemoteException,
            UsrNotFoundException {

        BseSrchValue srchValue = SrchResultsAction.retrieveSrchCriteria(request);
        FrmLayout frmLayout = (FrmLayout) request.getSession().getAttribute(
                FrmBuilderAction.FRM_LAYOUT_KEY);

        Integer resultCount = null;
        SrchResultValue srchResult = SearchResultsAction.retrieveSearchResults(request);
        if (srchResult != null) {
            resultCount = new Integer(srchResult.getTotal());
        }

        sfd.saveSearch(userGuid,
                form.getTitle(),
                form.getDesc(),
                form.getNewTtle(),
                srchValue,
                frmLayout,
                resultCount,
                form.getSearches());

    }

SrchFrmDelegate.java

/**
 * Reference to the remote interface.
 */
private SrhFrmFacadeRemote srhFacadeRemote;

public String saveSearch(final String userId, final String srchTtle,
            final String srchDesc, final Boolean newTtle,
            final BsSearchValue srchValue, final FrmLay frmLay,
            final Integer resultCount, final List alerts)
            throws UsrNotFoundException,
            RemoteException {

        return srhFacadeRemote.saveSearch(userId, srchTtle,
                srchDesc, newTtle, srchValue, frmLay,
                resultCount, alerts);

    }

SrchFrmFacadeRemote.java

/**
 * Remote interface for SrchFrmFacade.
 */

public java.lang.String saveSearch( java.lang.String userId,java.lang.String srchTtle,java.lang.String srchDesc,java.lang.Boolean newTtle,com.common.search.BsSearchValue srchValue,com.common.search.advanced.FrmLay frmLay,java.lang.Integer resultCount,java.util.List alerts ) throws com.common.admin.UserNotFoundException, java.rmi.RemoteException;


问:
How to apply setting by toggle switch?

Possible Duplicate:

  can anyone tell me how to use switch ?

Hi I have two view

the first view contains the main function and the second view is used to let the user change the setting on the first view.

I have insert a switch in second view to let user change a setting on the first view

I have two questions, how to use switch to set YES and NO for a value? and then, base on that value
the first view will respond differently?

P.S. I change the view with navigation method , not add subview

Thanks in advance

lets say I have the following code

First View.m

```<code>- (IBAction) addValue:(id)sender
{
aValue ++;
}
//the following will react according to the setting on second view
If (????//Don't know what to put here to represent the switch is ON or OFF)
{ //whatever action}
else
{//whatever action}
</code>```

second view.h

```<code>@interface
    //declaration of the switch
        - (IBAction) changeMode:(id)sender
    @end
</code>```

second view.m

```<code>    -(IBAction) changeMode:(id)sender
{
    //What to put here to switch ON and OFF ??
}
</code>```

答:
You can do this:

```<code>if ( self.mySwitch.on )
// do something
</code>```

Here I assume mySwitch is an instance of UISwitch. It is a good idea to store switch value to NSUserDefaults so that you can retrieve it from another view.

This is how you store the value:

```<code>NSString *switchValue;
if ( self.mySwitch.on )
    switchValue = @"YES";
else
    switchValue = @"NO";

[[NSUserDefaults standardUserDefaults] setObject:switchValue forKey:@"switchValue"];
[[NSUserDefaults standardUserDefaults] synchronize];
</code>```

This is how you retrieve the value:

```<code>BOOL switchState = [[[NSUserDefaults standardUserDefaults] objectForKey:@"switchValue"] boolValue];
</code>```

Title: How to apply setting by toggle switch?

Body:
Possible Duplicate:

  can anyone tell me how to use switch ?

Hi I have two view

the first view contains the main function and the second view is used to let the user change the setting on the first view.

I have insert a switch in second view to let user change a setting on the first view

I have two questions, how to use switch to set YES and NO for a value? and then, base on that value
the first view will respond differently?

P.S. I change the view with navigation method , not add subview

Thanks in advance

lets say I have the following code

First View.m

- (IBAction) addValue:(id)sender
{
aValue ++;
}
//the following will react according to the setting on second view
If (????//Don't know what to put here to represent the switch is ON or OFF)
{ //whatever action}
else
{//whatever action}

second view.h

@interface
    //declaration of the switch
        - (IBAction) changeMode:(id)sender
    @end

second view.m

    -(IBAction) changeMode:(id)sender
{
    //What to put here to switch ON and OFF ??
}

Body:
You can do this:

if ( self.mySwitch.on )
// do something

Here I assume mySwitch is an instance of UISwitch. It is a good idea to store switch value to NSUserDefaults so that you can retrieve it from another view.

This is how you store the value:

NSString *switchValue;
if ( self.mySwitch.on )
    switchValue = @"YES";
else
    switchValue = @"NO";

[[NSUserDefaults standardUserDefaults] setObject:switchValue forKey:@"switchValue"];
[[NSUserDefaults standardUserDefaults] synchronize];

This is how you retrieve the value:

BOOL switchState = [[[NSUserDefaults standardUserDefaults] objectForKey:@"switchValue"] boolValue];


问:
Open url in new tab based on data in service in Kendo Menu
I searched around number of posts, but haven't any solution applicable to my scenario. I am population kendo-menu dynamically using an array build via sql.

```<code><kendo-menu [items]="items"
            [vertical]="true"
            style="display:inline-block;">
</kendo-menu>
</code>```

This is the sample I am following:

https://www.telerik.com/kendo-angular-ui/components/menus/menu/vertical/

Here is how items array is structured:

```<code>export const items: any[] = [
  {
  text: 'Reportingd',
    items: [{ text: 'Dash', url: "https://www.google.com" },  {
    text: 'Realtime',
      items: [{ text: 'DesktopNew', url: "https://www.telerik.com" }, { text: 'laptop', url: "https://www.msn.com" }]
  }]
},
{
  text: 'Other Reporting',
  items: [{ text: 'Training', url: "https://www.msn.com" }, { text: 'UserManual', url: "https://www.msn.com" }, { text: 'Guide',
    items: }]
},
{
  text: 'Tools',
  items:[{ text: 'Training', url: "https://www.msn.com" }]
}];
</code>```

However, this on click of menu/sub-menu opens url in the same window. I want to open in different window or new tab. HTML  tag does not work here. Please suggest

```<code><a href="https://www.thesitewizard.com/" target="_blank">thesitewizard.com</a>
</code>```

答:
was able to resolve. It is 2 step process though. with following array structure given in initial post just open in current window. Therefore, fetched unique MenuID instead of url on initial load. Then as  ManirajSS suggested</p>

```<code>public onSelect({ item }): void {

//call service to get url for this MenuID

}
</code>```

Body:
I searched around number of posts, but haven't any solution applicable to my scenario. I am population kendo-menu dynamically using an array build via sql.

<kendo-menu [items]="items"
            [vertical]="true"
            style="display:inline-block;">
</kendo-menu>

This is the sample I am following:

https://www.telerik.com/kendo-angular-ui/components/menus/menu/vertical/

Here is how items array is structured:

export const items: any[] = [
  {
  text: 'Reportingd',
    items: [{ text: 'Dash', url: "https://www.google.com" },  {
    text: 'Realtime',
      items: [{ text: 'DesktopNew', url: "https://www.telerik.com" }, { text: 'laptop', url: "https://www.msn.com" }]
  }]
},
{
  text: 'Other Reporting',
  items: [{ text: 'Training', url: "https://www.msn.com" }, { text: 'UserManual', url: "https://www.msn.com" }, { text: 'Guide',
    items: }]
},
{
  text: 'Tools',
  items:[{ text: 'Training', url: "https://www.msn.com" }]
}];

However, this on click of menu/sub-menu opens url in the same window. I want to open in different window or new tab. HTML  tag does not work here. Please suggest

thesitewizard.com

Body:
was able to resolve. It is 2 step process though. with following array structure given in initial post just open in current window. Therefore, fetched unique MenuID instead of url on initial load. Then as  ManirajSS suggested

public onSelect({ item }): void {

//call service to get url for this MenuID

}


问:
Java spring caching, saveAll proper handling of update
So I currently try to cache as much as possible SAFELY in my spring boot application.

Bud i run into brain scratcher.
How do i handle saveAll(list of entities) method ?

```<code> public List<WorkaroundEntity> saveAll(List<WorkaroundEntity> workaroundEntities) {
</code>```

This method saves all entities, My current cache looks like this :

```<code>  /**
    * K=WorkaroundEntity.id   --   Value=WorkaroundEntity
   */
   private static final String CACHE_NAME_WORKAROUNDS = "workarounds";
</code>```

So basically my map has IDs AND entities.
When user saves LIST OF ALL ENTITIES. From my point of view I only have this option :

```<code>@CacheEvict(value = CACHE_NAME_WORKAROUNDS, allEntries = true, condition = "#workaroundEntities.size()>=1")
public List<WorkaroundEntity> saveAll(List<WorkaroundEntity> workaroundEntities) {
    return workaroundEntityRepository.saveAll(workaroundEntities);
}
</code>```

Am I wrong and is there a better solution for this kind of problem?

So far i use this cache in methods :

```<code>public WorkaroundEntity save(WorkaroundEntity workaroundEntity)
public WorkaroundEntity findById(long id)
public void delete(WorkaroundEntity workaroundEntity)
public WorkaroundEntity getOne(long id)
</code>```

How do you handle methods that work with collections instead of single entities?

答: In the end , answer for me was to use hibernate 2nd level cache and spring cache together. I got best of both words. In addition to this i have created additiona linternal caches to hit database even less.

Body:
So I currently try to cache as much as possible SAFELY in my spring boot application.

Bud i run into brain scratcher.
How do i handle saveAll(list of entities) method ?

 public List<WorkaroundEntity> saveAll(List<WorkaroundEntity> workaroundEntities) {

This method saves all entities, My current cache looks like this :

  /**
    * K=WorkaroundEntity.id   --   Value=WorkaroundEntity
   */
   private static final String CACHE_NAME_WORKAROUNDS = "workarounds";

So basically my map has IDs AND entities.
When user saves LIST OF ALL ENTITIES. From my point of view I only have this option :

@CacheEvict(value = CACHE_NAME_WORKAROUNDS, allEntries = true, condition = "#workaroundEntities.size()>=1")
public List<WorkaroundEntity> saveAll(List<WorkaroundEntity> workaroundEntities) {
    return workaroundEntityRepository.saveAll(workaroundEntities);
}

Am I wrong and is there a better solution for this kind of problem?

So far i use this cache in methods :

public WorkaroundEntity save(WorkaroundEntity workaroundEntity)
public WorkaroundEntity findById(long id)
public void delete(WorkaroundEntity workaroundEntity)
public WorkaroundEntity getOne(long id)

How do you handle methods that work with collections instead of single entities?


问:
How do I save the data on a user control before switching to a different one?
I have a WPF Application with different user controls. Each of them can be accessed by clicking a button on the left side. My issue is, when I am in one of the user controls and filling out the data in textboxes, combo boxes etc, I may have to stop it mid way and click on another user control. While doing that, I need to keep the data in the previous user control intact so that when I return to the first user control, the data should be present in all the controls before I left it. How do I achieve this?  Here's a sample picture of how my application looks like:

Picture Credit: https://rachel53461.wordpress.com/2011/12/18/navigation-with-mvvm-2/

From the picture, if I am in the Products Page, I might have several text boxes with data entered in there. For a variety of reasons, I may have to step away from this and click on Home Page or some other page , do some work there and return back to the Products page. When I return, I need the data to be present as is when I left it.

Thanks in Advance

答:
You must have create a ViewModel to each diferent user control.
ViewModel remains in memory until you process that or make a diferent process.
For Example you hava a User control for your Main Page, that's mean you have a view (MainPageView) of your user control for your main page, that view belong to a ViewModelMainPage.
For Products you maybe have a ProductView, that's belong to ViewModelProducts.
You must create a ManagerViewModel to manage the view for diferents user control.</p>


问:
How to map the row data in ag grid to field of field obtained by API in json.?
how to map to the values required?

```<code>import { Component, OnInit} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import "ag-grid-enterprise";
@Component({
  selector: 'app-lists',
  templateUrl: './lists.component.html',
  styleUrls: ['./lists.component.css']
})
export class ListsComponent implements OnInit {

columnDefs = [
  {headerName: 'Funds #', field: 'portfolioId',filter:false,Sorting:false},
  {headerName: 'Short Name', field: 'portfolioName',filter:false,Sorting:false}
];
ngOnInit(){
  this.myData= this.http.get('https://aswsfl29sit.fmrco.com:22933/CCService/resource/projectedcashdetails/3?offsetNumber=0&json=true');
  console.log(this.myData);
}
}`enter code here`
</code>```

i want to display field of field of portfolio(portfolio->x->y) which i obtained in json format from an API. As this field has further parts ,there is nothing being display in ag grid.enter code here

答:
With regards to your question and the sample data you've provided, first, this is what you should have on your lists.component.html:

```<code><ag-grid-angular
  class="ag-theme-balham-dark"
  [rowData]="myData"
  [columnDefs]="columnDefs"
  (gridReady)="onGridReady($event)"
   <!-- other ag-grid properties -->
 >
 </ag-grid-angular>
</code>```

On your component.ts, I notice this glaring issue. While you have made the HTTP GET request, you did not return the values. You will need to subscribe() to it to return the observable values, so that the values can be used.

```<code>import { Component, OnInit} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import "ag-grid-enterprise";
@Component({
  selector: 'app-lists',
  templateUrl: './lists.component.html',
  styleUrls: ['./lists.component.css']
})
export class ListsComponent implements OnInit {

  constructor(private http: HttpClient) { }

  columnDefs = [
    {headerName: 'Funds #', field: 'portfolioId',filter:false,Sorting:false},
    {headerName: 'Short Name', field: 'portfolioName',filter:false,Sorting:false}
  ];

  ngOnInit() {
this.http.get('https://aswsfl29sit.fmrco.com:22933/CCService/resource/projectedcashdetails/3?offsetNumber=0&json=true').subscribe(res => {
    this.myData = res;
    console.log(this.myData);
    // do the rest to ensure that myData is a single level array of objects
  });
}
</code>```

Body:
how to map to the values required?

import { Component, OnInit} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import "ag-grid-enterprise";
@Component({
  selector: 'app-lists',
  templateUrl: './lists.component.html',
  styleUrls: ['./lists.component.css']
})
export class ListsComponent implements OnInit {

columnDefs = [
  {headerName: 'Funds #', field: 'portfolioId',filter:false,Sorting:false},
  {headerName: 'Short Name', field: 'portfolioName',filter:false,Sorting:false}
];
ngOnInit(){
  this.myData= this.http.get('https://aswsfl29sit.fmrco.com:22933/CCService/resource/projectedcashdetails/3?offsetNumber=0&json=true');
  console.log(this.myData);
}
}`enter code here`

i want to display field of field of portfolio(portfolio->x->y) which i obtained in json format from an API. As this field has further parts ,there is nothing being display in ag grid.enter code here

Body:
With regards to your question and the sample data you've provided, first, this is what you should have on your lists.component.html:

<ag-grid-angular
  class="ag-theme-balham-dark"
  [rowData]="myData"
  [columnDefs]="columnDefs"
  (gridReady)="onGridReady($event)"
   <!-- other ag-grid properties -->
 >
 </ag-grid-angular>

On your component.ts, I notice this glaring issue. While you have made the HTTP GET request, you did not return the values. You will need to subscribe() to it to return the observable values, so that the values can be used.

import { Component, OnInit} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import "ag-grid-enterprise";
@Component({
  selector: 'app-lists',
  templateUrl: './lists.component.html',
  styleUrls: ['./lists.component.css']
})
export class ListsComponent implements OnInit {

  constructor(private http: HttpClient) { }

  columnDefs = [
    {headerName: 'Funds #', field: 'portfolioId',filter:false,Sorting:false},
    {headerName: 'Short Name', field: 'portfolioName',filter:false,Sorting:false}
  ];

  ngOnInit() {
this.http.get('https://aswsfl29sit.fmrco.com:22933/CCService/resource/projectedcashdetails/3?offsetNumber=0&json=true').subscribe(res => {
    this.myData = res;
    console.log(this.myData);
    // do the rest to ensure that myData is a single level array of objects
  });
}


问:
Triggering DynamicData cache update using Reactive Subject
As a caveat I'm a novice with Rx (2 weeks) and have been experimenting with using Rx, RxUI and Roland Pheasant's DynamicData.

I have a service that initially loads data from local persistence and then, upon some user (or system) instruction will contact the server (TriggerServer in the example) to get additional or replacement data.  The solution I've come up with uses a Subject and I've come across many a site discussing the pros/cons of using them.  Although I understand the basics of hot/cold it's all based on reading rather than real world.

So, using the below as a simplified version, is this 'right' way of going about this problem or is there something I haven't properly understood somewhere?

NB: I'm not sure how important it is, but the actual code is taken from a Xamarin.Forms app, that uses RxUI, the user input being a ReactiveCommand.

Example:

```<code>using DynamicData;
using System;
using System.Linq;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;

public class MyService : IDisposable
{

    private CompositeDisposable _cleanup;
    private Subject<Unit> _serverSubject = new Subject<Unit>();

    public MyService()
    {

        var data = Initialise().Publish();
        AllData = data.AsObservableCache();

        _cleanup = new CompositeDisposable(AllData, data.Connect());
    }

    public IObservableCache<MyData, Guid> AllData { get; }

    public void TriggerServer()
    {
        // This is what I'm not sure about...
        _serverSubject.OnNext(Unit.Default);
    }

    private IObservable<IChangeSet<MyData, Guid>> Initialise()
    {
        return ObservableChangeSet.Create<MyData, Guid>(async cache =>
        {
            // inital load - is this okay?
            cache.AddOrUpdate(await LoadLocalData());

            // is this a valid way of doing this?
            var sync = _serverSubject.Select(_ => GetDataFromServer())
                .Subscribe(async task =>
                {
                    var data = await task.ConfigureAwait(false);
                    cache.AddOrUpdate(data);
                });

            return new CompositeDisposable(sync);
        }, d=> d.Id);
    }

    private IObservable<MyData> LoadLocalData()
    {
        return Observable.Timer(TimeSpan.FromSeconds(3)).Select(_ => new MyData("localdata"));
    }

    private async Task<MyData> GetDataFromServer()
    {
        await Task.Delay(2000).ConfigureAwait(true);
        return new MyData("serverdata");
    }

    public void Dispose()
    {
        _cleanup?.Dispose();
    }
}

public class MyData
{
    public MyData(string value)
    {
        Value = value;
    }

    public Guid Id { get; } = Guid.NewGuid();

    public string Value { get; set; }
}
</code>```

And a simple Console app to run:

```<code>public static class TestProgram
{
    public static void Main()
    {
        var service = new MyService();

        service.AllData.Connect()
            .Bind(out var myData)
            .Subscribe(_=> Console.WriteLine("data in"), ()=> Console.WriteLine("COMPLETE"));

        while (Continue())
        {
            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine($"Triggering Server Call, current data is: {string.Join(", ", myData.Select(x=> x.Value))}");
            service.TriggerServer();
        }
    }

    private static bool Continue()
    {
        Console.WriteLine("Press any key to call server, x to exit");
        var key = Console.ReadKey();
        return key.Key != ConsoleKey.X;
    }
}
</code>```

答:
I'm putting what I've come to as my solution just in case there's others that find this while they're wandering the internets.

I ended up removing the Subjects all together and chaining together several SourceCache, so when one changed it pushed into the other and so on.  I've removed some code for brevity:

```<code>public class MyService : IDisposable
{
    private SourceCache<MyData, Guid> _localCache = new SourceCache<MyData, Guid>(x=> x.Id);
    private SourceCache<MyData, Guid> _serverCache = new SourceCache<MyData, Guid>(x=> x.Id);

    public MyService()
    {
        var localdata = _localCache.Connect();
        var serverdata = _serverCache.Connect();
        var alldata = localdata.Merge(serverdata);

        AllData = alldata.AsObservableCache();
    }

    public IObservableCache<MyData, Guid> AllData { get; }

    public IObservable<Unit> TriggerLocal()
    {
        return LoadLocalAsync().ToObservable();
    }

    public IObservable<Unit> TriggerServer()
    {
        return LoadServerAsync().ToObservable();
    }
}
</code>```

EDIT: I've changed this again to remove any chaining of caches - I just manage the one cache internally.  Lesson is not to post too early.

Body:
As a caveat I'm a novice with Rx (2 weeks) and have been experimenting with using Rx, RxUI and Roland Pheasant's DynamicData.

I have a service that initially loads data from local persistence and then, upon some user (or system) instruction will contact the server (TriggerServer in the example) to get additional or replacement data.  The solution I've come up with uses a Subject and I've come across many a site discussing the pros/cons of using them.  Although I understand the basics of hot/cold it's all based on reading rather than real world.

So, using the below as a simplified version, is this 'right' way of going about this problem or is there something I haven't properly understood somewhere?

NB: I'm not sure how important it is, but the actual code is taken from a Xamarin.Forms app, that uses RxUI, the user input being a ReactiveCommand.

Example:

using DynamicData;
using System;
using System.Linq;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;

public class MyService : IDisposable
{

    private CompositeDisposable _cleanup;
    private Subject<Unit> _serverSubject = new Subject<Unit>();

    public MyService()
    {

        var data = Initialise().Publish();
        AllData = data.AsObservableCache();

        _cleanup = new CompositeDisposable(AllData, data.Connect());
    }

    public IObservableCache<MyData, Guid> AllData { get; }

    public void TriggerServer()
    {
        // This is what I'm not sure about...
        _serverSubject.OnNext(Unit.Default);
    }

    private IObservable<IChangeSet<MyData, Guid>> Initialise()
    {
        return ObservableChangeSet.Create<MyData, Guid>(async cache =>
        {
            // inital load - is this okay?
            cache.AddOrUpdate(await LoadLocalData());

            // is this a valid way of doing this?
            var sync = _serverSubject.Select(_ => GetDataFromServer())
                .Subscribe(async task =>
                {
                    var data = await task.ConfigureAwait(false);
                    cache.AddOrUpdate(data);
                });

            return new CompositeDisposable(sync);
        }, d=> d.Id);
    }

    private IObservable<MyData> LoadLocalData()
    {
        return Observable.Timer(TimeSpan.FromSeconds(3)).Select(_ => new MyData("localdata"));
    }

    private async Task<MyData> GetDataFromServer()
    {
        await Task.Delay(2000).ConfigureAwait(true);
        return new MyData("serverdata");
    }

    public void Dispose()
    {
        _cleanup?.Dispose();
    }
}

public class MyData
{
    public MyData(string value)
    {
        Value = value;
    }

    public Guid Id { get; } = Guid.NewGuid();

    public string Value { get; set; }
}

And a simple Console app to run:

public static class TestProgram
{
    public static void Main()
    {
        var service = new MyService();

        service.AllData.Connect()
            .Bind(out var myData)
            .Subscribe(_=> Console.WriteLine("data in"), ()=> Console.WriteLine("COMPLETE"));

        while (Continue())
        {
            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine($"Triggering Server Call, current data is: {string.Join(", ", myData.Select(x=> x.Value))}");
            service.TriggerServer();
        }
    }

    private static bool Continue()
    {
        Console.WriteLine("Press any key to call server, x to exit");
        var key = Console.ReadKey();
        return key.Key != ConsoleKey.X;
    }
}

Body:
I'm putting what I've come to as my solution just in case there's others that find this while they're wandering the internets.

I ended up removing the Subjects all together and chaining together several SourceCache, so when one changed it pushed into the other and so on.  I've removed some code for brevity:

public class MyService : IDisposable
{
    private SourceCache<MyData, Guid> _localCache = new SourceCache<MyData, Guid>(x=> x.Id);
    private SourceCache<MyData, Guid> _serverCache = new SourceCache<MyData, Guid>(x=> x.Id);

    public MyService()
    {
        var localdata = _localCache.Connect();
        var serverdata = _serverCache.Connect();
        var alldata = localdata.Merge(serverdata);

        AllData = alldata.AsObservableCache();
    }

    public IObservableCache<MyData, Guid> AllData { get; }

    public IObservable<Unit> TriggerLocal()
    {
        return LoadLocalAsync().ToObservable();
    }

    public IObservable<Unit> TriggerServer()
    {
        return LoadServerAsync().ToObservable();
    }
}

EDIT: I've changed this again to remove any chaining of caches - I just manage the one cache internally.  Lesson is not to post too early.


问:
model/sql joins in rails 3
How can I join the objects with the models below?

```
User
has_many messages

Message
belongs_to user

Thread
has_many messages
```

I'm trying to get all threads that belong to user X. I would like to join on message.user_id = user.user_id and thread.message_id = message.message_id. I can do this using find_by_sql but I'm trying to avoid that.

Thanks

答:
The following should work: (note that I've added your missing message belongs_to :thread)

```<code>class User < ActiveRecord::Base
  has_many :messages
  has_many :threads, :through => :messages
end

class Message < ActiveRecord::Base
  belongs_to :user
  belongs_to :thread
end

class Thread < ActiveRecord::Base
  has_many :messages
  has_many :users, :through => :messages
end
</code>```

This should allow you to do my_user.threads and my_thread.users.

You can read more about has_many :through on the Rails Guides and the API.

Title: model/sql joins in rails 3

Body:
How can I join the objects with the models below?

User
has_many messages

Message
belongs_to user

Thread
has_many messages

I'm trying to get all threads that belong to user X. I would like to join on message.user_id = user.user_id and thread.message_id = message.message_id. I can do this using find_by_sql but I'm trying to avoid that.

Thanks

Body:
The following should work: (note that I've added your missing message belongs_to :thread)

class User < ActiveRecord::Base
  has_many :messages
  has_many :threads, :through => :messages
end

class Message < ActiveRecord::Base
  belongs_to :user
  belongs_to :thread
end

class Thread < ActiveRecord::Base
  has_many :messages
  has_many :users, :through => :messages
end

This should allow you to do my_user.threads and my_thread.users.

You can read more about has_many :through on the Rails Guides and the API.


问:
How to create and use an "out" parameter with a SQL Server database
I am working on a C# desktop application. I want to use a stored procedure (insert query) to add a new record to a data table. I need to return the primary key which is an identity insert (bigint) to avoid another round trip to the database. I have searched the MS Help(less) files for a couple of hours and found nothing on how to set the out parameter of the stored procedure or how to obtain the return value.

答:
What you want is an OUTPUT Parameter. I'm not a C# developer, so I've omitted the C# side of things and linked an answer:

```<code>--Sample Table
CREATE TABLE dbo.YourTable (ID bigint IDENTITY,
                            SomeColumn varchar(20));

GO
--Sample SP
CREATE PROC dbo.InsertYourTable @SomeColumn varchar(20), @ID bigint OUTPUT AS
BEGIN

    DECLARE @IDt table (ID bigint);

    INSERT INTO dbo.YourTable(SomeColumn)
    OUTPUT inserted.ID INTO @IDt
    VALUES(@SomeColumn);

    SET @ID = (SELECT ID FROM @IDt);
END;

GO
--Sample EXEC of proc and PRINT of OUTPUT value of ID
DECLARE @SomeColumn varchar(20) = 'abc', @ID bigint;

EXEC dbo.InsertYourTable @SomeColumn = @SomeColumn,
                         @ID = @ID OUTPUT;

PRINT @ID;
</code>```

Using this answer I think the c# would be:

```<code>cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@SomeColumn",SqlDbType.VarChar,20);
cmd.Parameters["@SomeColumn"].Value = MyColumn;
cmd.Parameters.Add("@ID",SqlDbType.int).Direction = ParameterDirection.Output;
</code>```

Body:
What you want is an OUTPUT Parameter. I'm not a C# developer, so I've omitted the C# side of things and linked an answer:

--Sample Table
CREATE TABLE dbo.YourTable (ID bigint IDENTITY,
                            SomeColumn varchar(20));

GO
--Sample SP
CREATE PROC dbo.InsertYourTable @SomeColumn varchar(20), @ID bigint OUTPUT AS
BEGIN

    DECLARE @IDt table (ID bigint);

    INSERT INTO dbo.YourTable(SomeColumn)
    OUTPUT inserted.ID INTO @IDt
    VALUES(@SomeColumn);

    SET @ID = (SELECT ID FROM @IDt);
END;

GO
--Sample EXEC of proc and PRINT of OUTPUT value of ID
DECLARE @SomeColumn varchar(20) = 'abc', @ID bigint;

EXEC dbo.InsertYourTable @SomeColumn = @SomeColumn,
                         @ID = @ID OUTPUT;

PRINT @ID;

Using this answer I think the c# would be:

cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@SomeColumn",SqlDbType.VarChar,20);
cmd.Parameters["@SomeColumn"].Value = MyColumn;
cmd.Parameters.Add("@ID",SqlDbType.int).Direction = ParameterDirection.Output;