问:
I'm trying to change state on a parent component from a child component based on data rendering in the child
I am trying to change state for my parent component based on data coming in through the child component. I can't figure out how to change a parent without a button. this.state.rows on the child element comes in from a database and I want to change the state so I can show a spinning icon while the data loads.

```<code>class Parent extends Component{
  constructor(props){
    super();
    this.state={
      spinner=false
    }
    this.spinnerUpdate = this.spinnerUpdate.bind(this)
  }

  spinnerUpdate(){}

  render(){
    return(
      <Child spinner={this.spinnerUpdate}/>
    )
  }
}

class Child extends Component{
  constructor(props){
    super(props);
    this.state={
      rows: rows,
    }
    this.spinner = this.spinner.bind(this)
  }

  spinner(){
    if(this.state.rows){
      this.setState({spinner: true})
    }
  }

  render(){
    return(
      <div>
        //random info
      </div>
    )
  }
}
</code>```

I expected the spinner function in the child component to change the state of the parent state when the data gets rendered.

答:
Child component will receive spinner in props passed from Parent component.

```<code>    class Parent extends Component{
        constructor(props){
         ...
          this.spinnerUpdate = this.spinnerUpdate.bind(this)
        }

      //will receive one param from Child component to hide/show spinner.
        spinnerUpdate(spinnerStatus){
            this.setState({spinner: spinnerStatus})
        }

        render(){
          return(
            <Child spinner={this.spinnerUpdate}/>
          )
        }
      }

      class Child extends Component{
        constructor(props){
          ...
        }

        spinner(){

   //call spinner of parent based on matched criteria
          if(this.state.rows){
            this.props.spinner(true);
          }else{
            this.props.spinner(false);
          }
        }

        render(){
          return(
            <div>
              //random info
            </div>
          )
        }
      }
</code>```

Body:
I am trying to change state for my parent component based on data coming in through the child component. I can't figure out how to change a parent without a button. this.state.rows on the child element comes in from a database and I want to change the state so I can show a spinning icon while the data loads.

class Parent extends Component{
  constructor(props){
    super();
    this.state={
      spinner=false
    }
    this.spinnerUpdate = this.spinnerUpdate.bind(this)
  }

  spinnerUpdate(){}

  render(){
    return(
      <Child spinner={this.spinnerUpdate}/>
    )
  }
}

class Child extends Component{
  constructor(props){
    super(props);
    this.state={
      rows: rows,
    }
    this.spinner = this.spinner.bind(this)
  }

  spinner(){
    if(this.state.rows){
      this.setState({spinner: true})
    }
  }

  render(){
    return(

        //random info

    )
  }
}

I expected the spinner function in the child component to change the state of the parent state when the data gets rendered.

Body:
Child component will receive spinner in props passed from Parent component.

    class Parent extends Component{
        constructor(props){
         ...
          this.spinnerUpdate = this.spinnerUpdate.bind(this)
        }

      //will receive one param from Child component to hide/show spinner.
        spinnerUpdate(spinnerStatus){
            this.setState({spinner: spinnerStatus})
        }

        render(){
          return(
            <Child spinner={this.spinnerUpdate}/>
          )
        }
      }

      class Child extends Component{
        constructor(props){
          ...
        }

        spinner(){

   //call spinner of parent based on matched criteria
          if(this.state.rows){
            this.props.spinner(true);
          }else{
            this.props.spinner(false);
          }
        }

        render(){
          return(
            <div>
              //random info
            </div>
          )
        }
      }


来源: stackexchange

问:
Python - input from a user
I am planning to configure a switch using python script and the sample code is below.
Values like interface name , ip address are to be obtained from the user and I want my output to be list as shown below:

```<code>    int_device_configs = ['interface GigabitEthernet0/0^
    ip address 192.168.1.2 255.255.255.0','interface GigabitEthernet0/1^
    ip address 192.168.9.10 255.255.255.0,'interface Management0/0^
    ip address 10.197.104.233 255.255.255.224]
</code>```

Is it possible to obtain the same set of values using input function ??

I am not able to obtain the interface and the ip address within the input function as below.

How to obtain multiple values within the input function:

```<code>    switch=[]
    i=0
    while 1:
     item=input(('interface %s ip address %s'))
     if item=='':
         break
    switch.append(item)
    print(switch)

    Expected from the interpreter:
    interface <value from the user>,ip address <value from the user>
    interface <value from the user>,ip address <value from the user>
    interface <value from the user>,ip address <value from the user>
</code>```

...
...
until the user inputs nothing.

答:
It sounds like you need to calls to input in your loop:

```<code>interfaces=[]
addresses=[]
i=0
while 1:
    interface=input('Interface: ')
    if interface=='':
        break
    interfaces.append(f'interface {interface}')
    address=input('Address: ')
    addresses.append(f'ip address {address}')
print([item[0] + ', ' + item[1] for item in zip(interfaces, addresses)])
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python - input from a user

Body:
I am planning to configure a switch using python script and the sample code is below.
Values like interface name , ip address are to be obtained from the user and I want my output to be list as shown below:

    int_device_configs = ['interface GigabitEthernet0/0^
    ip address 192.168.1.2 255.255.255.0','interface GigabitEthernet0/1^
    ip address 192.168.9.10 255.255.255.0,'interface Management0/0^
    ip address 10.197.104.233 255.255.255.224]

Is it possible to obtain the same set of values using input function ??

I am not able to obtain the interface and the ip address within the input function as below.

How to obtain multiple values within the input function:

    switch=[]
    i=0
    while 1:
     item=input(('interface %s ip address %s'))
     if item=='':
         break
    switch.append(item)
    print(switch)

    Expected from the interpreter:
    interface <value from the user>,ip address <value from the user>
    interface <value from the user>,ip address <value from the user>
    interface <value from the user>,ip address <value from the user>

...
...
until the user inputs nothing.

Body:
It sounds like you need to calls to input in your loop:

interfaces=[]
addresses=[]
i=0
while 1:
    interface=input('Interface: ')
    if interface=='':
        break
    interfaces.append(f'interface {interface}')
    address=input('Address: ')
    addresses.append(f'ip address {address}')
print([item[0] + ', ' + item[1] for item in zip(interfaces, addresses)])


问:
What are Sockets afterall? Why can't we use sockets instead of HTTP?
Are sockets just a connection between 2 machines?

And if sockets can be established why do we even use HTTP connection?

答:
Read about the OSI model for network communcations: http://en.wikipedia.org/wiki/OSI_model
It should do a good job of explaining where each of those components fit. </p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
Cannot make new host in MAMP Pro 4 because Create button is always disabled
When I launch MAMP Pro and navigate to the Hosts tab, click on the "+" at the bottom of the list of hosts, the modal has the create button disabled and I cannot complete making a new host.

答:
I found out that the reason behind of all of this is because of this character "-" and this _.

Do not use this characters in your localhost name.


问:
How to connect a class list in another class to the DataGridView

Class Student

```<code>class StudentInfo
    {
        public int StudentId { get; set; }
        public String FullName { get; set; }
        public String LessonStudy { get; set; }
        public String GroupName { get; set; }
        public StatusStudentBell StatusStudentBell { get; set; }
    }
</code>```

class StatusStudentBell

```<code>class StatusStudentBell
    {
        public String Bell1 { get; set; }
        public String Bell2 { get; set; }
        public String Bell3 { get; set; }
        public String Bell4 { get; set; }
    }
</code>```

In Form

```<code>ConservatoryEntities ConservatoryEntities = new ConservatoryEntities();
        private void Form1_Load(object sender, EventArgs e)
        {
            var student = ConservatoryEntities.LocationTimeClasses.Where(l =>
                    l.Day.Name.Equals("Friday"));

            var dateNow = DateTime.Parse(DateTime.UtcNow.ToShortDateString());

            var studentInfo = new List<StudentInfo>();
            foreach (var item in student)
            {

                studentInfo.AddRange(item.LessonToFieldStudy.FieldOfStudy.Students.ToList().Select(s =>
                new StudentInfo()
                {
                    FullName = s.Name,
                    GroupName = s.Team.Name,
                    LessonStudy = s.FieldOfStudy.Name,
                    StatusStudentBell = new StatusStudentBell()
                    {
                        Bell1 = item.LessonToFieldStudy.RollCalls.FirstOrDefault(r => r.fk_bell_Id == 1 &&
                        r.Date == dateNow)?.Absent + "",
                        Bell2 = item.LessonToFieldStudy.RollCalls.FirstOrDefault(r => r.fk_bell_Id == 2 &&
                        r.Date == dateNow)?.Absent + "",
                    }
                }).ToList());

            }

        }
</code>```

I'm just using C # and I am a beginner.

In C #, I want to connect this list that I've created to a dataGridView.

How can I add the StudentInfo list in which the StatusStudentBell class can connect to a DataGridView?

Please Help me.

答:
Try following :</p>

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication7
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            DataTable dt = new DataTable();

            dt.Columns.Add("StudentId", typeof(string));
            dt.Columns.Add("FullName", typeof(string));
            dt.Columns.Add("LessonStudy", typeof(string));
            dt.Columns.Add("GroupName", typeof(string));
            dt.Columns.Add("Bell1", typeof(string));
            dt.Columns.Add("Bell2", typeof(string));
            dt.Columns.Add("Bell3", typeof(string));
            dt.Columns.Add("Bell4", typeof(string));

            List<StudentInfo> studentInfo = new List<StudentInfo>() {
               new StudentInfo() { FullName = "John", GroupName = "Apple", LessonStudy = "Math", StudentId = 123, StatusStudentBell = new StatusStudentBell() { Bell1 = "A", Bell2 = "B", Bell3 = "C", Bell4 = "D"}},
               new StudentInfo() { FullName = "Marry", GroupName = "Bannana", LessonStudy = "English", StudentId = 345, StatusStudentBell = new StatusStudentBell() { Bell1 = "E", Bell2 = "F", Bell3 = "G", Bell4 = "H"}},
               new StudentInfo() { FullName = "Harry", GroupName = "Grape", LessonStudy = "French", StudentId = 678, StatusStudentBell = new StatusStudentBell() { Bell1 = "I", Bell2 = "J", Bell3 = "K", Bell4 = "L"}},
               new StudentInfo() { FullName = "July", GroupName = "Pinapple", LessonStudy = "Gym", StudentId = 246, StatusStudentBell = new StatusStudentBell() { Bell1 = "M", Bell2 = "N", Bell3 = "O", Bell4 = "P"}}
            };

            foreach (StudentInfo info in studentInfo)
            {
                dt.Rows.Add(new object[] { info.FullName, info.GroupName, info.LessonStudy, info.StudentId, info.StatusStudentBell.Bell1, info.StatusStudentBell.Bell2, info.StatusStudentBell.Bell3, info.StatusStudentBell.Bell4 });
            }

            dataGridView1.DataSource = dt;
        }
        class StudentInfo
        {
            public int StudentId { get; set; }
            public String FullName { get; set; }
            public String LessonStudy { get; set; }
            public String GroupName { get; set; }
            public StatusStudentBell StatusStudentBell { get; set; }
        }
        class StatusStudentBell
        {
            public String Bell1 { get; set; }
            public String Bell2 { get; set; }
            public String Bell3 { get; set; }
            public String Bell4 { get; set; }
        }
    }
}
</code>```

