问:
MATLAB pdf of filtered Rayleigh distribution
Good evening,

I am trying to program the following equation in MATLAB, which is a rayleigh distribution made up of two gaussian arrays. No matter what I do it does not look close to the normalized histogram or the generic pdf distribution for a rayleigh fade:

So, here is what I have done.

```<code>x1 = randn(100000, 1);
% Create a second array of Gaussian random numbers
y1 = randn(100000, 1);

% Pass both Gaussian arrays through low pass filter and save to variable
x1_LPF = filter(LPF, 1, x1);
y1_LPF = filter(LPF, 1, y1);

% New Histograms of Raleigh distribution for filtered data
ray1 = abs(x1_LPF + j*y1_LPF);

figure('Name', 'Normalized Histogram of Raleigh Distribution')
[a, b] = hist(ray1, 100)
delta_x = b(3) - b(2)
% SIGMA left out in equation because it is equal to 1 in the problem
g = b .* exp((-b.^2) / 2) .* delta_x;
plot(b , g, 'b')
</code>```

Which gives me this:

When instead it should look something like this the black line on this:

Here is the settings for my filter in fdatool in case someone wants to run it for themselves by exporting as variable LPF:

答:
The following code can generate the desired distribution:

```<code>N=1000000;

%Random uniform variables
U=rand(N,1);

%Rayleight random variable using an inverse transform sampling
sigma=1;
x1=sigma*sqrt(-2*log(1-U));

histogram(x1,'Normalization','pdf');

% Theoretical equation
x=linspace(0,6,100);
pdf=x/sigma^2.*exp((-x.^2)/(2*sigma^2));
% Plot
hold on
plot(x,pdf,'r')
legend('Stochastic','Theoretical')
</code>```

The resulting plot is the following

Body:
Good evening,

I am trying to program the following equation in MATLAB, which is a rayleigh distribution made up of two gaussian arrays. No matter what I do it does not look close to the normalized histogram or the generic pdf distribution for a rayleigh fade:

So, here is what I have done.

x1 = randn(100000, 1);
% Create a second array of Gaussian random numbers
y1 = randn(100000, 1);

% Pass both Gaussian arrays through low pass filter and save to variable
x1_LPF = filter(LPF, 1, x1);
y1_LPF = filter(LPF, 1, y1);

% New Histograms of Raleigh distribution for filtered data
ray1 = abs(x1_LPF + j*y1_LPF);

figure('Name', 'Normalized Histogram of Raleigh Distribution')
[a, b] = hist(ray1, 100)
delta_x = b(3) - b(2)
% SIGMA left out in equation because it is equal to 1 in the problem
g = b .* exp((-b.^2) / 2) .* delta_x;
plot(b , g, 'b')

Which gives me this:

When instead it should look something like this the black line on this:

Here is the settings for my filter in fdatool in case someone wants to run it for themselves by exporting as variable LPF:

Body:
The following code can generate the desired distribution:

N=1000000;

%Random uniform variables
U=rand(N,1);

%Rayleight random variable using an inverse transform sampling
sigma=1;
x1=sigma*sqrt(-2*log(1-U));

histogram(x1,'Normalization','pdf');

% Theoretical equation
x=linspace(0,6,100);
pdf=x/sigma^2.*exp((-x.^2)/(2*sigma^2));
% Plot
hold on
plot(x,pdf,'r')
legend('Stochastic','Theoretical')

The resulting plot is the following


来源: stackexchange

问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
I started at around 7-8 years of age (1992-93) in QBasic. A friend (same age) showed me the amazing graphical programs he could do. I often asked something like "Could you make the ... do ... instead?", and he could!

One program I still remember was something resembling fluid filling up the screen, intially containing a few big and thick circles. Scanning left to right and back again, bumping into walls, and exploding (!) if it gets stuck somewhere.

OwnerDisplayName: Michael Buen

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Triptych

OwnerDisplayName: MizardX

LastEditorDisplayName: MizardX


问:
Javascript push input into Array causes several arrays not one
This is a follow up to my question, seen here

I am trying to write that when a user enters in their name (string) into the field and hits enter, it pushes it into an array.  It works, kinda.  But I get an error when I try it one and then it produces multiple arrays when I try it another.  I don't want to use jQuery.

Here is the HTML

```<code><input type="text"
   class="theplayer pre"
   name="Player"
   id="bind"
   placeholder="Enter Names"
    />
<button type="button" id="thego" class="pre enterteam" value="click">Go</button>
</code>```