Body:
Class Student

class StudentInfo
    {
        public int StudentId { get; set; }
        public String FullName { get; set; }
        public String LessonStudy { get; set; }
        public String GroupName { get; set; }
        public StatusStudentBell StatusStudentBell { get; set; }
    }

class StatusStudentBell

class StatusStudentBell
    {
        public String Bell1 { get; set; }
        public String Bell2 { get; set; }
        public String Bell3 { get; set; }
        public String Bell4 { get; set; }
    }

In Form

ConservatoryEntities ConservatoryEntities = new ConservatoryEntities();
        private void Form1_Load(object sender, EventArgs e)
        {
            var student = ConservatoryEntities.LocationTimeClasses.Where(l =>
                    l.Day.Name.Equals("Friday"));

            var dateNow = DateTime.Parse(DateTime.UtcNow.ToShortDateString());

            var studentInfo = new List<StudentInfo>();
            foreach (var item in student)
            {

                studentInfo.AddRange(item.LessonToFieldStudy.FieldOfStudy.Students.ToList().Select(s =>
                new StudentInfo()
                {
                    FullName = s.Name,
                    GroupName = s.Team.Name,
                    LessonStudy = s.FieldOfStudy.Name,
                    StatusStudentBell = new StatusStudentBell()
                    {
                        Bell1 = item.LessonToFieldStudy.RollCalls.FirstOrDefault(r => r.fk_bell_Id == 1 &&
                        r.Date == dateNow)?.Absent + "",
                        Bell2 = item.LessonToFieldStudy.RollCalls.FirstOrDefault(r => r.fk_bell_Id == 2 &&
                        r.Date == dateNow)?.Absent + "",
                    }
                }).ToList());

            }

        }

I'm just using C # and I am a beginner.

In C #, I want to connect this list that I've created to a dataGridView.

How can I add the StudentInfo list in which the StatusStudentBell class can connect to a DataGridView?

Please Help me.

Body:
Try following :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication7
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            DataTable dt = new DataTable();

            dt.Columns.Add("StudentId", typeof(string));
            dt.Columns.Add("FullName", typeof(string));
            dt.Columns.Add("LessonStudy", typeof(string));
            dt.Columns.Add("GroupName", typeof(string));
            dt.Columns.Add("Bell1", typeof(string));
            dt.Columns.Add("Bell2", typeof(string));
            dt.Columns.Add("Bell3", typeof(string));
            dt.Columns.Add("Bell4", typeof(string));

            List<StudentInfo> studentInfo = new List<StudentInfo>() {
               new StudentInfo() { FullName = "John", GroupName = "Apple", LessonStudy = "Math", StudentId = 123, StatusStudentBell = new StatusStudentBell() { Bell1 = "A", Bell2 = "B", Bell3 = "C", Bell4 = "D"}},
               new StudentInfo() { FullName = "Marry", GroupName = "Bannana", LessonStudy = "English", StudentId = 345, StatusStudentBell = new StatusStudentBell() { Bell1 = "E", Bell2 = "F", Bell3 = "G", Bell4 = "H"}},
               new StudentInfo() { FullName = "Harry", GroupName = "Grape", LessonStudy = "French", StudentId = 678, StatusStudentBell = new StatusStudentBell() { Bell1 = "I", Bell2 = "J", Bell3 = "K", Bell4 = "L"}},
               new StudentInfo() { FullName = "July", GroupName = "Pinapple", LessonStudy = "Gym", StudentId = 246, StatusStudentBell = new StatusStudentBell() { Bell1 = "M", Bell2 = "N", Bell3 = "O", Bell4 = "P"}}
            };

            foreach (StudentInfo info in studentInfo)
            {
                dt.Rows.Add(new object[] { info.FullName, info.GroupName, info.LessonStudy, info.StudentId, info.StatusStudentBell.Bell1, info.StatusStudentBell.Bell2, info.StatusStudentBell.Bell3, info.StatusStudentBell.Bell4 });
            }

            dataGridView1.DataSource = dt;
        }
        class StudentInfo
        {
            public int StudentId { get; set; }
            public String FullName { get; set; }
            public String LessonStudy { get; set; }
            public String GroupName { get; set; }
            public StatusStudentBell StatusStudentBell { get; set; }
        }
        class StatusStudentBell
        {
            public String Bell1 { get; set; }
            public String Bell2 { get; set; }
            public String Bell3 { get; set; }
            public String Bell4 { get; set; }
        }
    }
}


问:
firebase get key values from list

Doing a subscribe on /chat returns this:

```<code>[
  {
    "-L-bXjl628aN6MvCY7iA": {
      "content": "dsad",
      "img": "https://firebasestorage.googleapis.com/v0/b/neverl-fd59d.appspot.com/o/images%2F1512395563.jpg?alt=m...",
      "senderId": "TjRj5oSWrcdx8CiZyZhq625bJSx2",
      "senderName": "Khaled",
      "time": "December 5, 2017 6:38 PM"
    }
  }
]
</code>```

The objects are returning correctly however, I cannot get the value EwffbmmqgFc.... (Highlighted in yellow)

How should I amend the code to be able to retrieve the path by listing the array content...?

Code below:

```<code> send(senderId:string,chatObject:any){
   this.db.list(`users/${senderId}/chat/${this.authProvider.getUID()}`).push(chatObject);
 }
</code>```

答: In the realtime DB every object gets a unique ID. Your chat node is comprised of objects. Inside your chat object(highlighted in yellow) you then add other objects (likely messages)  My best guess here is that you neglected to set any values/keys for your chat object likely because your simply pushing messages into the reference before setting values to the chat object itself. You should first create a chat object with name and whatever other values you choose. Once that is created you can then add your object to that specific chat reference. Hard to be sure without any code. </p>

Title: firebase get key values from list

Body:
Doing a subscribe on /chat returns this:

[
  {
    "-L-bXjl628aN6MvCY7iA": {
      "content": "dsad",
      "img": "https://firebasestorage.googleapis.com/v0/b/neverl-fd59d.appspot.com/o/images%2F1512395563.jpg?alt=m...",
      "senderId": "TjRj5oSWrcdx8CiZyZhq625bJSx2",
      "senderName": "Khaled",
      "time": "December 5, 2017 6:38 PM"
    }
  }
]

The objects are returning correctly however, I cannot get the value EwffbmmqgFc.... (Highlighted in yellow)

How should I amend the code to be able to retrieve the path by listing the array content...?

Code below:

 send(senderId:string,chatObject:any){
   this.db.list(`users/${senderId}/chat/${this.authProvider.getUID()}`).push(chatObject);
 }


问:
Snakes and Ladders - Coding the Jump in the Snakes and Ladders
I want to make a simple 'Snakes and Ladders' game to go through the motions, so that if I land on a Ladder, which would be represented as an array
Ladder = [3 5 11 20];, then I'd want my Position to increase by LadderGain = [18 3 15 9]; and vise-versa for Snakes.

My thought was

```<code>if Position == Ladder
Position = Position + LadderGain;
end
</code>```

thinking that the index at which it landed would carry over to LadderGain. This didn't work. I'm wondering how I can make this operation work without excessive if-statements.

```<code>   if Ladder(Ladder == Position)
       Position = Position + LadderGain(find(Ladder == Position,1));
   end
</code>```

This is the solution I've come up with.

答:
I would approach it this way:

```<code>Ladder = [3 5 11 20];       % Ladder positions.
LadderGain = [18 3 15 9];   % Ladder gains.

while true % Loop.
    Position = input('Enter position: ');       % Request user input.

    if any(Position == Ladder)                  % Check if Position matches any of the Ladder positions.
        idx = find(Position == Ladder);         % Find the index of the matching case.
        Position = Position + LadderGain(idx);  % Add the corresponding gain to the position.
    end

    fprintf('Position: %d\n', Position);    % Display new position.
end
</code>```

Test case 1: Player doesn't land on a ladder.

```<code>Enter position: 0
Position: 0
</code>```

Test case 2: Player lands on a ladder.

```<code>Enter position: 3
Position: 21
</code>```

Body:
I want to make a simple 'Snakes and Ladders' game to go through the motions, so that if I land on a Ladder, which would be represented as an array
Ladder = [3 5 11 20];, then I'd want my Position to increase by LadderGain = [18 3 15 9]; and vise-versa for Snakes.

My thought was

if Position == Ladder
Position = Position + LadderGain;
end

thinking that the index at which it landed would carry over to LadderGain. This didn't work. I'm wondering how I can make this operation work without excessive if-statements.

   if Ladder(Ladder == Position)
       Position = Position + LadderGain(find(Ladder == Position,1));
   end

This is the solution I've come up with.

Body:
I would approach it this way:

Ladder = [3 5 11 20];       % Ladder positions.
LadderGain = [18 3 15 9];   % Ladder gains.

while true % Loop.
    Position = input('Enter position: ');       % Request user input.

    if any(Position == Ladder)                  % Check if Position matches any of the Ladder positions.
        idx = find(Position == Ladder);         % Find the index of the matching case.
        Position = Position + LadderGain(idx);  % Add the corresponding gain to the position.
    end

    fprintf('Position: %d\n', Position);    % Display new position.
end

Test case 1: Player doesn't land on a ladder.

Enter position: 0
Position: 0

Test case 2: Player lands on a ladder.

Enter position: 3
Position: 21


问:
How to extract day,month,year from a filled cell dynamically new cell we're added as row in Excel?
How to work following things in excel
I have
Column

```<code>A.            B.         C.       D
12/12/17.     12.       Dec.      17
13/12/17.     13.       Dec       17
</code>```

From column A how to extract date and month and year as shown in column B,C,D?

if any of them entering 3rd and 4 th row on their own, for row 3 and 4 column B,C,D needs to be updated automatically.

```<code>Row 3 column A is 14/12/17
Row 4 column A is 15/12/17
</code>```

Note : not to use fill option in column B,C,D

答:
Day

```<code>=Day(A1)
</code>```

Month

```<code>=TEXT(A1,"ddd")
</code>```

Year:

```<code>=--TEXT(A1,"yy")
</code>```

Body:
How to work following things in excel
I have
Column

A.            B.         C.       D
12/12/17.     12.       Dec.      17
13/12/17.     13.       Dec       17

From column A how to extract date and month and year as shown in column B,C,D?

if any of them entering 3rd and 4 th row on their own, for row 3 and 4 column B,C,D needs to be updated automatically.

Row 3 column A is 14/12/17
Row 4 column A is 15/12/17

Note : not to use fill option in column B,C,D

Body:
Day

=Day(A1)

Month

=TEXT(A1,"ddd")

Year:

=--TEXT(A1,"yy")


问:
How do I subset a matrix by rownames using a list of row headers
I have a list of names (mylist). This list of names coincide with some of the row names in a (much) bigger file, which also contain additional columns of data (bigfile). How can I extract the rows in 'bigfile' matching with the names in 'mylist'?</p>

答:
```<code># collect the names from the bigfile
BigFileNames <- colnames(bigfile)

# find the intersect between your list and the list of names from Bigfile
common <- intersect(BigFileNames, myListNames)

# extract info from dataframe
infoFromCommon <- bigfile[,match(common, myListNames)]
</code>```


问:
How do I delay page display until JS is done?
I've done the prerequisite searching of stackoverflow and looking on the internet. I suspect that the answer is ' This can't be done. ' but I'm hoping someone here might have a solution.

My page loads fine, but many of my YUI components don't fully load before being displayed. For example, my DataTable will resize itself when displaying or my buttons will appear in their native form and then get YUI-fied.

Is there a way to delay the displaying of the page until all the Javascript is finished (i.e. all my YUI components are finished rendering)? I don't know how this would happen, as a lot of the JS depends on the DOM being present to manipulate it.

答: Try putting your Javascript in the head section of the page, as if it's near the end of the page, it'll load later (making the first elements load faster).  OR, better yet, serve up your Javascript compressed and via a CDN, such as Amazon CloudFront so that it loads quickly.</p>


问:
How to add custom CSP Header in JBOSS using httpd.conf file
I am trying to add response header Content security policy in JBoss environment using httpd.conf file but, I am not able to found any changes in the application.  I tried to set header using following code:

```<code>Header set Content-Security-Policy "default-src 'self';"

add_header Content-Security-Policy "default-src 'self';";
</code>```

答:
Servlet

If you are processing requests from a servlet then add the header to the response object in the appropriate method (i.e. doGet, doPost ... ).

```<code>  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException
  {

    response.setHeader("Content-Security-Policy", "default-src 'self';");
    // ...
  }
</code>```

JSF

If you are using JSF then create a filter and configure it in your web.xml file

```<code>public class SecurityFilter implements javax.servlet.Filter
{

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
                throws IOException, ServletException
{
    HttpServletResponse httpRes = (HttpServletResponse) response;

    httpRes.setHeader("Content-Security-Policy", "default-src 'self';");

    // Continue the chain.
    chain.doFilter(request, response);
}

}
</code>```

Sample entries to add to web.xml

```<code><filter>
  <filter-name>SecurityFilter </filter-name>
  <filter-class>com.blah.blah.SecurityFilter</filter-class>
</filter>

<filter-mapping>
  <filter-name>SecurityFilter</filter-name>
  <servlet-name>FacesServlet</servlet-name>
</filter-mapping>
</code>```

Body:
I am trying to add response header Content security policy in JBoss environment using httpd.conf file but, I am not able to found any changes in the application.  I tried to set header using following code:

Header set Content-Security-Policy "default-src 'self';"

add_header Content-Security-Policy "default-src 'self';";

Body:
Servlet

If you are processing requests from a servlet then add the header to the response object in the appropriate method (i.e. doGet, doPost ... ).

  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException
  {

    response.setHeader("Content-Security-Policy", "default-src 'self';");
    // ...
  }

JSF

If you are using JSF then create a filter and configure it in your web.xml file

public class SecurityFilter implements javax.servlet.Filter
{

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
                throws IOException, ServletException
{
    HttpServletResponse httpRes = (HttpServletResponse) response;

    httpRes.setHeader("Content-Security-Policy", "default-src 'self';");

    // Continue the chain.
    chain.doFilter(request, response);
}

}

Sample entries to add to web.xml

<filter>
  <filter-name>SecurityFilter </filter-name>
  <filter-class>com.blah.blah.SecurityFilter</filter-class>
</filter>

<filter-mapping>
  <filter-name>SecurityFilter</filter-name>
  <servlet-name>FacesServlet</servlet-name>
</filter-mapping>


问:
Trying to read and write parquet files from s3 with local spark
I'm trying to read and write parquet files from my local machine to S3 using spark. But I can't seem to configure my spark session properly to do so.  Obviously there are configurations to be made, but I could not find a clear reference on how to do it.

Currently my spark session reads local parquet mocks and is defined as such:

```<code>val sparkSession = SparkSession.builder.master("local").appName("spark session example").getOrCreate()
</code>```

答:
To read and write parquet files from S3 with local Spark, you need to add following 2 dependencies in your sbt project-

```<code>"com.amazonaws" % "aws-java-sdk" % "1.7.4"
"org.apache.hadoop" % "hadoop-aws" % "2.7.3"
</code>```

I am assuming its an sbt project. If its mvn then add following dependencies-

```<code><dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk</artifactId>
    <version>1.7.4</version>
</dependency>

<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-aws</artifactId>
    <version>2.7.3</version>
</dependency>
</code>```

Then you need to set S3 credentials in sparkSession, like this-

```<code>val sparkSession = SparkSession.builder.master("local").appName("spark session example").getOrCreate()
sparkSession.sparkContext.hadoopConfiguration.set("fs.s3n.impl", "org.apache.hadoop.fs.s3native.NativeS3FileSystem")
sparkSession.sparkContext.hadoopConfiguration.set("fs.s3n.awsAccessKeyId", "s3AccessKey")
sparkSession.sparkContext.hadoopConfiguration.set("fs.s3n.awsSecretAccessKey", "s3SecretKey")
</code>```

And its done. Now, you can Read/Write a Parquet file to S3. For example:

```<code>sparkSession.read.parquet("s3n://bucket/abc.parquet")    //Read
df.write.parquet("s3n://bucket/xyz.parquet")    //Write
</code>```

I hope it helps!

Body:
I'm trying to read and write parquet files from my local machine to S3 using spark. But I can't seem to configure my spark session properly to do so.  Obviously there are configurations to be made, but I could not find a clear reference on how to do it.

Currently my spark session reads local parquet mocks and is defined as such:

val sparkSession = SparkSession.builder.master("local").appName("spark session example").getOrCreate()

Body:
To read and write parquet files from S3 with local Spark, you need to add following 2 dependencies in your sbt project-

"com.amazonaws" % "aws-java-sdk" % "1.7.4"
"org.apache.hadoop" % "hadoop-aws" % "2.7.3"

I am assuming its an sbt project. If its mvn then add following dependencies-

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk</artifactId>
    <version>1.7.4</version>
</dependency>

<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-aws</artifactId>
    <version>2.7.3</version>
</dependency>

Then you need to set S3 credentials in sparkSession, like this-

val sparkSession = SparkSession.builder.master("local").appName("spark session example").getOrCreate()
sparkSession.sparkContext.hadoopConfiguration.set("fs.s3n.impl", "org.apache.hadoop.fs.s3native.NativeS3FileSystem")
sparkSession.sparkContext.hadoopConfiguration.set("fs.s3n.awsAccessKeyId", "s3AccessKey")
sparkSession.sparkContext.hadoopConfiguration.set("fs.s3n.awsSecretAccessKey", "s3SecretKey")

And its done. Now, you can Read/Write a Parquet file to S3. For example:

sparkSession.read.parquet("s3n://bucket/abc.parquet")    //Read
df.write.parquet("s3n://bucket/xyz.parquet")    //Write

I hope it helps!


问:
Spring CXF Soap Web Service Under Tomcat: No Services Found
I'm trying to set-up a simple CXF Web Service running on Tomcat with CXF and Spring:

I have a Web Application initializer to bootstrap the CXF servlet:

```<code>public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
  @Override
  protected void registerContextLoaderListener(ServletContext servletContext)
  {
    CXFServlet cxfServlet = new CXFServlet();
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("cxf", cxfServlet);
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/services/*");
  }

  .....
}
</code>```

I have a Spring configuration class:

```<code>@Configuration
public class WebServiceConfiguration
{
  @Bean
  public Endpoint endPoint()
  {
    EndpointImpl endpoint = new EndpointImpl(cxf(), eorthoWebService());
    endpoint.getHandlers().add(inboundRequestHandler());
    endpoint.getHandlers().add(outboundRequestHandler());
    //the below works and uses cxf's embedded Jetty server
    //endpoint.publish("http://localhost:9090/services/EorthoWebService");
    //this doesn't work
    endpoint.publish("/EorthoWebService");

    return endpoint;
  }

  @Bean
  public SpringBus cxf()
  {
    return new SpringBus();
  }

  @Bean
  public EorthoWebService eorthoWebService()
  {
    return new EorthoWebServiceImpl();
  }
}
</code>```

I have a Web Service implementation:

```<code>@WebService(endpointInterface = "com.aoa.eortho.ws.service.EorthoWebService")
@SchemaValidation(type = SchemaValidationType.IN)
public class EorthoWebServiceImpl implements EorthoWebService {

    @WebMethod
    public RulesEngineOrthodonticSubmissionResponseEnv processRequest(RulesEngineOrthodonticSubmissionRequestEnv requestEnvelope) {
        ...
    }
}
</code>```

When I hit /services I get the output:

No services have been found.

The only way I can it to work is by publishing as below which seems to publish it to an embedded Jetty server rather than the Tomcat instance it is deployed to:

```<code>endpoint.publish("http://localhost:9090/services/EorthoWebService");
</code>```

What am I missing to get it working on Tomcat using:

```<code>endpoint.publish("/EorthoWebService");
</code>```

答:
The part you're missing is the spring contextscanning.

From Baeldung -- A Guide to Apache CXF with Spring

First, a Spring application context is created and configured to register a class containing configuration metadata:

```<code>AnnotationConfigWebApplicationContext context
    = new AnnotationConfigWebApplicationContext();
context.register(ServiceConfiguration.class);
</code>```

The ServiceConfiguration class is annotated with the @Configuration annotation to provide bean definitions. This class is discussed in the next subsection.
    The following snippet shows how the Spring application context is added to the servlet context:

```<code>container.addListener(new ContextLoaderListener(context));
</code>```

So, the complete class is:

```<code>public class AppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext container) {

        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(ServiceConfiguration.class);

        container.addListener(new ContextLoaderListener(context));

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new CXFServlet());
        dispatcher.setLoadOnStartup(1);

        dispatcher.addMapping("/services/*");
    }
}
</code>```

Which is different from your AbstractAnnotationConfigDispatcherServletInitializer extended class but when i override onStartup instead of registerContextLoaderListener it seems to work just as well. Hopefully this is enough to get you sorted out.

Also, my Configuration class:

```<code>@Configuration
public class ServiceConfiguration {

    @Bean
    public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(cxf(), new HelloWorldImpl());
        endpoint.publish("/HelloWorld");
        return endpoint;
    }

    @Bean
    public SpringBus cxf() {
        return new SpringBus();
    }

}
</code>```

Body:
I'm trying to set-up a simple CXF Web Service running on Tomcat with CXF and Spring:

I have a Web Application initializer to bootstrap the CXF servlet:

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
  @Override
  protected void registerContextLoaderListener(ServletContext servletContext)
  {
    CXFServlet cxfServlet = new CXFServlet();
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("cxf", cxfServlet);
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/services/*");
  }

  .....
}

I have a Spring configuration class:

@Configuration
public class WebServiceConfiguration
{
  @Bean
  public Endpoint endPoint()
  {
    EndpointImpl endpoint = new EndpointImpl(cxf(), eorthoWebService());
    endpoint.getHandlers().add(inboundRequestHandler());
    endpoint.getHandlers().add(outboundRequestHandler());
    //the below works and uses cxf's embedded Jetty server
    //endpoint.publish("http://localhost:9090/services/EorthoWebService");
    //this doesn't work
    endpoint.publish("/EorthoWebService");

    return endpoint;
  }

  @Bean
  public SpringBus cxf()
  {
    return new SpringBus();
  }

  @Bean
  public EorthoWebService eorthoWebService()
  {
    return new EorthoWebServiceImpl();
  }
}

I have a Web Service implementation:

@WebService(endpointInterface = "com.aoa.eortho.ws.service.EorthoWebService")
@SchemaValidation(type = SchemaValidationType.IN)
public class EorthoWebServiceImpl implements EorthoWebService {

    @WebMethod
    public RulesEngineOrthodonticSubmissionResponseEnv processRequest(RulesEngineOrthodonticSubmissionRequestEnv requestEnvelope) {
        ...
    }
}

When I hit /services I get the output:

No services have been found.

The only way I can it to work is by publishing as below which seems to publish it to an embedded Jetty server rather than the Tomcat instance it is deployed to:

endpoint.publish("http://localhost:9090/services/EorthoWebService");

What am I missing to get it working on Tomcat using:

endpoint.publish("/EorthoWebService");

Body:
The part you're missing is the spring contextscanning.

From Baeldung -- A Guide to Apache CXF with Spring

First, a Spring application context is created and configured to register a class containing configuration metadata:

AnnotationConfigWebApplicationContext context
    = new AnnotationConfigWebApplicationContext();
context.register(ServiceConfiguration.class);

The ServiceConfiguration class is annotated with the @Configuration annotation to provide bean definitions. This class is discussed in the next subsection.
    The following snippet shows how the Spring application context is added to the servlet context:

container.addListener(new ContextLoaderListener(context));

So, the complete class is:

public class AppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext container) {

        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(ServiceConfiguration.class);

        container.addListener(new ContextLoaderListener(context));

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new CXFServlet());
        dispatcher.setLoadOnStartup(1);

        dispatcher.addMapping("/services/*");
    }
}

Which is different from your AbstractAnnotationConfigDispatcherServletInitializer extended class but when i override onStartup instead of registerContextLoaderListener it seems to work just as well. Hopefully this is enough to get you sorted out.

Also, my Configuration class:

@Configuration
public class ServiceConfiguration {

    @Bean
    public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(cxf(), new HelloWorldImpl());
        endpoint.publish("/HelloWorld");
        return endpoint;
    }

    @Bean
    public SpringBus cxf() {
        return new SpringBus();
    }

}


问:
Braintree Payments requestPaymentMethod hangs
I am trying to get the javascript V3 version of Braintree Payments running against sandbox, and am having a problem with the requestPaymentMethod hanging when I provide a valid sandbox cc.

The following displays the page and successfully displays the "RequestPaymentMethod Error" alert when I do not provide a cc, but hangs (with fast a green progress "stripe" scrolling across the screen under the Pay with Card header) when the valid 4111-1111-1111-1111 cc is entered.

Note - I am trying to do this by dropping a file into the browser (ie. file://...) instead of http or https - that worked with the script tag dropin.

```<code><head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <title>Braintree Payments Test - JS3</title>

        <link rel="stylesheet" type="text/css" href="https://assets.braintreegateway.com/web/dropin/1.9.2/css/dropin.min.css" id="braintree-dropin-stylesheet">
    </head>

    <body>
        <div align="center"> <h1>Braintree Payments Test - JS3</h1></div>

            <div id="dropin-container"></div>
            <button id="submit-button">Purchase</button>

            <script src="https://js.braintreegateway.com/web/dropin/1.9.2/js/dropin.min.js"></script>
            <script>
                var button = document.querySelector('#submit-button');
                braintree.dropin.create({
                    authorization: <sandbox tokenizationKey>,
                    container: '#dropin-container'
                }).then(function(dropinInstance) {
                    button.addEventListener('click', function() {
                        alert("requesting payment method");
                        dropinInstance.requestPaymentMethod().then(function(payload) {
                            alert("Recvd nonce: " + payload.nonce);
                        }).catch(function(requestPaymentMethodError) {
                            alert("RequestPaymentMethod Error: " + requestPaymentMethodError);
                        });
                    });
                }).catch(function(createErr) {
                    alert("Create Error: " + createErr);
                });

            </script>
    </body>
</code>```

答:
Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.

Due to how Braintree's JavaScript SDK relies on postMessage(), you will need to run your application via HTTP or HTTPS in order to avoid the issue you're experiencing. This is because with postMessage() file:// cannot be used as a security restriction;

Body:
I am trying to get the javascript V3 version of Braintree Payments running against sandbox, and am having a problem with the requestPaymentMethod hanging when I provide a valid sandbox cc.

The following displays the page and successfully displays the "RequestPaymentMethod Error" alert when I do not provide a cc, but hangs (with fast a green progress "stripe" scrolling across the screen under the Pay with Card header) when the valid 4111-1111-1111-1111 cc is entered.

Note - I am trying to do this by dropping a file into the browser (ie. file://...) instead of http or https - that worked with the script tag dropin.

        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <title>Braintree Payments Test - JS3</title>

        <link rel="stylesheet" type="text/css" href="https://assets.braintreegateway.com/web/dropin/1.9.2/css/dropin.min.css" id="braintree-dropin-stylesheet">

Braintree Payments Test - JS3

            <button id="submit-button">Purchase</button>


问:
How can I update the parent's state in React?
My structure looks as follows:

```<code>Component 1

 - |- Component 2

 - - |- Component 4

 - - -  |- Component 5

Component 3
</code>```

Component 3 should display some data depending on state of Component 5.

Since props are immutable, I can't simply save its state in Component 1 and forward it, right? And yes, I've read about Redux, but I don't want to use it. I hope that it's possible to solve it just with react. Am I wrong?

答:
```<code><Footer
  action={()=>this.setState({showChart: true})}
/>

<footer className="row">
    <button type="button" onClick={this.props.action}>Edit</button>
  {console.log(this.props)}
</footer>

Try this example to write inline setState, it avoids creating another function.
</code>```

Body:
My structure looks as follows:

Component 1

 - |- Component 2

 - - |- Component 4

 - - -  |- Component 5

Component 3

Component 3 should display some data depending on state of Component 5.

Since props are immutable, I can't simply save its state in Component 1 and forward it, right? And yes, I've read about Redux, but I don't want to use it. I hope that it's possible to solve it just with react. Am I wrong?


问:
EDMX: edmx is not updated in the server
today as a litle task i needed add a new column to my datamodel (edmx file) and it works ok in my development machine. but I tried put my changes to the server the web.page didn't work :(
 I suppose  is because the datamodel is not sync with the database ( in the server the db is already updated ), but i don't know how to check or how to make sure if i have the last version of my changes related with the datamodel :(.
Any suggestion?
Thank you!</p>

答:
Have you double-clicked on your EDMX file and opened up the 'work area' (you know where it shows your entities, like this

Then right click and select Update Model from database and this will cause your EDMX to update to reflect the db model. Hope that helps

Title: EDMX: edmx is not updated in the server


问:
How does SQL query parameterisation work?
I feel a little silly for asking this since I seem to be the only person in the world who doesn't get it, but here goes anyway.  I'm going to use Python as an example.  When I use raw SQL queries (I usually use ORMs) I use parameterisation, like this example using SQLite:

Method A:

```<code>username = "wayne"
query_params = (username)
cursor.execute("SELECT * FROM mytable WHERE user=?", query_params)
</code>```

I know this works and I know this is the generally recommended way to do it.  A SQL injection-vulnerable way to do the same thing would be something like this:

Method B:

```<code>username = "wayne"
cursor.execute("SELECT * FROM mytable WHERE user='%s'" % username)
</code>```

As far I can tell I understand SQL injection, as explained in this Wikipedia article.  My question is simply: How is method A really different to method B?  Why is the end result of method A not the same as method B?  I assume that the cursor.execute() method (part of Python's DB-API specification) takes care of correctly escaping and type-checking the input, but this is never explicitly stated anywhere.  Is that all that parameterisation in this context is?  To me, when we say "parameterisation", all that means is "string substitution", like %-formatting.  Is that incorrect?

答:
Just a caveat here.
This ? syntax will work just fine and escapes embedded single or double quotes in strings correctly.

However I found one case where it does not work. I have a column that tracks a version string of the form "n.n.n" e.g. "1.2.3" It seems that format causes an error because it looks like a Real number up until the second ".". For example:

```<code>   rec = (some_value, '1.2.3')
   sql = ''' UPDATE some_table
              SET some_column=?
              WHERE version=? '''
    cur = self.conn.cursor()
    cur.execute(sql, rec)
</code>```

Failed with an error "Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied."

This works ok:

```<code>   vers = '1.2.3'
   rec = (some_value)
   sql = ''' UPDATE some_table
              SET some_column=?
              WHERE version='%s' ''' % (vers)
    cur = self.conn.cursor()
    cur.execute(sql, rec)
</code>```

Body:
I feel a little silly for asking this since I seem to be the only person in the world who doesn't get it, but here goes anyway.  I'm going to use Python as an example.  When I use raw SQL queries (I usually use ORMs) I use parameterisation, like this example using SQLite:

Method A:

username = "wayne"
query_params = (username)
cursor.execute("SELECT * FROM mytable WHERE user=?", query_params)

I know this works and I know this is the generally recommended way to do it.  A SQL injection-vulnerable way to do the same thing would be something like this:

Method B:

username = "wayne"
cursor.execute("SELECT * FROM mytable WHERE user='%s'" % username)

As far I can tell I understand SQL injection, as explained in this Wikipedia article.  My question is simply: How is method A really different to method B?  Why is the end result of method A not the same as method B?  I assume that the cursor.execute() method (part of Python's DB-API specification) takes care of correctly escaping and type-checking the input, but this is never explicitly stated anywhere.  Is that all that parameterisation in this context is?  To me, when we say "parameterisation", all that means is "string substitution", like %-formatting.  Is that incorrect?

Body:
Just a caveat here.
This ? syntax will work just fine and escapes embedded single or double quotes in strings correctly.

However I found one case where it does not work. I have a column that tracks a version string of the form "n.n.n" e.g. "1.2.3" It seems that format causes an error because it looks like a Real number up until the second ".". For example:

   rec = (some_value, '1.2.3')
   sql = ''' UPDATE some_table
              SET some_column=?
              WHERE version=? '''
    cur = self.conn.cursor()
    cur.execute(sql, rec)

Failed with an error "Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied."

This works ok:

   vers = '1.2.3'
   rec = (some_value)
   sql = ''' UPDATE some_table
              SET some_column=?
              WHERE version='%s' ''' % (vers)
    cur = self.conn.cursor()
    cur.execute(sql, rec)


问:
How to refactor and reduce complexity
I have the following code:

```<code>@model = "ford"
@attribute = "name"

def grouped
   grouped = {}

   @array.each do |r|
     field = r.car.send(@model)

     if field.is_a? ActiveRecord::Associations::CollectionProxy
        field.each do |obj|
           key = obj.send(@attribute)
           grouped[key] = [] unless grouped.has_key?(key)
           grouped[key].push(r)
       end
     else
       key = field.send(@attribute)
       grouped[key] = [] unless grouped.has_key?(key)
       grouped[key].push(r)
     end
   end

  grouped
end
</code>```

The result is:

```<code>{ford: [a, b, c]}
</code>```

The codeclimate says that it has cognitive complexity.

How can I refactor this method to something cleaner?

答:
```<code>def grouped
   @array.each_with_object(Hash.new { |h, k| h[k] = [] }) do |r, grouped|
     case field = r.car.send(@model)
     when ActiveRecord::Associations::CollectionProxy
        field.each do |obj|
          grouped[obj.send(@attribute)] << r
        end
     else
       grouped[field.send(@attribute)] << r
     end
   end
end
</code>```

Title: How to refactor and reduce complexity

Body:
I have the following code:

@model = "ford"
@attribute = "name"

def grouped
   grouped = {}

   @array.each do |r|
     field = r.car.send(@model)

     if field.is_a? ActiveRecord::Associations::CollectionProxy
        field.each do |obj|
           key = obj.send(@attribute)
           grouped[key] = [] unless grouped.has_key?(key)
           grouped[key].push(r)
       end
     else
       key = field.send(@attribute)
       grouped[key] = [] unless grouped.has_key?(key)
       grouped[key].push(r)
     end
   end

  grouped
end

The result is:

{ford: [a, b, c]}

The codeclimate says that it has cognitive complexity.

How can I refactor this method to something cleaner?


问:
Does JavaScript interpreter produce value from anything it reads?
From JavaScript eloquent book:

Many operations in the language that don’t produce a meaningful value
  yield undefined simply because they have to
  yield some value.

Does the interpreter has to produce a value from anything it reads?

And what are examples of these operations that do not produce a meaningful value?

答:
Both statements and expressions have values, but the values of non-expression statements* are not accessible in code. This is meaningful at a specification level, and you can see it in your browser's console, but it doesn't really have any day-to-day utility. Declarations, being outside the step-by-step execution of the code, don't have result values at the specification level (consoles show undefined as their result, though).

To see it in action, open your browser console, type this:

```<code>if (true) "foo"
</code>```

...and press Enter. You'll see "foo". Now try:

```<code>if (false) "foo"
</code>```

...and press Enter. You'll see undefined.

Why? Because the result of an if statement is the result of its body (if the condition is true) or undefined (if the condition is false).

Here's what the spec link above says about if (condition) statement:

Runtime Semantics: Evaluation

IfStatement: if (Expression) Statement

Let exprRef be the result of evaluating Expression.

Let exprValue be ToBoolean(? GetValue(exprRef)).

If exprValue is false, then

Return NormalCompletion(undefined).

  Else

Let stmtCompletion be the result of evaluating Statement.

Return Completion(UpdateEmpty(stmtCompletion, undefined)).

...where Completion(...) creates a completion record; the first argument is the value of the completion.

Here's another one to try in your console:

```<code>var n = 4; while (n--) { "body " + n; }
</code>```

The result is "body 0" because the value of a while statement is the value of the last execution of its body (or undefined if it never executed the body).

* "non-expression statements" - JavaScript allows any expression to be a statement if it appears where a statement is expected (this is how function calls work as statements, for instance). Which is why my "foo" in if (true) "foo" works; it's an expression statement where the expression is a string literal.

Body:
Both statements and expressions have values, but the values of non-expression statements* are not accessible in code. This is meaningful at a specification level, and you can see it in your browser's console, but it doesn't really have any day-to-day utility. Declarations, being outside the step-by-step execution of the code, don't have result values at the specification level (consoles show undefined as their result, though).

To see it in action, open your browser console, type this:

if (true) "foo"

...and press Enter. You'll see "foo". Now try:

if (false) "foo"

...and press Enter. You'll see undefined.

Why? Because the result of an if statement is the result of its body (if the condition is true) or undefined (if the condition is false).

Here's what the spec link above says about if (condition) statement:

Runtime Semantics: Evaluation

IfStatement: if (Expression) Statement

Let exprRef be the result of evaluating Expression.

Let exprValue be ToBoolean(? GetValue(exprRef)).

If exprValue is false, then

Return NormalCompletion(undefined).

  Else

Let stmtCompletion be the result of evaluating Statement.

Return Completion(UpdateEmpty(stmtCompletion, undefined)).

...where Completion(...) creates a completion record; the first argument is the value of the completion.

Here's another one to try in your console:

var n = 4; while (n--) { "body " + n; }

The result is "body 0" because the value of a while statement is the value of the last execution of its body (or undefined if it never executed the body).

* "non-expression statements" - JavaScript allows any expression to be a statement if it appears where a statement is expected (this is how function calls work as statements, for instance). Which is why my "foo" in if (true) "foo" works; it's an expression statement where the expression is a string literal.


问:
the server responded with a status of 404 (Not Found) Failed to load resource
I am facing issue in accessing public folder of laravel.

I am on ubuntu 17.10.

I am trying to run the app on localhost.

I am accessing like this:

```<code><img src="{{URL::asset('public/assets/img/person.jpg')}}"/>
</code>```

Also when checking the its source , its path is shown correct :

It may seem duplicate but I've tried most of the solutions present on net.

答:
You are calling the wrong directory
 Instead of

```<code><img src="{{URL::asset('public/assets/img/person.jpg')}}"/>
</code>```

Use this instead

```<code>   <img src="{{asset('assets/img/person.jpg')}}"/>
</code>```

Considering the assets folder is existing in public folder.

I hope this will solve you :)

Just in case file had cached on your browser try to add query string on your file by doing this so browser will treat it as a new file

Body:
I am facing issue in accessing public folder of laravel.

I am on ubuntu 17.10.

I am trying to run the app on localhost.

I am accessing like this:

Also when checking the its source , its path is shown correct :

It may seem duplicate but I've tried most of the solutions present on net.

Body:
You are calling the wrong directory
 Instead of

<img src="{{URL::asset('public/assets/img/person.jpg')}}"/>

Use this instead

   <img src="{{asset('assets/img/person.jpg')}}"/>

Considering the assets folder is existing in public folder.

I hope this will solve you :)

Just in case file had cached on your browser try to add query string on your file by doing this so browser will treat it as a new file


问:
Symfony doesnt auto increment id
I have a database called cardb which is populated by a SQL file which made some cars. They have ID's starting from 1 up to 30. When I try to create new Car it works the first time and creates a car with id 0 then when it tries to do it again it again tries to make an entry with 0.

Here is the error

An exception occurred while executing 'INSERT INTO cars (Make, Model, TravelledDistance) VALUES (?, ?, ?)' with params ["fock", "fock", 320]:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY'

Here is my entity

```<code>    /**
 * Cars
 *
 * @ORM\Table(name="cars")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CarsRepository")
 */
class Cars
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="Make", type="string", length=255)
     */
    private $make;

    /**
     * @var string
     *
     * @ORM\Column(name="Model", type="string", length=255)
     */
    private $model;

    /**
     * @var int
     *
     * @ORM\Column(name="TravelledDistance", type="bigint")
     */
    private $travelledDistance;

    /**
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Parts", inversedBy="cars")
     * @ORM\JoinTable(
     *  name="PartCars",
     *  joinColumns={
     *      @ORM\JoinColumn(name="Part_Id", referencedColumnName="id")
     *  },
     *  inverseJoinColumns={
     *      @ORM\JoinColumn(name="Car_Id", referencedColumnName="id")
     *  })
     */
    private $parts;
    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set make
     *
     * @param string $make
     *
     * @return Cars
     */
    public function setMake($make)
    {
        $this->make = $make;

        return $this;
    }

    /**
     * Get make
     *
     * @return string
     */
    public function getMake()
    {
        return $this->make;
    }

    /**
     * Set model
     *
     * @param string $model
     *
     * @return Cars
     */
    public function setModel($model)
    {
        $this->model = $model;

        return $this;
    }

    /**
     * Get model
     *
     * @return string
     */
    public function getModel()
    {
        return $this->model;
    }

    /**
     * Set travelledDistance
     *
     * @param integer $travelledDistance
     *
     * @return Cars
     */
    public function setTravelledDistance($travelledDistance)
    {
        $this->travelledDistance = $travelledDistance;

        return $this;
    }

    /**
     * Get travelledDistance
     *
     * @return int
     */
    public function getTravelledDistance()
    {
        return $this->travelledDistance;
    }

    /**
     * @return mixed
     */
    public function getParts()
    {
        return $this->parts;
    }

}
</code>```

It is auto generated Entity which has auto increment annotation.

What could be the problem?

答:
The annotation

```<code> * @ORM\GeneratedValue(strategy="AUTO")
</code>```

won't make PHP create a unique ID. You can see from the insert statement that PHP doesn't provide an ID value at all.

That annotation tells the ORM what kind of column it is, but it depends on the database to generate the value. You can check the documentation for more details.

Based on the way your code looks, it appears you used the console to generate the entity, but I assume the fact that the database isn't doing the id properly means that you created the cars table by hand rather than using doctrine:schema:update, which is fine if that's the way you need/want to do it, but you'll have to alter your table to make the id column an autoincrement.

Title: Symfony doesnt auto increment id

Body:
I have a database called cardb which is populated by a SQL file which made some cars. They have ID's starting from 1 up to 30. When I try to create new Car it works the first time and creates a car with id 0 then when it tries to do it again it again tries to make an entry with 0.

Here is the error

An exception occurred while executing 'INSERT INTO cars (Make, Model, TravelledDistance) VALUES (?, ?, ?)' with params ["fock", "fock", 320]:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY'

Here is my entity

    /**
 * Cars
 *
 * @ORM\Table(name="cars")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CarsRepository")
 */
class Cars
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="Make", type="string", length=255)
     */
    private $make;

    /**
     * @var string
     *
     * @ORM\Column(name="Model", type="string", length=255)
     */
    private $model;

    /**
     * @var int
     *
     * @ORM\Column(name="TravelledDistance", type="bigint")
     */
    private $travelledDistance;

    /**
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Parts", inversedBy="cars")
     * @ORM\JoinTable(
     *  name="PartCars",
     *  joinColumns={
     *      @ORM\JoinColumn(name="Part_Id", referencedColumnName="id")
     *  },
     *  inverseJoinColumns={
     *      @ORM\JoinColumn(name="Car_Id", referencedColumnName="id")
     *  })
     */
    private $parts;
    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set make
     *
     * @param string $make
     *
     * @return Cars
     */
    public function setMake($make)
    {
        $this->make = $make;

        return $this;
    }

    /**
     * Get make
     *
     * @return string
     */
    public function getMake()
    {
        return $this->make;
    }

    /**
     * Set model
     *
     * @param string $model
     *
     * @return Cars
     */
    public function setModel($model)
    {
        $this->model = $model;

        return $this;
    }

    /**
     * Get model
     *
     * @return string
     */
    public function getModel()
    {
        return $this->model;
    }

    /**
     * Set travelledDistance
     *
     * @param integer $travelledDistance
     *
     * @return Cars
     */
    public function setTravelledDistance($travelledDistance)
    {
        $this->travelledDistance = $travelledDistance;

        return $this;
    }

    /**
     * Get travelledDistance
     *
     * @return int
     */
    public function getTravelledDistance()
    {
        return $this->travelledDistance;
    }

    /**
     * @return mixed
     */
    public function getParts()
    {
        return $this->parts;
    }

}

It is auto generated Entity which has auto increment annotation.

What could be the problem?

Body:
The annotation

 * @ORM\GeneratedValue(strategy="AUTO")

won't make PHP create a unique ID. You can see from the insert statement that PHP doesn't provide an ID value at all.

That annotation tells the ORM what kind of column it is, but it depends on the database to generate the value. You can check the documentation for more details.

Based on the way your code looks, it appears you used the console to generate the entity, but I assume the fact that the database isn't doing the id properly means that you created the cars table by hand rather than using doctrine:schema:update, which is fine if that's the way you need/want to do it, but you'll have to alter your table to make the id column an autoincrement.


问:
Unexpected directive 'MatSpinner' imported by the module 'AppModule'. Please add a @NgModule annotation
Angular 5 -

here are the npm modules (package.json)-

```<code>   "@angular/animations": "^5.0.0",
    "@angular/cdk": "^5.0.0-rc.2",
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/material": "^5.0.0-rc.2",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/router": "^5.0.0",
    "core-js": "^2.4.1",
    "hammerjs": "^2.0.8",
    "rxjs": "^5.5.2",
    "zone.js": "^0.8.14"