Here is my js that works but it creates multiple arrays instead of pushing everything into one array (because the nextElementSibling is not called, I know this, see next block

```<code>let namesOfPlayers = [];
let currentValue = document.getElementById("bind").value;
let button = currentValue.nextElementSibling;
document.addEventListener('keypress', function (e) {
    const key = e.which || e.keyCode;
    if (key === 13) {
        namesOfPlayers.push(currentValue);
        console.log('namesOfPlayers', namesOfPlayers);
    }
});
</code>```

Here is my js that throws an error (I don't want to use jQuery)

I want that when a user hits enter or clicks the button that the string is submitted and added into the empty array.  I can't for the life of me figure out how to make that work.

Thanks for your help!

答:
You fetch the value of the input too soon. You should fetch it only when the button is clicked, not before.

Secondly, the button does not have a keypress event, nor a keyCode associated with it. You need to listen to the click event.

So do this:

let namesOfPlayers = [];
let input = document.getElementById("bind");
let button = input.nextElementSibling;
button.addEventListener('click', function (e) {
    namesOfPlayers.push(input.value);
    console.log('namesOfPlayers', namesOfPlayers);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text"
       class="theplayer pre"
       name="Player"
       id="bind"
       placeholder="Enter Names" />
<button type="button" id="thego" class="pre enterteam" value="click">Go</button></code>```

ContentLicense: CC BY-SA 3.0

Body:
This is a follow up to my question, seen here

I am trying to write that when a user enters in their name (string) into the field and hits enter, it pushes it into an array.  It works, kinda.  But I get an error when I try it one and then it produces multiple arrays when I try it another.  I don't want to use jQuery.

Here is the HTML

<input type="text"
   class="theplayer pre"
   name="Player"
   id="bind"
   placeholder="Enter Names"
    />
<button type="button" id="thego" class="pre enterteam" value="click">Go</button>

Here is my js that works but it creates multiple arrays instead of pushing everything into one array (because the nextElementSibling is not called, I know this, see next block

let namesOfPlayers = [];
let currentValue = document.getElementById("bind").value;
let button = currentValue.nextElementSibling;
document.addEventListener('keypress', function (e) {
    const key = e.which || e.keyCode;
    if (key === 13) {
        namesOfPlayers.push(currentValue);
        console.log('namesOfPlayers', namesOfPlayers);
    }
});

Here is my js that throws an error (I don't want to use jQuery)

I want that when a user hits enter or clicks the button that the string is submitted and added into the empty array.  I can't for the life of me figure out how to make that work.

Thanks for your help!

Body:
You fetch the value of the input too soon. You should fetch it only when the button is clicked, not before.

Secondly, the button does not have a keypress event, nor a keyCode associated with it. You need to listen to the click event.

So do this:

let namesOfPlayers = [];
let input = document.getElementById("bind");
let button = input.nextElementSibling;
button.addEventListener('click', function (e) {
    namesOfPlayers.push(input.value);
    console.log('namesOfPlayers', namesOfPlayers);
});

<input type="text"
       class="theplayer pre"
       name="Player"
       id="bind"
       placeholder="Enter Names" />
<button type="button" id="thego" class="pre enterteam" value="click">Go</button>


答:
Try this code, i added a click (for the button) and keypress (for the text input) events

so if you click enter when you focus on the text input the text in the input will be in the array.

and the same will happen if you click "Go" button

 let namesOfPlayers = [];
 let currentElement = document.getElementById("bind");
 let button = currentElement.nextElementSibling;
 let addPlayer = () => {
   namesOfPlayers.push(currentElement.value);
   console.log(namesOfPlayers); // Just for testing
 }
currentElement.addEventListener('keypress', function (e) {
    if (e.which === 13 || e.keyCode === 13) {
        addPlayer();
    }
});

button.addEventListener('click', addPlayer);```
<pre class="snippet-code-html lang-html prettyprint-override"><code>   <input type="text"
               class="theplayer pre"
               name="Player"
               id="bind"
               placeholder="Enter Names"
                />
            <button type="button" id="thego" class="pre enterteam" value="click">Go</button></code>```

Title: Javascript push input into Array causes several arrays not one

Body:
Try this code, i added a click (for the button) and keypress (for the text input) events

so if you click enter when you focus on the text input the text in the input will be in the array.

and the same will happen if you click "Go" button

 let namesOfPlayers = [];
 let currentElement = document.getElementById("bind");
 let button = currentElement.nextElementSibling;
 let addPlayer = () => {
   namesOfPlayers.push(currentElement.value);
   console.log(namesOfPlayers); // Just for testing
 }
currentElement.addEventListener('keypress', function (e) {
    if (e.which === 13 || e.keyCode === 13) {
        addPlayer();
    }
});

button.addEventListener('click', addPlayer);

   <input type="text"
               class="theplayer pre"
               name="Player"
               id="bind"
               placeholder="Enter Names"
                />
            <button type="button" id="thego" class="pre enterteam" value="click">Go</button>


问:
How do you install Microsoft Visual Studio 2017 with minimal features?
The reason I ask is I want a small installation size and I only use the product for writing code for school work. I will not need 3rd party software, web capability, or integration with other software and applications.</p>

答:
In a comment now you requested for "command line to run the web installer in a certain predefined way say only download and install visual studio core editor and.net components". BTW, the recommendation including installing .NET components was a part of my original answer- now I splitted the answers, one for minimal install and this one for what you requested secondly, including .NET Visual Studio components:

The command line to install core and .net minimal is:

```<code>vs_xxxx.exe --layout %CD%\vs2017offline --lang en-US --add Microsoft.VisualStudio.Workload.ManagedDesktop
</code>```

(set your individual downloaded .exe name for 'vs_xxxx.exe', my downloaded name was for example 'vs_enterprise__873301792.1489161815.exe')

Body:
In a comment now you requested for "command line to run the web installer in a certain predefined way say only download and install visual studio core editor and.net components". BTW, the recommendation including installing .NET components was a part of my original answer- now I splitted the answers, one for minimal install and this one for what you requested secondly, including .NET Visual Studio components:

The command line to install core and .net minimal is:

vs_xxxx.exe --layout %CD%\vs2017offline --lang en-US --add Microsoft.VisualStudio.Workload.ManagedDesktop

(set your individual downloaded .exe name for 'vs_xxxx.exe', my downloaded name was for example 'vs_enterprise__873301792.1489161815.exe')


答:
You can combine the lists d and v and select the items, that contain an 'H':

```<code>[x for x in d + v if x[0] == 'H']
</code>```

Edit:
The suggestion above will create a new list in memory, that contains both d and v. To be more memory efficient, you cold use itertools.chain:

```<code>from itertools import chain
[x for x in chain(d, v) if x[0] == 'H']
</code>```

Title: Comparing 2 lists of lists (String and array)

Body:
Having a problem making a third list out of the identical strings from the two lists of String and array:

d = [('O', array([ 0.034     , -0.31900001,  1.18900001], dtype=float32)),
    ('H', array([ 0.29499999,  4.56899977,  1.44500005], dtype=float32)),
    ('O', array([ 0.30500001,  7.00199986,  1.88199997], dtype=float32)),
    ('H', array([  0.215     ,  11.07900047,   1.52199996], dtype=float32)),
    ('O', array([  0.23999999,  13.68999958,   1.99199998], dtype=float32)),
    ...]
v = [('H', array([ 0.64899999,  1.29700005,  3.33400011], dtype=float32)),
    ('O', array([-0.131     ,  3.41700006,  3.31900001], dtype=float32)),
    ('H', array([ 0.764     ,  7.69399977,  3.61800003], dtype=float32)),
    ('O', array([  0.15000001,  10.2130003 ,   3.273     ], dtype=float32)),
    ('H', array([  1.01499999,  14.08399963,   3.7420001 ], dtype=float32)),
    ...]

the result I need should contain all 'H' from both lists and all the coordinates of these H (periodically)

result = [('H', array([ 0.29499999,  4.56899977,  1.44500005], dtype=float32)),
         ('H', array([ 0.64899999,  1.29700005,  3.33400011], dtype=float32)),
         ('H', array([  0.215     ,  11.07900047,   1.52199996], dtype=float32)),
         ('H', array([ 0.764     ,  7.69399977,  3.61800003], dtype=float32)),
         ('H', array([  1.01499999,  14.08399963,   3.7420001 ],   dtype=float32)),
         ...]

Was trying different options, but getting stuck with unhashable type: 'numpy.ndarray' whenever I try to make it in a loop:

result=list(set(d[0][1:]) & set(v[0][1:]))

Many thanks for ideas, suggestions.

Body:
You can combine the lists d and v and select the items, that contain an 'H':

[x for x in d + v if x[0] == 'H']

Edit:
The suggestion above will create a new list in memory, that contains both d and v. To be more memory efficient, you cold use itertools.chain:

from itertools import chain
[x for x in chain(d, v) if x[0] == 'H']


问:
access object property in handlebar contains '.'
I am getting data from service in which  array of objects are coming like below:-

```<code>    [{
        title : 'Tilte 1',
        s.no : 1
     },
     {
        title : 'Tilte 2',
        s.no : 2
     }
    ]
</code>```

I have used handlebars templating to parse this data like below:-

```<code>{{#each this}}
   <div>
      <span>{{this.s.no}}</span>
      <h2>{{this.title}}</h2>
   </div>
{{/each}}
</code>```

In the above I am not able to access the property('s.no'). In vanilla JavaScript we can access it like this['s.no'] but in handlebars it's not working.

答:
You need to use special [] notation for properties that are not valid handlebar identifiers. Demo.</p>

```<code>{{#each this}}
   <div>
      <span>{{this.[s.no]}}</span>
      <h2>{{this.title}}</h2>
   </div>
{{/each}}
</code>```

Body:
I am getting data from service in which  array of objects are coming like below:-

    [{
        title : 'Tilte 1',
        s.no : 1
     },
     {
        title : 'Tilte 2',
        s.no : 2
     }
    ]

I have used handlebars templating to parse this data like below:-

{{#each this}}

      {{this.s.no}}

{{this.title}}

{{/each}}

In the above I am not able to access the property('s.no'). In vanilla JavaScript we can access it like this['s.no'] but in handlebars it's not working.

Body:
You need to use special [] notation for properties that are not valid handlebar identifiers. Demo.

{{#each this}}
   <div>
      <span>{{this.[s.no]}}</span>
      <h2>{{this.title}}</h2>
   </div>
{{/each}}


问:
"use of unresolved identifier 'myAlert & okAction'
I keep receiving an error on 15th and 16th lines from the bottom. It tells me:

"use of unresolved identifier 'myAlert & okAction'"

If anyone can help, it would be much appreciated.

Code:

```<code>import UIKit

class RegisterPageViewController: UIViewController {
    @IBOutlet weak var userNameTextField: UITextField!
    @IBOutlet weak var userPhoneTextField: UITextField!;
    @IBOutlet weak var userPasswordTextField: UITextField!;
    @IBOutlet weak var userConfirmPasswordTextField: UITextField!;
    @IBOutlet weak var userPlugTextField: UITextField!;

    @IBAction func RegisterButtonTapped(_ sender: Any) {
        let userName = userNameTextField.text;
        let userPhone = userPhoneTextField.text;
        let userPassword = userPasswordTextField.text;
        let userConfirmPassword = userConfirmPasswordTextField.text;
        let userPlug = userPlugTextField.text;

        // Check for empty fields
        if(userName!.isEmpty || userPhone!.isEmpty || userPassword!.isEmpty || userConfirmPassword!.isEmpty || userPlug!.isEmpty)
        {
            displayMyAlertMessage(userMessage: "All fields are required")

            return;
        }

        // check if passwords match
        if(userPassword != userConfirmPassword)
        {
         // Display an alert message
            displayMyAlertMessage(userMessage: "Passwords do not match")
            return;
        }

        // Store data
        UserDefaults.standard.set(userName, forKey: "userName")
        UserDefaults.standard.set(userName, forKey: "userPhone")
        UserDefaults.standard.set(userName, forKey: "userPassword")
        UserDefaults.standard.set(userName, forKey: "userPlug")
        UserDefaults.standard.synchronize();

        // Display alert message with confirmation
        _ = UIAlertController(title:"Alert", message:"Registration is successful. Thank you!", preferredStyle: UIAlertControllerStyle.alert);

        _ = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default){ action in
            self.dismiss(animated: true, completion:nil)
        }

        myAlert.addAction(okAction);
        self.present(myAlert, animated:true, completion:nil)
    }

    func displayMyAlertMessage(userMessage:String)
    {
        let myAlert = UIAlertController(title:"Alert", message:userMessage, preferredStyle: UIAlertControllerStyle.alert);

        let okAction = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default, handler:nil);

        myAlert.addAction(okAction);

        self.present(myAlert, animated:true, completion:nil);
    }
}
</code>```

答:
You cannot 'see' those two objects because you are trying to reference them outside of their scope. Their scope is the function in which they are defined.

Not sure why you have those two lines at all, though, if you have

```<code>displayMyAlertMessage(userMessage:)
</code>```

Body:
I keep receiving an error on 15th and 16th lines from the bottom. It tells me:

"use of unresolved identifier 'myAlert & okAction'"

If anyone can help, it would be much appreciated.

Code:

import UIKit

class RegisterPageViewController: UIViewController {
    @IBOutlet weak var userNameTextField: UITextField!
    @IBOutlet weak var userPhoneTextField: UITextField!;
    @IBOutlet weak var userPasswordTextField: UITextField!;
    @IBOutlet weak var userConfirmPasswordTextField: UITextField!;
    @IBOutlet weak var userPlugTextField: UITextField!;

    @IBAction func RegisterButtonTapped(_ sender: Any) {
        let userName = userNameTextField.text;
        let userPhone = userPhoneTextField.text;
        let userPassword = userPasswordTextField.text;
        let userConfirmPassword = userConfirmPasswordTextField.text;
        let userPlug = userPlugTextField.text;

        // Check for empty fields
        if(userName!.isEmpty || userPhone!.isEmpty || userPassword!.isEmpty || userConfirmPassword!.isEmpty || userPlug!.isEmpty)
        {
            displayMyAlertMessage(userMessage: "All fields are required")

            return;
        }

        // check if passwords match
        if(userPassword != userConfirmPassword)
        {
         // Display an alert message
            displayMyAlertMessage(userMessage: "Passwords do not match")
            return;
        }

        // Store data
        UserDefaults.standard.set(userName, forKey: "userName")
        UserDefaults.standard.set(userName, forKey: "userPhone")
        UserDefaults.standard.set(userName, forKey: "userPassword")
        UserDefaults.standard.set(userName, forKey: "userPlug")
        UserDefaults.standard.synchronize();

        // Display alert message with confirmation
        _ = UIAlertController(title:"Alert", message:"Registration is successful. Thank you!", preferredStyle: UIAlertControllerStyle.alert);

        _ = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default){ action in
            self.dismiss(animated: true, completion:nil)
        }

        myAlert.addAction(okAction);
        self.present(myAlert, animated:true, completion:nil)
    }

    func displayMyAlertMessage(userMessage:String)
    {
        let myAlert = UIAlertController(title:"Alert", message:userMessage, preferredStyle: UIAlertControllerStyle.alert);

        let okAction = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default, handler:nil);

        myAlert.addAction(okAction);

        self.present(myAlert, animated:true, completion:nil);
    }
}

Body:
You cannot 'see' those two objects because you are trying to reference them outside of their scope. Their scope is the function in which they are defined.

Not sure why you have those two lines at all, though, if you have

displayMyAlertMessage(userMessage:)


答:
After you have imported AngularJS and Angular Material (including the css file), you need to import Angular Material in your AngularJS app. To do this, you need to add the "ngMaterial" provider in your AngularJS module, like this:

var app = angular.module("myApp", ["ngMaterial"]);

(if you skip this part, it won't work).

Then you can write your HTML code as follows

```<code><div layout="row" layout-wrap>
    <div flex="80">80%</div>
    <div flex="20">20%</div>
</div>
</code>```

This will create a div that will act as a container. It will contain the elements you want to show and they will be aligned in a row and, if necessary, they will be displayed in a second row. In the flex property you can specify the width (as a percentage) of the element compared to the width of the container.

Obviously you can change the name of your Angular module and the number/ width of your html elements as you want.

And there you can see some examples and a bit of documentation

Title: Angularjs material one row with 2 columns

Body:
i am trying to achieve that, and can't figure how:

|-------------80%---------------------|----20%---|

one row with 2 columns with specific width.

i don't understand something, columns (usage in Material) are look to me like rows > in rows

|-------------------------------------|----//---|
|-------------------------------------|----//---|
|-------------------------------------|----//---|

and not like my example.

How can i achieve it?

Body:
After you have imported AngularJS and Angular Material (including the css file), you need to import Angular Material in your AngularJS app. To do this, you need to add the "ngMaterial" provider in your AngularJS module, like this:

var app = angular.module("myApp", ["ngMaterial"]);

(if you skip this part, it won't work).

Then you can write your HTML code as follows

<div layout="row" layout-wrap>
    <div flex="80">80%</div>
    <div flex="20">20%</div>
</div>

This will create a div that will act as a container. It will contain the elements you want to show and they will be aligned in a row and, if necessary, they will be displayed in a second row. In the flex property you can specify the width (as a percentage) of the element compared to the width of the container.

Obviously you can change the name of your Angular module and the number/ width of your html elements as you want.

And there you can see some examples and a bit of documentation

ContentLicense: CC BY-SA 4.0


问:
Typescript - Is this a compose syntax?
I got this definition in my assignment and I can't fully figure out exactly how it operates and what it does.

Is this a compose syntax?

f is a general function there is no specific definition.
Mainly I don't understand what is x.

```<code>const invokeN1 = (f, n) =>
    n === 0 ? (x) => x : (x) => f(invokeN1(f,n-1)(x))
</code>```

答:
What you're giving here is an invocation pattern/callback. invokeN1(func,n-1) will return a function of one variable.

Break it down:

```<code>(f,n)=>whatever
</code>```

This means invokeN1 will be a function accepting two variables, the result determined by 'whatever'. Let's look at that:

```<code>n===0?
</code>```

Check the second parameter of invokeN1 - it needs to have the same type and value as 0. Now, if it is 0 return:

```<code>(x) => x
</code>```

This is what's returned - another invocation pattern!
This represents a function of 1 argument returning the same argument. Note the (x) is the function signature here, and x is what will be returned.

What if n isn't 0?

```<code>(x) => f(invokeN1(f,n-1)(x))
</code>```

Another invocation pattern - again, a function accepting a single argument, represented as x, and returning the thing on the right- you should be able to tell recursively what that would do, right?

Title: Typescript - Is this a compose syntax?

Body:
I got this definition in my assignment and I can't fully figure out exactly how it operates and what it does.

Is this a compose syntax?

f is a general function there is no specific definition.
Mainly I don't understand what is x.

const invokeN1 = (f, n) =>
    n === 0 ? (x) => x : (x) => f(invokeN1(f,n-1)(x))

Body:
What you're giving here is an invocation pattern/callback. invokeN1(func,n-1) will return a function of one variable.

Break it down:

(f,n)=>whatever

This means invokeN1 will be a function accepting two variables, the result determined by 'whatever'. Let's look at that:

n===0?

Check the second parameter of invokeN1 - it needs to have the same type and value as 0. Now, if it is 0 return:

(x) => x

This is what's returned - another invocation pattern!
This represents a function of 1 argument returning the same argument. Note the (x) is the function signature here, and x is what will be returned.

What if n isn't 0?

(x) => f(invokeN1(f,n-1)(x))

Another invocation pattern - again, a function accepting a single argument, represented as x, and returning the thing on the right- you should be able to tell recursively what that would do, right?


问:
Return Result from Select Query in stored procedure to a List
I'm writing a stored procedure that currently contains only a SELECT query. It will be expanded to do a number of other things, which is why it has to be a stored procedure, but for now, it is a simple query.

Something like this:

```<code>SELECT name, occupation, position
FROM jobs
WHERE ...
</code>```

I'm looking to return the results of this query to be used in C#. I want to add it to a list so that I can bind it to a GridView component.

I don't know how to go about this, though. If I have to insert it into a list after returning all selected data, then that's alright, I just need to know how to properly return the data so that I can do that.

If I can return it in a format that can be popped right into a list, though, that would be ideal.

答:
May be this will help:

Getting rows from DB:

```<code>public static DataRowCollection getAllUsers(string tableName)
{
     DataSet set = new DataSet();
     SqlCommand comm = new SqlCommand();
     comm.Connection = DAL.DAL.conn;
     comm.CommandType = CommandType.StoredProcedure;
     comm.CommandText = "getAllUsers";
     SqlDataAdapter da = new SqlDataAdapter();
     da.SelectCommand = comm;
     da.Fill(set,tableName);

     DataRowCollection usersCollection = set.Tables[tableName].Rows;
     return usersCollection;
}
</code>```

Populating DataGridView from  DataRowCollection :

```<code>public static void ShowAllUsers(DataGridView grdView,string table, params string[] fields)
{
    DataRowCollection userSet = getAllUsers(table);
    foreach (DataRow user in userSet)
    {
         grdView.Rows.Add(user[fields[0]],
         user[fields[1]],
         user[fields[2]],
         user[fields[3]]);
    }
}
</code>```

Implementation :

```<code>BLL.BLL.ShowAllUsers(grdUsers,"eusers","eid","euname","eupassword","eposition");
</code>```

Body:
I'm writing a stored procedure that currently contains only a SELECT query. It will be expanded to do a number of other things, which is why it has to be a stored procedure, but for now, it is a simple query.

Something like this:

SELECT name, occupation, position
FROM jobs
WHERE ...

I'm looking to return the results of this query to be used in C#. I want to add it to a list so that I can bind it to a GridView component.

I don't know how to go about this, though. If I have to insert it into a list after returning all selected data, then that's alright, I just need to know how to properly return the data so that I can do that.

If I can return it in a format that can be popped right into a list, though, that would be ideal.

Body:
May be this will help:

Getting rows from DB:

public static DataRowCollection getAllUsers(string tableName)
{
     DataSet set = new DataSet();
     SqlCommand comm = new SqlCommand();
     comm.Connection = DAL.DAL.conn;
     comm.CommandType = CommandType.StoredProcedure;
     comm.CommandText = "getAllUsers";
     SqlDataAdapter da = new SqlDataAdapter();
     da.SelectCommand = comm;
     da.Fill(set,tableName);

     DataRowCollection usersCollection = set.Tables[tableName].Rows;
     return usersCollection;
}

Populating DataGridView from  DataRowCollection :

public static void ShowAllUsers(DataGridView grdView,string table, params string[] fields)
{
    DataRowCollection userSet = getAllUsers(table);
    foreach (DataRow user in userSet)
    {
         grdView.Rows.Add(user[fields[0]],
         user[fields[1]],
         user[fields[2]],
         user[fields[3]]);
    }
}

Implementation :

BLL.BLL.ShowAllUsers(grdUsers,"eusers","eid","euname","eupassword","eposition");


问:
Default app receives error on ripple emulation
I've just downloaded an extension for creating multi-device-hybrid-apps for Visual Studio 2013.
Before I've created a new project I've installed everything that's needed (Android SDK, ant, git cli, etc.)

Now, when I've created a blank app in Visual Studio, and ran it using ripple (nexus galaxy), I get the emulator and in the screen it says "Cannot GET /index.html".

The address shown in the address bar is localhost:4400/index.html?enableripple=cordova-3.0.0-NexusGalaxy.

Can anyone help?

答:
I had some missing files in my android folder. I'm unsure how that happened, but this fixed the problem.

Open a command prompt at the project folder and enter:

```<code>cordova platform remove android
cordova platform add android
</code>```

Then open VS 2015 and run Clean, then Rebuild.

Body:
I had some missing files in my android folder. I'm unsure how that happened, but this fixed the problem.

Open a command prompt at the project folder and enter:

cordova platform remove android
cordova platform add android

Then open VS 2015 and run Clean, then Rebuild.


问:
manipulating multidimensional array
I have a multi-dimensional array. Since the value of the string "volvo" is present twice, I want to combine those keys. Here's the source array:

```<code>Array
(

    [0] => Array
        (
            [0] => Volvo
            [1] => 22
        )

    [1] => Array
        (
            [0] => BMW
            [1] => 15
        )

    [2] => Array
        (
            [0] => Saab
            [1] => 5
        )

    [3] => Array
        (
            [0] => Volvo
            [1] => 17
        )

)
</code>```

and I'd like to convert it to this one:

```<code>Array
(

    [0] => Array
        (
            [0] => Volvo
            [1] => 39
        )

    [1] => Array
        (
            [0] => BMW
            [1] => 15
        )

    [2] => Array
        (
            [0] => Saab
            [1] => 5
        )
)
</code>```

答:
I think this would make more sense to return an associated array, that way you can do $arr["volvo"], if you're fine with an associated array, just remove the second foreach loop.

If not, this will get the correct output:

```<code><?php

$arr = Array (
    Array (
        "Volvo",
        22
    ),
    Array (
        "BMW",
        15
    ),
    Array (
        "Saab",
        5
    ),
    Array (
        "Volvo",
        17
    )
);

$tmpNewArr = Array();
foreach ($arr as $ele) {
    if (!isset($arr[$ele[0]])) {
        $tmpNewArr[$ele[0]] = 0;
    }
    $tmpNewArr[$ele[0]] += $ele[1];
}
$newArr = [];
foreach ($tmpNewArr as $key => $ele) {
    array_push($newArr,[$key,$ele]);
}

var_dump($newArr);

?>
</code>```

Here's an eval.in:

https://eval.in/766340

Title: manipulating multidimensional array

Body:
I have a multi-dimensional array. Since the value of the string "volvo" is present twice, I want to combine those keys. Here's the source array:

Array
(

    [0] => Array
        (
            [0] => Volvo
            [1] => 22
        )

    [1] => Array
        (
            [0] => BMW
            [1] => 15
        )

    [2] => Array
        (
            [0] => Saab
            [1] => 5
        )

    [3] => Array
        (
            [0] => Volvo
            [1] => 17
        )

)

and I'd like to convert it to this one:

Array
(

    [0] => Array
        (
            [0] => Volvo
            [1] => 39
        )

    [1] => Array
        (
            [0] => BMW
            [1] => 15
        )

    [2] => Array
        (
            [0] => Saab
            [1] => 5
        )
)

Body:
I think this would make more sense to return an associated array, that way you can do $arr["volvo"], if you're fine with an associated array, just remove the second foreach loop.

If not, this will get the correct output:

<?php

$arr = Array (
    Array (
        "Volvo",
        22
    ),
    Array (
        "BMW",
        15
    ),
    Array (
        "Saab",
        5
    ),
    Array (
        "Volvo",
        17
    )
);

$tmpNewArr = Array();
foreach ($arr as $ele) {
    if (!isset($arr[$ele[0]])) {
        $tmpNewArr[$ele[0]] = 0;
    }
    $tmpNewArr[$ele[0]] += $ele[1];
}
$newArr = [];
foreach ($tmpNewArr as $key => $ele) {
    array_push($newArr,[$key,$ele]);
}

var_dump($newArr);

?>

Here's an eval.in:

https://eval.in/766340


问:
Python module pexpect - how to connect to ssh server and then run bash commands
I'm new and I couldn't find a full answer to my question. So I'm asking it here.
I'm using python and the pexpect module to connect to an ssh server and run a few commands. However some of the commands don't work. I looked at the documentation and I can see that running a command like:

ls -l | grep -i <Filter>

Because I have to use the spawn command to run the bash script with a

child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > logs.txt"')

However, the way I connect to the server is by sending an ssh command with a key:

p = pexpect.spawn("ssh  -t -t NAME@IP -i ~/.ssh/Keyfile ")

So I can't run the spawn command with the bash command inside it (or can I?)

The response should be a password request because its re-directing me to another machine.

How do I use the spawn command so I can connect to the server with the key enter the password for the re-directed machine and then run a bash command.

Note: I'm trying to figure out the bash part. The Connection to the server and the re-direction + password insertion already work for me.

答:
You may send the command in the next line:</p>

```<code>ssh = pexpect.spawn('ssh  -t -t NAME@IP -i ~/.ssh/Keyfile')
#You may write expect here to check if the ask if for password or some other error or the initial banner message
ssh.sendline('password')
#You may check if the password is successful
ssh.sendline('/bin/bash -c "ls -l | grep LOG > logs.txt"');
</code>```

Body:
You may send the command in the next line:

ssh = pexpect.spawn('ssh  -t -t NAME@IP -i ~/.ssh/Keyfile')
#You may write expect here to check if the ask if for password or some other error or the initial banner message
ssh.sendline('password')
#You may check if the password is successful
ssh.sendline('/bin/bash -c "ls -l | grep LOG > logs.txt"');


问:
Quick guide to get started using Git + GitX with Xcode projects on the mac?
Using Git on the mac feels like a huge pain, and the Git documentation is just huuuuuuuuge. Maybe someone has a top secret blog article or even screencast to share, that explains the basics fairly simple and quickly?

Creating a repository. Big pain.

Opening that repository with GitX: Pain.

Working in Xcode and then committing changes: No idea, probably big pain too.

Cloning the repository to a few other developers with their own macs so they can start collaborate on the project: Oh man, my head explodes... need a doctor!

Merging those cloned repositories back somehow, so everyone gets an updated repository with the changes of anyone else: Red alert!

Right now I feel I'll need a month to grok it. Would be SO glad if someone can point out really helpful resources that don't force me to read for some days... or is there a great and thin book that explains this madness?

答:
Launch a terminal window.

Creating a repository:

```<code>cd project-dir
git init
</code>```

Opening the repository in GitX:

```<code>cd project-dir
gitx
</code>```

Committing changes:

```<code>git status
git add .  # or individual files
git commit
</code>```

(it's a good idea to set up a .gitignore file from the beginning.)

Read the Pro Git book or look at some of the video tutorials at git-scm.com to get started quickly. The one by Linus is mostly a description of the implementation plus rant against other VCSs; the second video is really useful.

Body:
Launch a terminal window.

Creating a repository:

cd project-dir
git init

Opening the repository in GitX:

cd project-dir
gitx

Committing changes:

git status
git add .  # or individual files
git commit

(it's a good idea to set up a .gitignore file from the beginning.)

Read the Pro Git book or look at some of the video tutorials at git-scm.com to get started quickly. The one by Linus is mostly a description of the implementation plus rant against other VCSs; the second video is really useful.


问:
Custom user-data reservation in ansi-c
I have a library with the following structure:

```<code>struct frame_meta_data
{
    uint8_t id;
    uint8_t general_field_1;
    uint8_t general_field_2;
    ...
    uint8_t user_data[16];
};
</code>```

And I would like users of the library to be able to save custom data into frame objects (that's what the user_data field is for).

However when trying to cast user_data into a custom structure:

```<code>frame_meta_data cur_frame;
...
#define USER_HDR ((struct my_user_header*)cur_frame.user_data)
</code>```

I get the following error:

```
warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
#define USER_HDR ((struct my_user_header*)cur_frame.user_data)
```

How can I work around this?

Thanks in advance.

答:
If you know what you are doing, you can disable that warning. There is however a potential problem.

Assume that the structure you want to use contains something that is larger than 1 byte. For example a 4-byte integer. Now if you simply cast that user_data field to your structure it is possible that the int is not aligned to 4-byte boundary as it should be. This might result in a runtime exception in some architectures.

Using memcpy should solve that problem though. And remove the warning.

Title: Custom user-data reservation in ansi-c

Body:
I have a library with the following structure:

struct frame_meta_data
{
    uint8_t id;
    uint8_t general_field_1;
    uint8_t general_field_2;
    ...
    uint8_t user_data[16];
};

And I would like users of the library to be able to save custom data into frame objects (that's what the user_data field is for).

However when trying to cast user_data into a custom structure:

frame_meta_data cur_frame;
...
#define USER_HDR ((struct my_user_header*)cur_frame.user_data)

I get the following error:

warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
#define USER_HDR ((struct my_user_header*)cur_frame.user_data)

How can I work around this?

Thanks in advance.


答:
You could use</p>

```<code>array_unique(Your_array, SORT_REGULAR);
</code>```

Title: manipulating multidimensional array

Body:
You could use

array_unique(Your_array, SORT_REGULAR);


问:
In Autofac, how do I replace the default registration with a decorator?
I ran in to some unexpected behaviour in Autofac (v4.4.0, .NET 4.6.1), which I feel may be a bug.

From the documentation:

Default Registrations

If more than one component exposes the same service, Autofac will use the last registered component as the default provider of that service:

e.g. If I do this:

```<code>    builder.RegisterType<FooOne>().As<IFoo>();
    // Next line replaces default IFoo implementation
    builder.RegisterType<FooTwo>().As<IFoo>();
</code>```

I expect (and get) an instance of FooTwo when I resolve IFoo from the container.

However, if I have already registered an IFoo, and I use the RegisterDecorator<T> function to register a decorator of IFoo, it does not replace the default registration of IFoo. e.g:

```<code>    // Register FooOne directly
    builder.RegisterType<FooOne>().As<IFoo>(); // (1)
    // Now set up a decorator
    builder.RegisterType<FooOne>().Named<IFoo>("foo");
    builder.RegisterDecorator<IFoo>((c, inner) =>
      new DecoratorFoo(inner), fromKey: "foo");
</code>```

Will resolve IFoo as an undecorated FooOne. This feels inconsistent to me; a violation of the principle of least astonishment.

You might claim that I shouldn't have line (1) at all (and the code works correctly without it) - but it's an accepted idiom (e.g. here) to use a plug-in to replace registrations.

In my case, this bug manisfested in a fairly large codebase where the wrapped type was already registered by a convention and, now needing to be decorated, requires a significant re-think of how registration is done.

A Gist suitable for LINQPad demonstrating the issue is here.

Is there any design reason for the observed behaviour that I am missing? Is there a way to have the decorator registration replace the default?

答:
You can see open issue about your problem here. In discussion there you can find reasoning behind this behavior. They are trying to fix this as I understand, but it turns out it is not quite trivial because of inner workings of autofac.

Meanwhile as a workaround you can register your decorator like this:

```<code>builder.Register((cnt, parameters) => new DecoratorFoo(cnt.ResolveNamed<IFoo>("foo", parameters))).As<IFoo>();
</code>```

This will also fix another issue\bug (mentioned in this stackoverflow question) which you might experience (or not) later, related to the fact decorator will not propagate parameters forward to decorated object.

Body:
I ran in to some unexpected behaviour in Autofac (v4.4.0, .NET 4.6.1), which I feel may be a bug.

From the documentation:

Default Registrations

If more than one component exposes the same service, Autofac will use the last registered component as the default provider of that service:

e.g. If I do this:

    builder.RegisterType<FooOne>().As<IFoo>();
    // Next line replaces default IFoo implementation
    builder.RegisterType<FooTwo>().As<IFoo>();

I expect (and get) an instance of FooTwo when I resolve IFoo from the container.

However, if I have already registered an IFoo, and I use the RegisterDecorator<T> function to register a decorator of IFoo, it does not replace the default registration of IFoo. e.g:

    // Register FooOne directly
    builder.RegisterType<FooOne>().As<IFoo>(); // (1)
    // Now set up a decorator
    builder.RegisterType<FooOne>().Named<IFoo>("foo");
    builder.RegisterDecorator<IFoo>((c, inner) =>
      new DecoratorFoo(inner), fromKey: "foo");

Will resolve IFoo as an undecorated FooOne. This feels inconsistent to me; a violation of the principle of least astonishment.

You might claim that I shouldn't have line (1) at all (and the code works correctly without it) - but it's an accepted idiom (e.g. here) to use a plug-in to replace registrations.

In my case, this bug manisfested in a fairly large codebase where the wrapped type was already registered by a convention and, now needing to be decorated, requires a significant re-think of how registration is done.

A Gist suitable for LINQPad demonstrating the issue is here.

Is there any design reason for the observed behaviour that I am missing? Is there a way to have the decorator registration replace the default?

Body:
You can see open issue about your problem here. In discussion there you can find reasoning behind this behavior. They are trying to fix this as I understand, but it turns out it is not quite trivial because of inner workings of autofac.

Meanwhile as a workaround you can register your decorator like this:

builder.Register((cnt, parameters) => new DecoratorFoo(cnt.ResolveNamed<IFoo>("foo", parameters))).As<IFoo>();

This will also fix another issue\bug (mentioned in this stackoverflow question) which you might experience (or not) later, related to the fact decorator will not propagate parameters forward to decorated object.


问:
How to make temporary un-hit-testable paths in paper.js?
I need to make temporary paths (which will get removed once some operation is completed) using paper.js but I do not want them to be available in the HitResult.

I can achieve this by adding a flag to such paths, have a wrapper function over HitTest api which removes such paths from the result.

But I do not think this is a good design. HitTest calculations can be sped up if such paths are ignored at initial stages.

Is there any other option to achieve this?

答:
You can set the item as locked to skip it in the hitTest calculations.

```<code>var path = new Path.Circle(new Point(100, 70), 50);
path.fillColor = 'black';
path.locked = true;

function onMouseDown(e) {
  console.log(e.item);
}
</code>```

And a Sketch here

Quoting this thread:

For now it only affects Item#hitTest(). Any item that is locked is skipped there.

Body:
You can set the item as locked to skip it in the hitTest calculations.

var path = new Path.Circle(new Point(100, 70), 50);
path.fillColor = 'black';
path.locked = true;

function onMouseDown(e) {
  console.log(e.item);
}

And a Sketch here

Quoting this thread:

For now it only affects Item#hitTest(). Any item that is locked is skipped there.


答:
Reinterpreting addresses like that isn't allowed by the C standard. Strict aliasing means that compilers are free to assume two pointers of different types will never point at the same object, and then make all sorts of optimizations based of that.

Your code violates the C standard and has undefined behavior on account of that. But you can fix it still. Like melpomene suggested in the comments, don't cast, but use memcpy:

```<code>struct my_user_header obj;
memcpy(&obj, cur_frame.user_data, sizeof obj);
</code>```

Alternatively, some compilers allow you to write non-standard code with compiler option, such as GCC's -fno-strict-aliasing.

Title: Custom user-data reservation in ansi-c

Body:
Reinterpreting addresses like that isn't allowed by the C standard. Strict aliasing means that compilers are free to assume two pointers of different types will never point at the same object, and then make all sorts of optimizations based of that.

Your code violates the C standard and has undefined behavior on account of that. But you can fix it still. Like melpomene suggested in the comments, don't cast, but use memcpy:

struct my_user_header obj;
memcpy(&obj, cur_frame.user_data, sizeof obj);

Alternatively, some compilers allow you to write non-standard code with compiler option, such as GCC's -fno-strict-aliasing.


问:
SSDT Equivalent for Oracle Database
In SSDT there is a mechanism for managing DDL changes, for instance a new column or a change to a data type. Instead of putting an 'Alter Table' statement into the database project, instead we edit that original 'Create Table' statement which focuses on the final state that includes the new column. It detects the difference between older and new script and creates necessary 'Alter Table' script to use for deployment.

Is there any equivalent strategy to achieve the same in Oracle Database as I am using J2EE technologies and Eclipse IDE.

答:
Well, there is "Oracle Developer Tools for Visual Studio" .

I haven't looked at this for 5+ years but it used to do some of the same things that the old Visual Studio Database Tools (datadude/dbproj/other names) did back then.

Title: SSDT Equivalent for Oracle Database


问:
Why does $("body") == $("body") return false?
How come the equation in the title is false? How do check if two jQuery selectors point to the same DOM object?</p>

答:
You are comparing two distinct jQuery objects because you call $() twice (once for each side of the equation), and as MooGoo explains jQuery creates new wrapper objects for each time you call it. That's why the comparison ends up returning false.

You can extract a DOM object from each jQuery object by either using get() or array dereferencing, then compare these elements. The following both return true because both identical selectors match the same body DOM element:

```<code>$('body').get(0) == $('body').get(0)
$('body')[0] == $('body')[0]
</code>```

If you want to test against a jQuery selector, use is(). Note that, unless your selectors are identical, the selectors you use may not necessarily match the same DOM elements (it's still better to use the above). This also returns true:

```<code>$('body').is('body')
</code>```

Body:
You are comparing two distinct jQuery objects because you call $() twice (once for each side of the equation), and as MooGoo explains jQuery creates new wrapper objects for each time you call it. That's why the comparison ends up returning false.

You can extract a DOM object from each jQuery object by either using get() or array dereferencing, then compare these elements. The following both return true because both identical selectors match the same body DOM element:

$('body').get(0) == $('body').get(0)
$('body')[0] == $('body')[0]

If you want to test against a jQuery selector, use is(). Note that, unless your selectors are identical, the selectors you use may not necessarily match the same DOM elements (it's still better to use the above). This also returns true:

$('body').is('body')


问:
Python class inheritance __init__
So, here's the problem..

if you do this:

```<code>class x(object):
  def __init__(self):
    pass
</code>```

why would you explicitly call init in child class to access parent class attribute? (class y has class x attribute anyway.)

```<code>class y(x):
  def __init__(self):
    x.__init__(self)
</code>```

Cheers.

Edit:

I read this article https://linuxmeerkat.wordpress.com/2015/04/28/why-you-should-use-super-in-python/, it says "In real life we tend to run the initializer for every parent class. This is simply because of how program designs tend to be. In our simple example a way to solve this is to explicitly call the initializer of A:" Could someone please explain?

答:
The fact is that in python there is a clear distinction between class and instance attributes:

Attributes declared in the class body, outside any method, are class attributes, they are the same for each object of that class and are the ones that are inherited by the subclasses. Be aware of the fact that doing instance_obj.class_att = something doesn't change the value of the class attribute, but simply creates an instance attribute and hides the shared class attribute for that object.

Instance attributes are the ones that are declared with syntax instance_obj.att = something, they are not shared between instances and are the most similar thing to non-static attributes that you have in other programming languages and they are usually created in the init method.self is just a convention to indicate the instance object automatically passed to methods.

Here's an example:

```<code>class MyClass:
    c = 1                    #class attribute, the subclasses will inherit this
    def __init__(self):
        self.i = 1           #instance attribute

MyClass.c     #access attribute c of class MyClass
MyClass.i     #error! MyClass has no attribute i
x = MyClass() #calling __init__ creates instance attribute i for obj x
x.i           #access instance attribute i of object x
x.c           #access class attribute c of class MyClass
x.c = 2       #hide MyClass.c and create instance attribute c for obj x
x.c           #access instance attribute c of obj x
</code>```

So, to sum up, doing:

```<code>class y(x):
    def __init__(self):
        x.__init__(self)
</code>```

is useful because if the base class would have been something like this

```<code>class x:
    def __init__(self):
        self.i=1
</code>```

you would have not been able to access the attribute i from any instances of y simply because they would not have it.

Title: Python class inheritance __init__

Body:
So, here's the problem..

if you do this:

class x(object):
  def __init__(self):
    pass

why would you explicitly call init in child class to access parent class attribute? (class y has class x attribute anyway.)

class y(x):
  def __init__(self):
    x.__init__(self)

Cheers.

Edit:

I read this article https://linuxmeerkat.wordpress.com/2015/04/28/why-you-should-use-super-in-python/, it says "In real life we tend to run the initializer for every parent class. This is simply because of how program designs tend to be. In our simple example a way to solve this is to explicitly call the initializer of A:" Could someone please explain?

Body:
The fact is that in python there is a clear distinction between class and instance attributes:

Attributes declared in the class body, outside any method, are class attributes, they are the same for each object of that class and are the ones that are inherited by the subclasses. Be aware of the fact that doing instance_obj.class_att = something doesn't change the value of the class attribute, but simply creates an instance attribute and hides the shared class attribute for that object.

Instance attributes are the ones that are declared with syntax instance_obj.att = something, they are not shared between instances and are the most similar thing to non-static attributes that you have in other programming languages and they are usually created in the init method.self is just a convention to indicate the instance object automatically passed to methods.

Here's an example:

class MyClass:
    c = 1                    #class attribute, the subclasses will inherit this
    def __init__(self):
        self.i = 1           #instance attribute

MyClass.c     #access attribute c of class MyClass
MyClass.i     #error! MyClass has no attribute i
x = MyClass() #calling __init__ creates instance attribute i for obj x
x.i           #access instance attribute i of object x
x.c           #access class attribute c of class MyClass
x.c = 2       #hide MyClass.c and create instance attribute c for obj x
x.c           #access instance attribute c of obj x

So, to sum up, doing:

class y(x):
    def __init__(self):
        x.__init__(self)

is useful because if the base class would have been something like this

class x:
    def __init__(self):
        self.i=1

you would have not been able to access the attribute i from any instances of y simply because they would not have it.


问:
I want {{dish.name}} to be displayed in an html page.
I'm new to angularjs. I've encountered a problem. I want {{dish.name}} to be displayed in html page. I've inserted it, but don't know as to why it isn't being displayed. Here is my code.

```<code>            <!DOCTYPE html>
            <html lang="en" ng-app="confusionApp">

            <head>
                <meta charset="utf-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <!-- The above 3 meta tags *must* come first in the head; any other head
                     content must come *after* these tags -->
                <title>Ristorante Con Fusion: Menu</title>
                <!-- Bootstrap -->
                <link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
                <link href="../bower_components/bootstrap/dist/css/bootstrap-theme.min.css" rel="stylesheet">
                <link href="../bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet">
                <link href="styles/bootstrap-social.css" rel="stylesheet">
                <link href="styles/mystyles.css" rel="stylesheet">

                <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
                <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
                <!--[if lt IE 9]>
                <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
                <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
                <![endif]-->
            </head>

            <body>

            <div class="container">
                <div class="row row-content">
                    <div class="col-xs-12" ng-controller="dishDetailController">
                        <h2 class="media-heading">
                            {{dish.name}} <!-- I want this to be displayed -->
                        </h2>
                    </div>
                    <div class="col-xs-9 col-xs-offset-1">
                        <p>Put the comments here</p>
                    </div>
                </div>

            </div>

            <script src="../bower_components/angular/angular.min.js"></script>
            <script>

                var app = angular.module('confusionApp',[]);

                app.controller('dishDetailController', function() {

                    var dish={
                        name:'Uthapizza',
                        image: 'images/uthapizza.png',
                        category: 'mains',
                        label:'Hot',
                        price:'4.99',
                        description:'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.',
                        comments: [
                            {
                                rating:5,
                                comment:"Imagine all the eatables, living in conFusion!",
                                author:"John Lemon",
                                date:"2012-10-16T17:57:28.556094Z"
                            },
                            {
                                rating:4,
                                comment:"Sends anyone to heaven, I wish I could get my mother-in-law to eat it!",
                                author:"Paul McVites",
                                date:"2014-09-05T17:57:28.556094Z"
                            },
                            {
                                rating:3,
                                comment:"Eat it, just eat it!",
                                author:"Michael Jaikishan",
                                date:"2015-02-13T17:57:28.556094Z"
                            },
                            {
                                rating:4,
                                comment:"Ultimate, Reaching for the stars!",
                                author:"Ringo Starry",
                                date:"2013-12-02T17:57:28.556094Z"
                            },
                            {
                                rating:2,
                                comment:"It's your birthday, we're gonna party!",
                                author:"25 Cent",
                                date:"2011-12-02T17:57:28.556094Z"
                            }

                        ]
                    };

                    this.dish = dish;

                });

            </script>

            </body>

            </html>
</code>```

The {{dish.name}} is located under row-content div which is located under container

答:
Just replace with:

```<code>app.controller('dishDetailController', function($scope) {

                    $scope.dish={
                        name:'Uthapizza',
                        image: 'images/uthapizza.png',
                        category: 'mains',
                        label:'Hot',
                        price:'4.99',
                        description:'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.',
                        comments: [
                            {
</code>```

Basically there are two ways to achieve this:

1- Make an alias of your controller using ng-controller="fooController as bar" and then in your markup you use that alias (Not Recommended)

2- A much cleaner implementation would be to inject the $scope service in your controller and use $scope.abc = {name:'Test'} and in the markup you do {{abc.name}} which is termed as interpolation binding.

Body:
I'm new to angularjs. I've encountered a problem. I want {{dish.name}} to be displayed in html page. I've inserted it, but don't know as to why it isn't being displayed. Here is my code.

            <!DOCTYPE html>

                <meta charset="utf-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initial-scale=1">

                <title>Ristorante Con Fusion: Menu</title>

                <link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
                <link href="../bower_components/bootstrap/dist/css/bootstrap-theme.min.css" rel="stylesheet">
                <link href="../bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet">
                <link href="styles/bootstrap-social.css" rel="stylesheet">
                <link href="styles/mystyles.css" rel="stylesheet">

                            {{dish.name}}

Put the comments here

The {{dish.name}} is located under row-content div which is located under container

Body:
Just replace with:

app.controller('dishDetailController', function($scope) {

                    $scope.dish={
                        name:'Uthapizza',
                        image: 'images/uthapizza.png',
                        category: 'mains',
                        label:'Hot',
                        price:'4.99',
                        description:'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.',
                        comments: [
                            {

Basically there are two ways to achieve this:

1- Make an alias of your controller using ng-controller="fooController as bar" and then in your markup you use that alias (Not Recommended)

2- A much cleaner implementation would be to inject the $scope service in your controller and use $scope.abc = {name:'Test'} and in the markup you do {{abc.name}} which is termed as interpolation binding.


问:
No property findAllEntries found for type Entry
I don't know why Spring doesn't like my code:

I have Entry.java:

```<code>@Entity
@Table(name = "entries")
public class Entry {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "text")
    private String text;
}
</code>```

EntryDao.java:

```<code>public interface EntryDao extends JpaRepository<Entry, Long> {
    List<Entry> findAllEntries();
}
</code>```

EntryService.java:

```<code>@Service
public interface EntryService {

    List<Entry> findAllEntries();

}
</code>```

EntryServiceImpl.java:

```<code>public class EntryServiceImpl implements EntryService {
    private EntryDao entryDao;
    private SessionFactory sessionFactory;

    @Override
    @SuppressWarnings("unchecked")
    public List<Entry> findAllEntries()  {
        Session session = this.sessionFactory.getCurrentSession();
        List<Entry> entries = session.createQuery("from entries").list();
        return entries;
    }
}
</code>```

This code gives me an error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entryDao': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property findAllEntries found for type Entry!

I don't understand how to handle this error and why this error occurs.

答:
As @AbdullahWasi said, just use the existing findAll() method from SpringData for your code. You might want to place a @Transactional annotation in your code, but that depends on your transaction boundaries.

Just remove your custom method from your Dao.

```<code>public interface EntryDao extends JpaRepository<Entry, Long> {
}
</code>```

And use the default spring data findAll

```<code>@Transactional
public class EntryServiceImpl implements EntryService {
    private EntryDao entryDao;
    private SessionFactory sessionFactory;

    @Override
    @SuppressWarnings("unchecked")
    public List<Entry> findAllEntries()  {
        return entryDao.findAll();
    }
}
</code>```

Body:
I don't know why Spring doesn't like my code:

I have Entry.java:

@Entity
@Table(name = "entries")
public class Entry {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "text")
    private String text;
}

EntryDao.java:

public interface EntryDao extends JpaRepository<Entry, Long> {
    List<Entry> findAllEntries();
}

EntryService.java:

@Service
public interface EntryService {

    List<Entry> findAllEntries();

}

EntryServiceImpl.java:

public class EntryServiceImpl implements EntryService {
    private EntryDao entryDao;
    private SessionFactory sessionFactory;

    @Override
    @SuppressWarnings("unchecked")
    public List<Entry> findAllEntries()  {
        Session session = this.sessionFactory.getCurrentSession();
        List<Entry> entries = session.createQuery("from entries").list();
        return entries;
    }
}

This code gives me an error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entryDao': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property findAllEntries found for type Entry!

I don't understand how to handle this error and why this error occurs.

Body:
As @AbdullahWasi said, just use the existing findAll() method from SpringData for your code. You might want to place a @Transactional annotation in your code, but that depends on your transaction boundaries.

Just remove your custom method from your Dao.

public interface EntryDao extends JpaRepository<Entry, Long> {
}

And use the default spring data findAll

@Transactional
public class EntryServiceImpl implements EntryService {
    private EntryDao entryDao;
    private SessionFactory sessionFactory;

    @Override
    @SuppressWarnings("unchecked")
    public List<Entry> findAllEntries()  {
        return entryDao.findAll();
    }
}


问:
UIBezierPath appending overlapping isn't filled
I'm trying to merge two overlapping UIBezierPaths using UIBezierPath.append, and I want the overlapping space to be filled. I tried setting the usesEvenOddFillRule property to false, but it still doesn't fill. Here is minimal example of the problem:

```<code>override func draw(_ rect: CGRect) {
    let firstShape = UIBezierPath()

    firstShape.move(to: CGPoint(x: 100, y: 100))
    firstShape.addLine(to: CGPoint(x: 100, y: 150))
    firstShape.addLine(to: CGPoint(x: 150, y: 170))
    firstShape.close()

    let secondShape = UIBezierPath(rect: CGRect(x: 125, y: 125, width: 75, height: 75))

    let combined = UIBezierPath()
    combined.append(firstShape)
    combined.append(secondShape)

    UIColor.black.setFill()
    combined.fill()
}
</code>```

This yields the following shape:

What I would like it to look like:

This problem also seems to occur when using move(to: CGPoint) on one UIBezierPath. If you would draw both these shapes on the same UIBezierPath, the same problem would occur.

Does anyone know how to make the overlapping region filled? Preferably the solution would also work when doing addClip()

答:
Just call fill before you close the first shape:</p>

```<code>firstShape.fill()
firstShape.close()
</code>```

Body:
I'm trying to merge two overlapping UIBezierPaths using UIBezierPath.append, and I want the overlapping space to be filled. I tried setting the usesEvenOddFillRule property to false, but it still doesn't fill. Here is minimal example of the problem:

override func draw(_ rect: CGRect) {
    let firstShape = UIBezierPath()

    firstShape.move(to: CGPoint(x: 100, y: 100))
    firstShape.addLine(to: CGPoint(x: 100, y: 150))
    firstShape.addLine(to: CGPoint(x: 150, y: 170))
    firstShape.close()

    let secondShape = UIBezierPath(rect: CGRect(x: 125, y: 125, width: 75, height: 75))

    let combined = UIBezierPath()
    combined.append(firstShape)
    combined.append(secondShape)

    UIColor.black.setFill()
    combined.fill()
}

This yields the following shape:

What I would like it to look like:

This problem also seems to occur when using move(to: CGPoint) on one UIBezierPath. If you would draw both these shapes on the same UIBezierPath, the same problem would occur.

Does anyone know how to make the overlapping region filled? Preferably the solution would also work when doing addClip()

Body:
Just call fill before you close the first shape:

firstShape.fill()
firstShape.close()


问:
SAS - Find and print first non-zero value from a dataset in columns
I have a data set with ID in rows and months in columns, as the one shown below.

I want to create an auxiliary column that records the first value that is not zero of each line.

```<code>ID  M1  M2  M3  M4  M5      Auxiliary column
1   0   0   8   8   7       8
2   7   7   7   .   .       7
3   0   0   0   0   9       9
4   0   9   9   9   8       9
5   1   1   1   1   1       1
6   0   2   2   1   1       2
</code>```

Currently l am using this code, but I haven't been able to get the results I am looking for. Any ideas?

```<code>data new_ops04;
set new_ops03;

array MONTHS (24) M1-M24;

RETAIN AUXILIARY_COLUMN 0;
    do i=1 to 24;
    IF MONTHS(i) ne 0 and AUXILIARY_COLUMN = 0 THEN
               AUXILIARY_COLUMN = MONTHS(i);
    end;
        drop i;
run;
</code>```

Thanks a lot!

答:
You're very close.  Just drop the retain statement:

```<code>data new_ops04;
set new_ops03;

array MONTHS (24) M1-M24;

AUXILIARY_COLUMN = 0;
do i=1 to 24;
IF MONTHS(i) ne 0 and AUXILIARY_COLUMN = 0 THEN
           AUXILIARY_COLUMN = MONTHS(i);
end;
    drop i;
run;
</code>```

you need to consider what happens if the first observation(s) are missing

Body:
I have a data set with ID in rows and months in columns, as the one shown below.

I want to create an auxiliary column that records the first value that is not zero of each line.

ID  M1  M2  M3  M4  M5      Auxiliary column
1   0   0   8   8   7       8
2   7   7   7   .   .       7
3   0   0   0   0   9       9
4   0   9   9   9   8       9
5   1   1   1   1   1       1
6   0   2   2   1   1       2

Currently l am using this code, but I haven't been able to get the results I am looking for. Any ideas?

data new_ops04;
set new_ops03;

array MONTHS (24) M1-M24;

RETAIN AUXILIARY_COLUMN 0;
    do i=1 to 24;
    IF MONTHS(i) ne 0 and AUXILIARY_COLUMN = 0 THEN
               AUXILIARY_COLUMN = MONTHS(i);
    end;
        drop i;
run;

Thanks a lot!

Body:
You're very close.  Just drop the retain statement:

data new_ops04;
set new_ops03;

array MONTHS (24) M1-M24;

AUXILIARY_COLUMN = 0;
do i=1 to 24;
IF MONTHS(i) ne 0 and AUXILIARY_COLUMN = 0 THEN
           AUXILIARY_COLUMN = MONTHS(i);
end;
    drop i;
run;

you need to consider what happens if the first observation(s) are missing


问:
Fragment onResume() & onPause() is not called on backstack
I have multiple fragment inside an activity. On a button click I am starting a new fragment, adding it to backstack. I naturally expected the onPause() method of current Fragment and onResume() of new Fragment to be called. Well it is not happening.

LoginFragment.java

```<code>public class LoginFragment extends Fragment{
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      final View view  =   inflater.inflate(R.layout.login_fragment, container, false);
      final FragmentManager mFragmentmanager =  getFragmentManager();

      Button btnHome  = (Button)view.findViewById(R.id.home_btn);
      btnHome.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view){
           HomeFragment fragment    = new HomeFragment();
           FragmentTransaction ft2   =  mFragmentmanager.beginTransaction();
           ft2.setCustomAnimations(R.anim.slide_right, R.anim.slide_out_left
                    , R.anim.slide_left, R.anim.slide_out_right);
           ft2.replace(R.id.middle_fragment, fragment);
           ft2.addToBackStack("");
           ft2.commit();
         }
      });
  }

  @Override
  public void onResume() {
     Log.e("DEBUG", "onResume of LoginFragment");
     super.onResume();
  }

  @Override
  public void onPause() {
    Log.e("DEBUG", "OnPause of loginFragment");
    super.onPause();
  }
}
</code>```

HomeFragment.java

```<code>public class HomeFragment extends Fragment{
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     final View view  =   inflater.inflate(R.layout.login_fragment, container, false);
  }

  @Override
  public void onResume() {
     Log.e("DEBUG", "onResume of HomeFragment");
     super.onResume();
  }

  @Override
  public void onPause() {
     Log.e("DEBUG", "OnPause of HomeFragment");
     super.onPause();
  }
}
</code>```

What I expected, was,

When button is clicked, LoginFragment gets replaced with
HomeFragment, onPause() of LoginFragment, and onResume() of
HomeFragment gets called

When back is pressed, HomeFragment is poped out and LoginFragment is
seen, and onPause() of HomeFragment and onResume() of LoginFragment
gets called.

What I am getting is,

When button is clicked, HomeFragment is correctly replacing
LoginFragment, onResume() of HomeFragment is called, but onPause()
of LoginFragment is never called.

When back pressed, HomeFragment is correctly popping to reveal
LoginFragment, onPause() of HomeFragment gets called, but onResume()
of LoginFragment never gets called.

Is this the normal behaviour? Why is onResume() of LoginFragment not getting called when I press the back button.

答:
onPause() method works in activity class you can use:

```<code>public void onDestroyView(){
super.onDestroyView
}
</code>```

for same purpose..

Body:
I have multiple fragment inside an activity. On a button click I am starting a new fragment, adding it to backstack. I naturally expected the onPause() method of current Fragment and onResume() of new Fragment to be called. Well it is not happening.

LoginFragment.java

public class LoginFragment extends Fragment{
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      final View view  =   inflater.inflate(R.layout.login_fragment, container, false);
      final FragmentManager mFragmentmanager =  getFragmentManager();

      Button btnHome  = (Button)view.findViewById(R.id.home_btn);
      btnHome.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view){
           HomeFragment fragment    = new HomeFragment();
           FragmentTransaction ft2   =  mFragmentmanager.beginTransaction();
           ft2.setCustomAnimations(R.anim.slide_right, R.anim.slide_out_left
                    , R.anim.slide_left, R.anim.slide_out_right);
           ft2.replace(R.id.middle_fragment, fragment);
           ft2.addToBackStack("");
           ft2.commit();
         }
      });
  }

  @Override
  public void onResume() {
     Log.e("DEBUG", "onResume of LoginFragment");
     super.onResume();
  }

  @Override
  public void onPause() {
    Log.e("DEBUG", "OnPause of loginFragment");
    super.onPause();
  }
}

HomeFragment.java

public class HomeFragment extends Fragment{
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     final View view  =   inflater.inflate(R.layout.login_fragment, container, false);
  }

  @Override
  public void onResume() {
     Log.e("DEBUG", "onResume of HomeFragment");
     super.onResume();
  }

  @Override
  public void onPause() {
     Log.e("DEBUG", "OnPause of HomeFragment");
     super.onPause();
  }
}

What I expected, was,

When button is clicked, LoginFragment gets replaced with
HomeFragment, onPause() of LoginFragment, and onResume() of
HomeFragment gets called

When back is pressed, HomeFragment is poped out and LoginFragment is
seen, and onPause() of HomeFragment and onResume() of LoginFragment
gets called.

What I am getting is,

When button is clicked, HomeFragment is correctly replacing
LoginFragment, onResume() of HomeFragment is called, but onPause()
of LoginFragment is never called.

When back pressed, HomeFragment is correctly popping to reveal
LoginFragment, onPause() of HomeFragment gets called, but onResume()
of LoginFragment never gets called.

Is this the normal behaviour? Why is onResume() of LoginFragment not getting called when I press the back button.

Body:
onPause() method works in activity class you can use:

public void onDestroyView(){
super.onDestroyView
}

for same purpose..


问:
.py files opens up in a text editor when run from cmd
Whenever I try to run a .py file from cmd it opens up in a text editor(np++). I'm trying to run the following:

```<code>django-admin.py startproject testprj
</code>```

Even if I run 'setup.py install'

答:
Your Windows file associations are set to open .py files in a text editor. You have to change those to use the python.exe interpreter, or you can prefix all your commands with python, like this:

python django-admin.py startproject testprj

If you want to change your file associations, and you are running Vista or Windows 7, you can change them in 'Control Panel'->'Default Programs'->'Associate a file type or protocol with a program'

Body:
Whenever I try to run a .py file from cmd it opens up in a text editor(np++). I'm trying to run the following:

django-admin.py startproject testprj

Even if I run 'setup.py install'


问:
Found DatabaseException: Found conflicting getters for name: isImportantForAccessibility
I am making a shopping app using firebase.I use Recycler View to show the data. Every function works fine but whenever i click on add to cart Button for indivisual item it throws an exception like this:

Log cat

```<code>04-02 11:41:57.480 1418-1418/com.app.demo E/Zygote: no v2
04-02 11:42:08.550 1418-1418/com.app.demo E/ViewRootImpl: sendUserActionEvent() mView == null
04-02 11:42:16.368 1418-1418/com.app.hdservices E/AndroidRuntime: FATAL EXCEPTION: main Process: com.app.demo,
  PID: 1418 com.google.firebase.database.DatabaseException:
  Found conflicting getters for name: isImportantForAccessibility

  at com.google.android.gms.internal.zzbtg$zza.<init>(Unknown Source)
  at com.google.android.gms.internal.zzbtg.zzi(Unknown Source)
  at com.google.android.gms.internal.zzbtg.zzaz(Unknown Source)
  at com.google.android.gms.internal.zzbtg.zzay(Unknown Source)
  at com.google.firebase.database.DatabaseReference.zza(Unknown Source)
  at com.google.firebase.database.DatabaseReference.setValue(Unknown Source)
  at com.app.hdservices.Veglist$VegViewHolder$3.onClick(Veglist.java:258)
  at android.view.View.performClick(View.java:5716)
  at android.widget.TextView.performClick(TextView.java:10926)
  at android.view.View$PerformClick.run(View.java:22596)
  at android.os.Handler.handleCallback(Handler.java:739)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:148)
  at android.app.ActivityThread.main(ActivityThread.java:7325)
  at java.lang.reflect.Method.invoke(Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
</code>```

Veglist.java

```<code>    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_veglist);

        mAuth=FirebaseAuth.getInstance();
        mAuthListener=new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(FirebaseAuth firebaseAuth) {

                if(firebaseAuth.getCurrentUser()==null)
                {
                    Intent i=new Intent(Veglist.this,Login.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);

                }

            }
        };

        mainReference = FirebaseDatabase.getInstance().getReference().child("Vegetable");
        cartReference = FirebaseDatabase.getInstance().getReference().child("Cart");
        cartobject = cartReference.child(mAuth.getCurrentUser().getUid()).push();

        mainRecyclerView=(RecyclerView)findViewById(R.id.recyclerview);
        mainRecyclerView.setHasFixedSize(true);
        mainRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        mainReference.keepSynced(true);
        cartReference.keepSynced(true);
        cartobject.keepSynced(true);

   Toolbar toolbar = (Toolbar) findViewById(R.id.newToolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("Fresh Vegetables");
        getSupportActionBar().getThemedContext();
        toolbar.setTitleTextColor(0xFFFFFFFF);

    }

public static class VegViewHolder extends RecyclerView.ViewHolder {

        public View mView;
        private ImageView postImage;
        private TextView quantityBox,postVegName,postPrice,postPriceTag;
        private ImageButton reducequantityButton,increaseQuantityButton;
        private Button add;
        private String mPostKey=null;
        String totalCost;
        private  DatabaseReference cartReference;
        private DatabaseReference cartobject;
        private FirebaseAuth mAuth;

        public VegViewHolder(final View itemView) {
            super(itemView);
            mView = itemView;

            mAuth=FirebaseAuth.getInstance();

            cartReference = FirebaseDatabase.getInstance().getReference().child("Cart");
            cartobject = cartReference.child(mAuth.getCurrentUser().getUid()).push();

            add=(Button)mView.findViewById(R.id.add);
            quantityBox=(TextView)mView.findViewById(R.id.quantity);
            reducequantityButton = (ImageButton) mView.findViewById(R.id.downQuantitybutton);
            increaseQuantityButton = (ImageButton) mView.findViewById(R.id.upQuantitybutton);

                    quantityBox.setText("1");

            increaseQuantityButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {

                        int i = Integer.parseInt(quantityBox.getText().toString());
                        int j = i + 1;
                        String k = String.valueOf(j);
                        quantityBox.setText(k);
                    } catch (Exception e) {
                        Toast.makeText(itemView.getContext(), "Quantity can only be a number", Toast.LENGTH_SHORT).show();
                    }
                }
            });

        reducequantityButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {

                    if (Integer.parseInt(quantityBox.getText().toString()) <= 1) {
                        Toast.makeText(itemView.getContext(), "Quantity can't be less than 1", Toast.LENGTH_SHORT).show();
                    } else {
                        int i = Integer.parseInt(quantityBox.getText().toString());
                        int j = i - 1;
                        String k = String.valueOf(j);
                        quantityBox.setText(k);
                    }

                } catch (Exception e) {
                    Toast.makeText(itemView.getContext(), "Quantity can only be a number", Toast.LENGTH_SHORT).show();
                }
            }
        });

              add.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
                     final ProgressDialog p=new ProgressDialog(mView.getContext());
                      p.setMessage("Wait! Adding to cart ..");
                      p.show();

                      cartobject.child("Image").setValue(postImage);
                      cartobject.child("Name").setValue(postVegName);
                      cartobject.child("Price").setValue(postPrice);
                      cartobject.child("PriceTag").setValue(postPriceTag);
                      cartobject.child("Quantity").setValue(quantityBox.getText().toString());

                      totalCost = String.valueOf(Integer.parseInt(quantityBox.getText().toString()) * Integer.parseInt(postPrice.getText().toString()));

                      cartobject.child("Total").setValue(totalCost).addOnSuccessListener(new OnSuccessListener<Void>() {
                          @Override
                          public void onSuccess(Void aVoid) {
                              p.dismiss();
                              Toast.makeText(mView.getContext(), postVegName + " successfully added to cart! ", Toast.LENGTH_SHORT).show();
                          }

                      });
                  }
              });

            }

        public void setName(String name) {
            postVegName = (TextView) mView.findViewById(R.id.vegName);
            postVegName.setText(name);

        }

        public void setPrice(String price) {
            postPrice = (TextView) mView.findViewById(R.id.VegPrice);
            postPrice.setText(price);

        }

        public void setPriceTag(String priceTag)
        {
            postPriceTag=(TextView)mView.findViewById(R.id.PriceTag);
            postPriceTag.setText(priceTag);
        }

        public void setImage(Context context, String image) {
            postImage = (ImageView) mView.findViewById(R.id.VegImg);
            Picasso.with(context).load(image).into(postImage);
        }

    }