</code>```

I am using Angular material Spinner as MatSpinner Directive from Material module

```<code>import { MatSpinner } from "@angular/material";
@NgModule({
imports: [

MatSpinner
],
declarations: [],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Here is the HTML:

```<code><mat-spinner></mat-spinner>
</code>```

I am Getting an ERROR-

Unexpected directive 'MatSpinner' imported by the module 'AppModule'. Please add a @NgModule annotation.

答: In your app-module, you would generally import MatProgressSpinnerModule, not MatSpinner.  MatSpinner would be imported in your component.</p>

Body:
Angular 5 -

here are the npm modules (package.json)-

   "@angular/animations": "^5.0.0",
    "@angular/cdk": "^5.0.0-rc.2",
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/material": "^5.0.0-rc.2",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/router": "^5.0.0",
    "core-js": "^2.4.1",
    "hammerjs": "^2.0.8",
    "rxjs": "^5.5.2",
    "zone.js": "^0.8.14"

I am using Angular material Spinner as MatSpinner Directive from Material module

import { MatSpinner } from "@angular/material";
@NgModule({
imports: [

MatSpinner
],
declarations: [],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Here is the HTML:

<mat-spinner></mat-spinner>

I am Getting an ERROR-

Unexpected directive 'MatSpinner' imported by the module 'AppModule'. Please add a @NgModule annotation.


问:
MySQL JOIN to return correct value from secondary table
I'm joining two tables together, a "Photos" table and "Locations" table. Each location may or may not have a default picture associated with it, and if it does I want to return that photo name. If it doesn't then return null. The default image for each location (if it exists) is always the image that has the "PictureSort" value of 1.

From my first SQL attempt below, if I use a WHERE statement, then I don't receive the null locations (where photos don't exist for that location).

```<code>SELECT a.LocationID, a.LocationName, b.PictureSort, b.PictureName
FROM Locations AS a
LEFT JOIN Photos AS b ON a.LocationID = b.LocationID
WHERE b.PictureSort = '1'
GROUP BY a.LocationID
</code>```

I also tried using the MIN() function in mySQL to say show me the lowest value in the PictureSort column, and while that works for that column, the column right next to it PictureName doesn't follow suit and return the associated value to the PictureSort column.

```<code>SELECT a.LocationID, a.LocationName, MIN(b.PictureSort) AS PictureSort, b.PictureName
FROM Locations AS a
LEFT JOIN Photos AS b ON a.LocationID = b.LocationID
GROUP BY a.LocationID
</code>```

Any help is greatly appreciated. I want this to work, but I'm also looking for the least expensive query possible to get this done.

Thanks!

答:
Conditions on the second table should be in the on clause for a left join.

Also, your table aliases should be related to the names of the table.  And the GROUP BY should not be needed.  So try this:

```<code>SELECT l.LocationID, l.LocationName, p.PictureSort, p.PictureName
FROM Locations l LEFT JOIN
     Photos p
     ON p.LocationID = l.LocationID AND b.PictureSort = '1';
</code>```

If PictureSort is stored as a number, then drop the single quotes.  Don't mix data types.

Body:
I'm joining two tables together, a "Photos" table and "Locations" table. Each location may or may not have a default picture associated with it, and if it does I want to return that photo name. If it doesn't then return null. The default image for each location (if it exists) is always the image that has the "PictureSort" value of 1.

From my first SQL attempt below, if I use a WHERE statement, then I don't receive the null locations (where photos don't exist for that location).

SELECT a.LocationID, a.LocationName, b.PictureSort, b.PictureName
FROM Locations AS a
LEFT JOIN Photos AS b ON a.LocationID = b.LocationID
WHERE b.PictureSort = '1'
GROUP BY a.LocationID

I also tried using the MIN() function in mySQL to say show me the lowest value in the PictureSort column, and while that works for that column, the column right next to it PictureName doesn't follow suit and return the associated value to the PictureSort column.

SELECT a.LocationID, a.LocationName, MIN(b.PictureSort) AS PictureSort, b.PictureName
FROM Locations AS a
LEFT JOIN Photos AS b ON a.LocationID = b.LocationID
GROUP BY a.LocationID

Any help is greatly appreciated. I want this to work, but I'm also looking for the least expensive query possible to get this done.

Thanks!

Body:
Conditions on the second table should be in the on clause for a left join.

Also, your table aliases should be related to the names of the table.  And the GROUP BY should not be needed.  So try this:

SELECT l.LocationID, l.LocationName, p.PictureSort, p.PictureName
FROM Locations l LEFT JOIN
     Photos p
     ON p.LocationID = l.LocationID AND b.PictureSort = '1';

If PictureSort is stored as a number, then drop the single quotes.  Don't mix data types.


问:
SASS Mixins to Animate Dropdown Opening
I have a series of Nav dropdowns.  When the user hovers over one of them, I want it to open using an animation.  So my HTML looks something like this:

```<code><div class="nav-dropdown-contents short-dropdown">
  <div>Item 1</div>
  <div>Item 2</div>
</div>

<div class="nav-dropdown-contents medium-dropdown">
  <div>Item A</div>
  <div>Item B</div>
  <div>Item C</div>
  <div>Item D</div>
</div>
</code>```

So short dropdown has 2 items, and medium dropdown has 4.

Here is my SCSS for the short dropdown:

```<code>.short-dropdown {
    &.open {
        animation-name: shortDropdownOpenAnimation;
        animation-duration: 400ms;
    }

    &.closed {
        animation-name: shortDropdownCloseAnimation;
        animation-duration: 400ms;
    }
}
</code>```

And I have the two animations defined thusly:

```<code>@keyframes shortDropdownOpenAnimation {
from {
    height: 0px;
}

to {
    height: 50px;
}
</code>```

}

```<code>@keyframes ShortDropdownCloseAnimation {
from {
    height: 50px;
}

to {
    height: 0px;
}
</code>```

}

So this works great, but now I also have to define keyframes for my medium dropdown.  And as I get more dropdowns with different numbers of items, it would be nice to be able to factor all of these mixins out into just one, that takes a height property that I can pass in.

I've seen numerous examples of how to use mixins with animations, but they are all kind of verbose, and allow you to animate any properties.  I just need to animate height.  That's it.  I'm looking for the simplest possible way to do that.

Thanks.

Aaron

答:
you could change the animation to max-height like this:

```<code>@keyframes dropdownOpenAnimation {
  from {
      max-height: 0;
  }

  to {
      max-height: 300px;
  }
}
</code>```

the problem is that the small dropdown animation will be faster than the big one. You should change the animation time to achieve the same feeling on both objects.

Title: SASS Mixins to Animate Dropdown Opening

Body:
I have a series of Nav dropdowns.  When the user hovers over one of them, I want it to open using an animation.  So my HTML looks something like this:

Item 1

Item 2

Item A

Item B

Item C

Item D

So short dropdown has 2 items, and medium dropdown has 4.

Here is my SCSS for the short dropdown:

.short-dropdown {
    &.open {
        animation-name: shortDropdownOpenAnimation;
        animation-duration: 400ms;
    }

    &.closed {
        animation-name: shortDropdownCloseAnimation;
        animation-duration: 400ms;
    }
}