</code>```

答:
These calls to setValue() are the problem:

```<code>cartobject.child("Image").setValue(postImage);
cartobject.child("Name").setValue(postVegName);
cartobject.child("Price").setValue(postPrice);
cartobject.child("PriceTag").setValue(postPriceTag);
</code>```

You cannot store a View in the Firebase database.  You probably meant to store the value contained in the view, for example:

```<code>cartobject.child("Name").setValue(postVegName.getText().toString().trim());
</code>```

Body:
I am making a shopping app using firebase.I use Recycler View to show the data. Every function works fine but whenever i click on add to cart Button for indivisual item it throws an exception like this:

Log cat

04-02 11:41:57.480 1418-1418/com.app.demo E/Zygote: no v2
04-02 11:42:08.550 1418-1418/com.app.demo E/ViewRootImpl: sendUserActionEvent() mView == null
04-02 11:42:16.368 1418-1418/com.app.hdservices E/AndroidRuntime: FATAL EXCEPTION: main Process: com.app.demo,
  PID: 1418 com.google.firebase.database.DatabaseException:
  Found conflicting getters for name: isImportantForAccessibility

  at com.google.android.gms.internal.zzbtg$zza.<init>(Unknown Source)
  at com.google.android.gms.internal.zzbtg.zzi(Unknown Source)
  at com.google.android.gms.internal.zzbtg.zzaz(Unknown Source)
  at com.google.android.gms.internal.zzbtg.zzay(Unknown Source)
  at com.google.firebase.database.DatabaseReference.zza(Unknown Source)
  at com.google.firebase.database.DatabaseReference.setValue(Unknown Source)
  at com.app.hdservices.Veglist$VegViewHolder$3.onClick(Veglist.java:258)
  at android.view.View.performClick(View.java:5716)
  at android.widget.TextView.performClick(TextView.java:10926)
  at android.view.View$PerformClick.run(View.java:22596)
  at android.os.Handler.handleCallback(Handler.java:739)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:148)
  at android.app.ActivityThread.main(ActivityThread.java:7325)
  at java.lang.reflect.Method.invoke(Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Veglist.java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_veglist);

        mAuth=FirebaseAuth.getInstance();
        mAuthListener=new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(FirebaseAuth firebaseAuth) {

                if(firebaseAuth.getCurrentUser()==null)
                {
                    Intent i=new Intent(Veglist.this,Login.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);

                }

            }
        };

        mainReference = FirebaseDatabase.getInstance().getReference().child("Vegetable");
        cartReference = FirebaseDatabase.getInstance().getReference().child("Cart");
        cartobject = cartReference.child(mAuth.getCurrentUser().getUid()).push();

        mainRecyclerView=(RecyclerView)findViewById(R.id.recyclerview);
        mainRecyclerView.setHasFixedSize(true);
        mainRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        mainReference.keepSynced(true);
        cartReference.keepSynced(true);
        cartobject.keepSynced(true);

   Toolbar toolbar = (Toolbar) findViewById(R.id.newToolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("Fresh Vegetables");
        getSupportActionBar().getThemedContext();
        toolbar.setTitleTextColor(0xFFFFFFFF);

    }

public static class VegViewHolder extends RecyclerView.ViewHolder {

        public View mView;
        private ImageView postImage;
        private TextView quantityBox,postVegName,postPrice,postPriceTag;
        private ImageButton reducequantityButton,increaseQuantityButton;
        private Button add;
        private String mPostKey=null;
        String totalCost;
        private  DatabaseReference cartReference;
        private DatabaseReference cartobject;
        private FirebaseAuth mAuth;

        public VegViewHolder(final View itemView) {
            super(itemView);
            mView = itemView;

            mAuth=FirebaseAuth.getInstance();

            cartReference = FirebaseDatabase.getInstance().getReference().child("Cart");
            cartobject = cartReference.child(mAuth.getCurrentUser().getUid()).push();

            add=(Button)mView.findViewById(R.id.add);
            quantityBox=(TextView)mView.findViewById(R.id.quantity);
            reducequantityButton = (ImageButton) mView.findViewById(R.id.downQuantitybutton);
            increaseQuantityButton = (ImageButton) mView.findViewById(R.id.upQuantitybutton);

                    quantityBox.setText("1");

            increaseQuantityButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {

                        int i = Integer.parseInt(quantityBox.getText().toString());
                        int j = i + 1;
                        String k = String.valueOf(j);
                        quantityBox.setText(k);
                    } catch (Exception e) {
                        Toast.makeText(itemView.getContext(), "Quantity can only be a number", Toast.LENGTH_SHORT).show();
                    }
                }
            });

        reducequantityButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {

                    if (Integer.parseInt(quantityBox.getText().toString()) <= 1) {
                        Toast.makeText(itemView.getContext(), "Quantity can't be less than 1", Toast.LENGTH_SHORT).show();
                    } else {
                        int i = Integer.parseInt(quantityBox.getText().toString());
                        int j = i - 1;
                        String k = String.valueOf(j);
                        quantityBox.setText(k);
                    }

                } catch (Exception e) {
                    Toast.makeText(itemView.getContext(), "Quantity can only be a number", Toast.LENGTH_SHORT).show();
                }
            }
        });

              add.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
                     final ProgressDialog p=new ProgressDialog(mView.getContext());
                      p.setMessage("Wait! Adding to cart ..");
                      p.show();

                      cartobject.child("Image").setValue(postImage);
                      cartobject.child("Name").setValue(postVegName);
                      cartobject.child("Price").setValue(postPrice);
                      cartobject.child("PriceTag").setValue(postPriceTag);
                      cartobject.child("Quantity").setValue(quantityBox.getText().toString());

                      totalCost = String.valueOf(Integer.parseInt(quantityBox.getText().toString()) * Integer.parseInt(postPrice.getText().toString()));

                      cartobject.child("Total").setValue(totalCost).addOnSuccessListener(new OnSuccessListener<Void>() {
                          @Override
                          public void onSuccess(Void aVoid) {
                              p.dismiss();
                              Toast.makeText(mView.getContext(), postVegName + " successfully added to cart! ", Toast.LENGTH_SHORT).show();
                          }

                      });
                  }
              });

            }

        public void setName(String name) {
            postVegName = (TextView) mView.findViewById(R.id.vegName);
            postVegName.setText(name);

        }

        public void setPrice(String price) {
            postPrice = (TextView) mView.findViewById(R.id.VegPrice);
            postPrice.setText(price);

        }

        public void setPriceTag(String priceTag)
        {
            postPriceTag=(TextView)mView.findViewById(R.id.PriceTag);
            postPriceTag.setText(priceTag);
        }

        public void setImage(Context context, String image) {
            postImage = (ImageView) mView.findViewById(R.id.VegImg);
            Picasso.with(context).load(image).into(postImage);
        }

    }

Body:
These calls to setValue() are the problem:

cartobject.child("Image").setValue(postImage);
cartobject.child("Name").setValue(postVegName);
cartobject.child("Price").setValue(postPrice);
cartobject.child("PriceTag").setValue(postPriceTag);

You cannot store a View in the Firebase database.  You probably meant to store the value contained in the view, for example:

cartobject.child("Name").setValue(postVegName.getText().toString().trim());