And I have the two animations defined thusly:

@keyframes shortDropdownOpenAnimation {
from {
    height: 0px;
}

to {
    height: 50px;
}

}

@keyframes ShortDropdownCloseAnimation {
from {
    height: 50px;
}

to {
    height: 0px;
}

}

So this works great, but now I also have to define keyframes for my medium dropdown.  And as I get more dropdowns with different numbers of items, it would be nice to be able to factor all of these mixins out into just one, that takes a height property that I can pass in.

I've seen numerous examples of how to use mixins with animations, but they are all kind of verbose, and allow you to animate any properties.  I just need to animate height.  That's it.  I'm looking for the simplest possible way to do that.

Thanks.

Aaron

Body:
you could change the animation to max-height like this:

@keyframes dropdownOpenAnimation {
  from {
      max-height: 0;
  }

  to {
      max-height: 300px;
  }
}

the problem is that the small dropdown animation will be faster than the big one. You should change the animation time to achieve the same feeling on both objects.


问:
Opening, edit/rewrite string, save back to a new or same file
I want to open a file, decode the format of data (from base64 to ASCII), rewrite or save the decoded string, either back to the same file, or new one.

I have it opening, reading, decoding (and printing as a test) the decoded base64 string into readable format (ASCII I believe)

My goal is to now save this output to: either a "newfile.txt" document or back to the original "test.mcz" file ready for the next steps of my mission...

I know there are great online base64 decoders and they do work well for what I am doing - I use them often, but my goal is to write my own program as a learning exercise more than anything (also when my internet plays up I need an offline program)

Here's where I am so far (the original file is .mcz format it is a game save)

```<code># PYTHON 3
import base64

f = open('test.mcz', 'r')
f_read = f.read()
# print(f_read) # was just as a test

new_f_read = base64.b64decode(f_read)
print (new_f_read)
</code>```

This prints a butt-load of readable code that is what I need, but I don't want to have to just copy and paste this output from the Python shell into another editor, I want to save it to a file...for convenience.

Either back into the same test.mcz (I will be re-encoding to base64 again later on anyway) or to a new file - thus leaving my original as it was.

problem arises when I want to save/write this decoded output that is stored within the new_f_read variable...it's just been a headache, before I started I could visualise how it needed to be written, I got tripped up when I had to switch it all over to Python3 for some reason (Don't ask...) and I have tried so many variations from online examples - I wouldn't know where to start explaining what I've tried so far. I can't open the original file as both "r" AND "w" together so once Ive opened and decoded I cant reopen the original file as "w" because it just wipes the contents (which are still encoded anyway) -

I think I need to write functions to handle:
1. Open, read, save string to a variable
2. Manipulate string - decode
3. Write the new string to new or existing file

Sounds easy I know, but I am stuck...so here I am. If anyone shows examples, please take the time to explain what is going on, it seems pointless to me having code I don't understand. Apologies if this seems like a simple thing, help would be appreciated..Thanks

答:
The easiest thing is to open first a read file handle, close it then open a write handle. Read/Write handles are complicated because they have to have a pointer to where in the file you are and it add overhead that you don't need to use. You could do it if you wanted, but its a waste of time here.

Using the with operator to open files is recommended since the file will automatically close when you leave the with block.

```<code>import base64

with open('test.mcz', 'r') as f:
    encode = base64.b64decode(f.read())

with open('test.mcz', 'wb') as f:
    f.write(encode)
</code>```

This is the same as

import base64

```<code>f = open('test.mcz', 'r'):
encode = base64.b64decode(f.read())
f.close()
f = open('test.mcz', 'wb'):
f.write(encode)
f.close()
</code>```

Body:
I want to open a file, decode the format of data (from base64 to ASCII), rewrite or save the decoded string, either back to the same file, or new one.

I have it opening, reading, decoding (and printing as a test) the decoded base64 string into readable format (ASCII I believe)

My goal is to now save this output to: either a "newfile.txt" document or back to the original "test.mcz" file ready for the next steps of my mission...

I know there are great online base64 decoders and they do work well for what I am doing - I use them often, but my goal is to write my own program as a learning exercise more than anything (also when my internet plays up I need an offline program)

Here's where I am so far (the original file is .mcz format it is a game save)

# PYTHON 3
import base64

f = open('test.mcz', 'r')
f_read = f.read()
# print(f_read) # was just as a test

new_f_read = base64.b64decode(f_read)
print (new_f_read)

This prints a butt-load of readable code that is what I need, but I don't want to have to just copy and paste this output from the Python shell into another editor, I want to save it to a file...for convenience.

Either back into the same test.mcz (I will be re-encoding to base64 again later on anyway) or to a new file - thus leaving my original as it was.

problem arises when I want to save/write this decoded output that is stored within the new_f_read variable...it's just been a headache, before I started I could visualise how it needed to be written, I got tripped up when I had to switch it all over to Python3 for some reason (Don't ask...) and I have tried so many variations from online examples - I wouldn't know where to start explaining what I've tried so far. I can't open the original file as both "r" AND "w" together so once Ive opened and decoded I cant reopen the original file as "w" because it just wipes the contents (which are still encoded anyway) -

I think I need to write functions to handle:
1. Open, read, save string to a variable
2. Manipulate string - decode
3. Write the new string to new or existing file

Sounds easy I know, but I am stuck...so here I am. If anyone shows examples, please take the time to explain what is going on, it seems pointless to me having code I don't understand. Apologies if this seems like a simple thing, help would be appreciated..Thanks

Body:
The easiest thing is to open first a read file handle, close it then open a write handle. Read/Write handles are complicated because they have to have a pointer to where in the file you are and it add overhead that you don't need to use. You could do it if you wanted, but its a waste of time here.

Using the with operator to open files is recommended since the file will automatically close when you leave the with block.

import base64

with open('test.mcz', 'r') as f:
    encode = base64.b64decode(f.read())

with open('test.mcz', 'wb') as f:
    f.write(encode)

This is the same as

import base64

f = open('test.mcz', 'r'):
encode = base64.b64decode(f.read())
f.close()
f = open('test.mcz', 'wb'):
f.write(encode)
f.close()


问:
Firebase reference doesn't get anything
Problem

I am trying to retrieve data off of my firevase server, and the reference code I am using to do so doesn't retrieve anything.

```<code>getItems(){
</code>```

     var items = [];

     var query = firebase.database().ref('users').child(expoID).orderByKey();

     query.once('value', (snap) => {

        var items = [];

        snap.forEach( (child) => {

            items.push({

       content: child.val().content,

       postKey: child.val().okey,

       color: child.val().color,

       notifKey: child.key

            });

        });

        items.reverse();

        }).then(() => {

        this.setState({firebaseItems: items});

    });

```<code>}
</code>```

expoID is a predefined variable, defined with expo's constants.

Server

The first items under users is the expoID seen in the code above. I tested, and its the same ID.

答:
orderByKey only creates a Query.
To retrieve the actual data you need to listen for an event. once and on are your friends here. There are following event types: "value", "child_added", "child_changed", "child_removed" and "child_moved."

To get the data use "value". So the code to get your data once for example is:

```<code>ref('users').child(expoID).orderByKey().once('value').then(function(snapshot) {
   console.log(snapshot.val());
});
</code>```

Hope this helps!

EDIT:

```<code>// Notice I removed the first declaration of var items
// var items = [];

var query = firebase.database().ref('users').child(expoID).orderByKey();

query.once('value', (snap) => {

  // This array is ONLY valid inside this callback
  var items = [];

  snap.forEach((child) => {
    items.push({
      content: child.val().content,
      postKey: child.val().okey,
      color: child.val().color,
      notifKey: child.key
    });
  });
  items.reverse();
  this.setState({ firebaseItems: items });
});
// No need to set your state in the promise. Just do it directly inside the callback
</code>```

Title: Firebase reference doesn't get anything

Body:
Problem

I am trying to retrieve data off of my firevase server, and the reference code I am using to do so doesn't retrieve anything.

getItems(){

     var items = [];

     var query = firebase.database().ref('users').child(expoID).orderByKey();

     query.once('value', (snap) => {

        var items = [];

        snap.forEach( (child) => {

            items.push({

       content: child.val().content,

       postKey: child.val().okey,

       color: child.val().color,

       notifKey: child.key

            });

        });

        items.reverse();

        }).then(() => {

        this.setState({firebaseItems: items});

    });

}

expoID is a predefined variable, defined with expo's constants.

Server

The first items under users is the expoID seen in the code above. I tested, and its the same ID.

Body:
orderByKey only creates a Query.
To retrieve the actual data you need to listen for an event. once and on are your friends here. There are following event types: "value", "child_added", "child_changed", "child_removed" and "child_moved."

To get the data use "value". So the code to get your data once for example is:

ref('users').child(expoID).orderByKey().once('value').then(function(snapshot) {
   console.log(snapshot.val());
});

Hope this helps!

EDIT:

// Notice I removed the first declaration of var items
// var items = [];

var query = firebase.database().ref('users').child(expoID).orderByKey();

query.once('value', (snap) => {

  // This array is ONLY valid inside this callback
  var items = [];

  snap.forEach((child) => {
    items.push({
      content: child.val().content,
      postKey: child.val().okey,
      color: child.val().color,
      notifKey: child.key
    });
  });
  items.reverse();
  this.setState({ firebaseItems: items });
});
// No need to set your state in the promise. Just do it directly inside the callback


问:
When I catch an exception, how do I get the type, file, and line number?
Catching an exception that would print like this:

```<code>Traceback (most recent call last):
  File "c:/tmp.py", line 1, in <module>
    4 / 0
ZeroDivisionError: integer division or modulo by zero
</code>```

I want to format it into:

```<code>ZeroDivisonError, tmp.py, 1
</code>```

答:
Simplest form that worked for me.

```<code>import traceback

try:
    print(4/0)
except ZeroDivisionError:
    print(traceback.format_exc())
</code>```

Output

```<code>Traceback (most recent call last):
  File "/path/to/file.py", line 51, in <module>
    print(4/0)
ZeroDivisionError: division by zero

Process finished with exit code 0
</code>```

Body:
Catching an exception that would print like this:

Traceback (most recent call last):
  File "c:/tmp.py", line 1, in <module>
    4 / 0
ZeroDivisionError: integer division or modulo by zero

I want to format it into:

ZeroDivisonError, tmp.py, 1

Body:
Simplest form that worked for me.

import traceback

try:
    print(4/0)
except ZeroDivisionError:
    print(traceback.format_exc())

Output

Traceback (most recent call last):
  File "/path/to/file.py", line 51, in <module>
    print(4/0)
ZeroDivisionError: division by zero

Process finished with exit code 0


问:
What is the min and max value of can hold in SQL Server process
I have a server where in I can upload and retrieve data fast when my server is in (take offline) mode but if I live the server (with 150 + process) in SQL Server, I get an error from the application:

The server was unable to process the request due to an internal error.

  For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs.

This is my screenshot of the server

and this is the error in Vb.net application

Error Logs

```<code>Date,Source,Severity,Message
12/05/2017 17:01:09,spid139,Unknown,CHECKDB for database 'SALESANDTRACKING07272017' finished without errors on 2016-06-07 00:00:09.867 (local time). This is an informational message only; no user action is required.
12/05/2017 17:01:06,spid139,Unknown,Starting up database 'SALESANDTRACKING07272017'.
12/05/2017 17:01:06,spid139,Unknown,Setting database option ONLINE to ON for database SALESANDTRACKING07272017.
12/05/2017 17:00:51,spid68,Unknown,Setting database option OFFLINE to ON for database SALESANDTRACKING07272017.
12/05/2017 17:00:51,spid68,Unknown,Process ID 139 was killed by hostname DESKTOP-NAVEQ78<c/> host process ID 18060.
12/05/2017 17:00:51,spid68,Unknown,Process ID 105 was killed by hostname DESKTOP-NAVEQ78<c/> host process ID 18060.
12/05/2017 17:00:51,spid68,Unknown,Process ID 53 was killed by hostname DESKTOP-NAVEQ78<c/> host process ID 18060.
12/05/2017 17:00:44,spid68,Unknown,CHECKDB for database 'SALES07272017' finished without errors on 2016-06-07 00:00:09.867 (local time). This is an informational message only; no user action is required.
12/05/2017 17:00:40,spid68,Unknown,Starting up database 'SALES07272017'.
12/05/2017 17:00:39,spid68,Unknown,Setting database option ONLINE to ON for database SALES07272017.
12/05/2017 17:00:35,spid203,Unknown,Setting database option OFFLINE to ON for database SALES07272017.
12/05/2017 17:00:35,spid203,Unknown,Process ID 145 was killed by hostname DESKTOP-NAVEQ78<c/> host process ID 18060.
12/05/2017 17:00:35,spid203,Unknown,Process ID 134 was killed by hostname DESKTOP-NAVEQ78<c/> host process ID 18060.
12/05/2017 17:00:35,spid203,Unknown,Process ID 68 was killed by hostname DESKTOP-NAVEQ78<c/> host process ID 18060.
12/05/2017 16:41:57,spid70,Unknown,The client was unable to reuse a session with SPID 70<c/> which had been reset for connection pooling. The failure ID is 29. This error may have been caused by an earlier operation failing. Check the error logs for failed operations immediately before this error message.
12/05/2017 16:41:57,spid70,Unknown,Error: 18056<c/> Severity: 20<c/> State: 29.
12/05/2017 16:37:40,spid121,Unknown,The client was unable to reuse a session with SPID 121<c/> which had been reset for connection pooling. The failure ID is 29. This error may have been caused by an earlier operation failing. Check the error logs for failed operations immediately before this error message.
12/05/2017 16:37:40,spid121,Unknown,Error: 18056<c/> Severity: 20<c/> State: 29.
12/05/2017 16:24:36,spid66,Unknown,The client was unable to reuse a session with SPID 66<c/> which had been reset for connection pooling. The failure ID is 29. This error may have been caused by an earlier operation failing. Check the error logs for failed operations immediately before this error message.
12/05/2017 16:24:36,spid66,Unknown,Error: 18056<c/> Severity: 20<c/> State: 29.
12/05/2017 16:23:14,spid61,Unknown,CHECKDB for database 'SALESANDTRACKING' finished without errors on 2016-06-07 00:00:09.867 (local time). This is an informational message only; no user action is required.
12/05/2017 16:23:13,spid61,Unknown,Starting up database 'SALESANDTRACKING'.
12/05/2017 16:23:13,spid61,Unknown,Setting database option ONLINE to ON for database SALESANDTRACKING.
12/05/2017 16:07:20,spid61,Unknown,Setting database option OFFLINE to ON for
</code>```

please see this screen shot from the server (memory usage)

Process in the server

https://ibb.co/nA2AHw

答:
whenever I try to upload data in the server it goes to the servicereference.channelafter that it goes to the api apibilling but the thing here whenever the application sends data to the services and api then from there to server the pooling of process in the server makes the consuming of the memory and for that the error will occur because it cannot handle the other connection in the application

try to change my connection string to my other server with smaller process and it works...  I conclude that the memory is the problem I will upgrade the memory of the server to 64gb.. by the way my current server has 32 ram on thanks for all the help :D it seems that the error is not on the Api or service behavior , it's the memory that causes the problem

and as far as I know on the server you must upgrade the memory if the database will expand fast that there are new users that are currently login in the application then it will have consume another memory.

'=========Updated Answer December 13, 2017 1:16 am------------------

I browse the internet and I search DataAdapter vs. DataReader and I found out that DataAdapter goes to memory cache while the DataReader The DataReader provides an unbuffered stream of data that allows procedural logic to efficiently process results from a data source sequentially. The DataReader is a good choice when retrieving large amounts of data because the data is not cached in memory.

I get that to this link
 http://www.dotnetcurry.com/aspnet/143/convert-data-reader-to-data-table

I use dataadapter when retrieving data so It happens that 150 + process will consume a lot of memory cache

'=========Updated Answer January 16, 2018 1:16 am------------------
My solution from this problem is Indexing

I read from this

What is an index in SQL?

that indexing has the ability to retrieve large amount of data in an instant

but beware to use indexing

I just read this

https://www.sqlpassion.at/archive/2016/03/29/clustered-indexes-advantages-disadvantages/

if you use many indexes the adding,uploading and deleting of data will be slowed

Body:
I have a server where in I can upload and retrieve data fast when my server is in (take offline) mode but if I live the server (with 150 + process) in SQL Server, I get an error from the application:

The server was unable to process the request due to an internal error.

  For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs.

This is my screenshot of the server

and this is the error in Vb.net application

Error Logs

Date,Source,Severity,Message
12/05/2017 17:01:09,spid139,Unknown,CHECKDB for database 'SALESANDTRACKING07272017' finished without errors on 2016-06-07 00:00:09.867 (local time). This is an informational message only; no user action is required.
12/05/2017 17:01:06,spid139,Unknown,Starting up database 'SALESANDTRACKING07272017'.
12/05/2017 17:01:06,spid139,Unknown,Setting database option ONLINE to ON for database SALESANDTRACKING07272017.
12/05/2017 17:00:51,spid68,Unknown,Setting database option OFFLINE to ON for database SALESANDTRACKING07272017.
12/05/2017 17:00:51,spid68,Unknown,Process ID 139 was killed by hostname DESKTOP-NAVEQ78<c/> host process ID 18060.
12/05/2017 17:00:51,spid68,Unknown,Process ID 105 was killed by hostname DESKTOP-NAVEQ78<c/> host process ID 18060.
12/05/2017 17:00:51,spid68,Unknown,Process ID 53 was killed by hostname DESKTOP-NAVEQ78<c/> host process ID 18060.
12/05/2017 17:00:44,spid68,Unknown,CHECKDB for database 'SALES07272017' finished without errors on 2016-06-07 00:00:09.867 (local time). This is an informational message only; no user action is required.
12/05/2017 17:00:40,spid68,Unknown,Starting up database 'SALES07272017'.
12/05/2017 17:00:39,spid68,Unknown,Setting database option ONLINE to ON for database SALES07272017.
12/05/2017 17:00:35,spid203,Unknown,Setting database option OFFLINE to ON for database SALES07272017.
12/05/2017 17:00:35,spid203,Unknown,Process ID 145 was killed by hostname DESKTOP-NAVEQ78<c/> host process ID 18060.
12/05/2017 17:00:35,spid203,Unknown,Process ID 134 was killed by hostname DESKTOP-NAVEQ78<c/> host process ID 18060.
12/05/2017 17:00:35,spid203,Unknown,Process ID 68 was killed by hostname DESKTOP-NAVEQ78<c/> host process ID 18060.
12/05/2017 16:41:57,spid70,Unknown,The client was unable to reuse a session with SPID 70<c/> which had been reset for connection pooling. The failure ID is 29. This error may have been caused by an earlier operation failing. Check the error logs for failed operations immediately before this error message.
12/05/2017 16:41:57,spid70,Unknown,Error: 18056<c/> Severity: 20<c/> State: 29.
12/05/2017 16:37:40,spid121,Unknown,The client was unable to reuse a session with SPID 121<c/> which had been reset for connection pooling. The failure ID is 29. This error may have been caused by an earlier operation failing. Check the error logs for failed operations immediately before this error message.
12/05/2017 16:37:40,spid121,Unknown,Error: 18056<c/> Severity: 20<c/> State: 29.
12/05/2017 16:24:36,spid66,Unknown,The client was unable to reuse a session with SPID 66<c/> which had been reset for connection pooling. The failure ID is 29. This error may have been caused by an earlier operation failing. Check the error logs for failed operations immediately before this error message.
12/05/2017 16:24:36,spid66,Unknown,Error: 18056<c/> Severity: 20<c/> State: 29.
12/05/2017 16:23:14,spid61,Unknown,CHECKDB for database 'SALESANDTRACKING' finished without errors on 2016-06-07 00:00:09.867 (local time). This is an informational message only; no user action is required.
12/05/2017 16:23:13,spid61,Unknown,Starting up database 'SALESANDTRACKING'.
12/05/2017 16:23:13,spid61,Unknown,Setting database option ONLINE to ON for database SALESANDTRACKING.
12/05/2017 16:07:20,spid61,Unknown,Setting database option OFFLINE to ON for

please see this screen shot from the server (memory usage)

Process in the server

https://ibb.co/nA2AHw