问:
100% inline svg width not working in IE11
I have a basic inline svg setup

```<code><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 25.51 25.51">
    <rect id="a1" x="0.5" y="0.5" width="25.51" height="25.51"/>
</svg>
</code>```

JSFIDDLE

In any browser the svg takes the full width, except IE11. The css looks like

```<code>svg {
    stroke: #000;
    stroke-width: 2px;
}

svg rect {
    fill: red;
}
</code>```

I've tried adding width: 100% and display: block to the svg but that didn't help. Any suggestion how I can make the svg 100% in width in IE11?

答:
By default, the attribute preserveAspectRatio = "xMinYMin meet"

Set the value of this attribute none

svg {
    stroke: #000;
    stroke-width: 2px;
}

svg rect {
    fill: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 30 30" preserveAspectRatio = "none">
    <rect id="a1" x="0.5" y="0.5" width="25.51" height="25.51"/>
</svg></code>```

Now the width of svg is 100% in IE11.

But the proportions are not respected and the square is stretched to a rectangle in consultation with the proportions of the browser window. To have a rectangle, you need to set the viewport SVG for example:

```<code>width="900" height="900"
</code>```

<svg xmlns="http://www.w3.org/2000/svg" width="900" height="900" viewBox="0 0 30 30" >
    <rect id="a1" x="0.5" y="0.5" width="25" height="25" stroke-width="2px" stroke="#000" fill="red"/>
</svg>```

Body:
I have a basic inline svg setup

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 25.51 25.51">
    <rect id="a1" x="0.5" y="0.5" width="25.51" height="25.51"/>
</svg>

JSFIDDLE

In any browser the svg takes the full width, except IE11. The css looks like

svg {
    stroke: #000;
    stroke-width: 2px;
}

svg rect {
    fill: red;
}

I've tried adding width: 100% and display: block to the svg but that didn't help. Any suggestion how I can make the svg 100% in width in IE11?

Body:
By default, the attribute preserveAspectRatio = "xMinYMin meet"

Set the value of this attribute none

svg {
    stroke: #000;
    stroke-width: 2px;
}

svg rect {
    fill: red;
}

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 30 30" preserveAspectRatio = "none">
    <rect id="a1" x="0.5" y="0.5" width="25.51" height="25.51"/>
</svg>

Now the width of svg is 100% in IE11.

But the proportions are not respected and the square is stretched to a rectangle in consultation with the proportions of the browser window. To have a rectangle, you need to set the viewport SVG for example:

width="900" height="900"

<svg xmlns="http://www.w3.org/2000/svg" width="900" height="900" viewBox="0 0 30 30" >
    <rect id="a1" x="0.5" y="0.5" width="25" height="25" stroke-width="2px" stroke="#000" fill="red"/>
</svg>


来源: stackexchange

问:
Ag grid tree data

I have an ag grid with tree data which filters out from the view the
  rows which are deleted

```<code>[
   {
      "name":"test",
      "children":[
         {
            "name":"test",
            "ROWSTATE":"DELETE"
         },
         {
            "name":"test",
            "ROWSTATE":"DELETE"
         }
      ]
   }
]
</code>```

this is my data and the filter configuration is like this

```<code>isExternalFilterPresent: () => { return true; },
            doesExternalFilterPass: (node: RowNode) {
        return node.data.ROWSTATE !== ROWSTATE.DELETE;
    }
</code>```

The grid doesn't display any value because all the chilrens does not
  pass the filter function I suppose. What I want to do is to make the grid to
  show the row which contains the parent.

答:
This also happens to me. What I did as a workaround was to modify my getNodeChildDetails function on the gridOptions, in a way such that it checks if all children are deleted. If they all are, then don't return anything. That way, ag-grid won't consider the row as a parent row.

```<code>var gridOptions = {
    ...
    getNodeChildDetails: function(row) {
        if (row.children) {
            for (var i = 0; i < row.children.length; i++) {
                if (row.children[i].ROWSTATE != 'DELETED') {
                    return {
                        group: true,
                        expanded: true,
                        children: row.children
                    };
                }
            }
        }
    },
    ...
};
</code>```

This is inefficient, since it has to iterate through all the children to check if all of them are deleted. However, it is a workaround that works.

Don't forget to add the group cell renderer to the column that will be in charge of the expansion and contraction of the children:

```<code>var columnDefs = [
    ...
    {
        headerName: ...
        cellRenderer: 'group'
    }
];
</code>```

Of course, this applies to whichever framework, either pure javascript or angular.

ContentLicense: CC BY-SA 3.0

Title: Ag grid tree data

Body:
I have an ag grid with tree data which filters out from the view the
  rows which are deleted

[
   {
      "name":"test",
      "children":[
         {
            "name":"test",
            "ROWSTATE":"DELETE"
         },
         {
            "name":"test",
            "ROWSTATE":"DELETE"
         }
      ]
   }
]

this is my data and the filter configuration is like this

isExternalFilterPresent: () => { return true; },
            doesExternalFilterPass: (node: RowNode) {
        return node.data.ROWSTATE !== ROWSTATE.DELETE;
    }

The grid doesn't display any value because all the chilrens does not
  pass the filter function I suppose. What I want to do is to make the grid to
  show the row which contains the parent.

Body:
This also happens to me. What I did as a workaround was to modify my getNodeChildDetails function on the gridOptions, in a way such that it checks if all children are deleted. If they all are, then don't return anything. That way, ag-grid won't consider the row as a parent row.

var gridOptions = {
    ...
    getNodeChildDetails: function(row) {
        if (row.children) {
            for (var i = 0; i < row.children.length; i++) {
                if (row.children[i].ROWSTATE != 'DELETED') {
                    return {
                        group: true,
                        expanded: true,
                        children: row.children
                    };
                }
            }
        }
    },
    ...
};

This is inefficient, since it has to iterate through all the children to check if all of them are deleted. However, it is a workaround that works.

Don't forget to add the group cell renderer to the column that will be in charge of the expansion and contraction of the children:

var columnDefs = [
    ...
    {
        headerName: ...
        cellRenderer: 'group'
    }
];

Of course, this applies to whichever framework, either pure javascript or angular.


问:
Error with window hierarchy when logging out and logging back in
I am trying to implement GoogleSignIn to my iOS app and I have it authenticating and logging the users in but when I log them out and try to log back in I am getting the error "Warning: Attempt to present UITabBarController on LoginViewController whose view is not in the window hierarchy!"

Here is where I sign them in in the AppDelegate:

```<code>func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
    if let error = error {
        print(error.localizedDescription)
        return
    }

    guard let authentication = user.authentication else { return }
    let credential = FIRGoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                   accessToken: authentication.accessToken)
    FIRAuth.auth()?.signIn(with: credential) { (user, error) in
        if let error = error {
            print(error.localizedDescription)
            return
        }
        self.databaseRef = FIRDatabase.database().reference()
        self.databaseRef.child("users").child(user!.uid).observeSingleEvent(of: .value, with: { (snapshot) in
            let snapshot = snapshot.value as? NSDictionary
            if(snapshot == nil){
                self.databaseRef.child("users").child(user!.uid).child("username").setValue(user?.displayName)
                self.databaseRef.child("users").child(user!.uid).child("email").setValue(user?.email)

                let imageUrl = GIDSignIn.sharedInstance().currentUser.profile.imageURL(withDimension: 400).absoluteString
                self.databaseRef.child("users").child(user!.uid).child("profileImageUrl").setValue(imageUrl)
            }
            self.window?.rootViewController?.performSegue(withIdentifier: "signIn_Segue", sender: nil)
        })
    }
}
</code>```

And here is how I log them out and go back to the Start View Controller:

```<code>@IBAction func logout_Clicked(_ sender: Any) {
    do{
        try FIRAuth.auth()?.signOut()
    } catch let logoutError{
        print(logoutError)
    }
    let storyboard = UIStoryboard(name: "Start", bundle: nil)
    let loginVC = storyboard.instantiateViewController(withIdentifier: "LoginViewController")
    self.present(loginVC, animated: true, completion: nil)
}
</code>```

答:
There is bad Approach to present login View controller in Logout Method. you need to reset App after log out. to do this

if you have presented log out view Controller (the view controller in which you have logout @IBaction method) then dismiss it

set rootViewController to LoginViewController.

this code may be helpful,

```<code>    self.dismiss(animated: false, completion: nil)
    let LoginUpViewController = UIStoryboard(name: "Start", bundle: nil).instantiateViewController(withIdentifier: "LoginViewController")
    let appdelegate = UIApplication.shared.delegate as! AppDelegate
    appdelegate.window?.rootViewController = LoginUpViewController
</code>```

or you can change according to your need. changing root to another View Controller will kill previous View Controller along with its child, so your app will completely reset.

Body:
I am trying to implement GoogleSignIn to my iOS app and I have it authenticating and logging the users in but when I log them out and try to log back in I am getting the error "Warning: Attempt to present UITabBarController on LoginViewController whose view is not in the window hierarchy!"

Here is where I sign them in in the AppDelegate:

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
    if let error = error {
        print(error.localizedDescription)
        return
    }

    guard let authentication = user.authentication else { return }
    let credential = FIRGoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                   accessToken: authentication.accessToken)
    FIRAuth.auth()?.signIn(with: credential) { (user, error) in
        if let error = error {
            print(error.localizedDescription)
            return
        }
        self.databaseRef = FIRDatabase.database().reference()
        self.databaseRef.child("users").child(user!.uid).observeSingleEvent(of: .value, with: { (snapshot) in
            let snapshot = snapshot.value as? NSDictionary
            if(snapshot == nil){
                self.databaseRef.child("users").child(user!.uid).child("username").setValue(user?.displayName)
                self.databaseRef.child("users").child(user!.uid).child("email").setValue(user?.email)

                let imageUrl = GIDSignIn.sharedInstance().currentUser.profile.imageURL(withDimension: 400).absoluteString
                self.databaseRef.child("users").child(user!.uid).child("profileImageUrl").setValue(imageUrl)
            }
            self.window?.rootViewController?.performSegue(withIdentifier: "signIn_Segue", sender: nil)
        })
    }
}

And here is how I log them out and go back to the Start View Controller:

@IBAction func logout_Clicked(_ sender: Any) {
    do{
        try FIRAuth.auth()?.signOut()
    } catch let logoutError{
        print(logoutError)
    }
    let storyboard = UIStoryboard(name: "Start", bundle: nil)
    let loginVC = storyboard.instantiateViewController(withIdentifier: "LoginViewController")
    self.present(loginVC, animated: true, completion: nil)
}

Body:
There is bad Approach to present login View controller in Logout Method. you need to reset App after log out. to do this

if you have presented log out view Controller (the view controller in which you have logout @IBaction method) then dismiss it

set rootViewController to LoginViewController.

this code may be helpful,

    self.dismiss(animated: false, completion: nil)
    let LoginUpViewController = UIStoryboard(name: "Start", bundle: nil).instantiateViewController(withIdentifier: "LoginViewController")
    let appdelegate = UIApplication.shared.delegate as! AppDelegate
    appdelegate.window?.rootViewController = LoginUpViewController

or you can change according to your need. changing root to another View Controller will kill previous View Controller along with its child, so your app will completely reset.


问:
bash: how to compare strings with nums and letters?
I have an array the contains element like 1617b, 1516a and the like. I want to echo the elements in descending order-meaning the ones with the greatest number chars in them, and if identical the ones with bigger letter. Any idea on how to do this? Will a simple "if" work? As in:

```<code>if [[ ${array[$j]}>${array[$j+1]} ]]; then
     .
     .
     .
</code>```

tnx in advance

答:
here is one way

```<code>$ ar=(1234a 2345b 1234c 4444d)
$ sorted=$(printf "%s\n" ${ar[@]} | sort | xargs)
$ echo $sorted

1234a 1234c 2345b 4444d
</code>```

for descending order add -r flag to sort

if you want your sorted values back to an array

```<code>$ sorted_ar=($(printf "%s\n" ${ar[@]} | sort))
$ echo ${sorted_ar[@]}
</code>```

Body:
I have an array the contains element like 1617b, 1516a and the like. I want to echo the elements in descending order-meaning the ones with the greatest number chars in them, and if identical the ones with bigger letter. Any idea on how to do this? Will a simple "if" work? As in:

if [[ ${array[$j]}>${array[$j+1]} ]]; then
     .
     .
     .

tnx in advance

Body:
here is one way

$ ar=(1234a 2345b 1234c 4444d)
$ sorted=$(printf "%s\n" ${ar[@]} | sort | xargs)
$ echo $sorted

1234a 1234c 2345b 4444d

for descending order add -r flag to sort

if you want your sorted values back to an array

$ sorted_ar=($(printf "%s\n" ${ar[@]} | sort))
$ echo ${sorted_ar[@]}


问:
Getting state of a text input when pressing enter key in React
I'm taking my first steps with React and I struggle with setting and getting states of an input element.

The application shall render a simple input element without a submit button.

When pressing Enter the current value of the text field shall be written to the console.

So far I've added two event handlers for onKeyUp (checking if Enter was pressed) and another for onChange to output the text field's value.

This is my current code:

```<code>import React, { Component } from "react";
import ReactDOM from "react-dom";

class Terminal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ""};
    this.handleChange = this.handleChange.bind(this);
  }

  handleKey(e) {
    if (e.key === "Enter") {
      console.log("Enter key pressed");
      console.log(this.state.value);
    }
  }

  handleChange(e) {
    this.setState({value: e.target.value});
  }

  render() {
    return (
      <div>
        <span>My Prompt: > </span>
        <input type="text" value={this.state.value} onKeyUp={this.handleKey} onChange={this.handleChange} />
      </div>
    );
  }
}

ReactDOM.render(
  <Terminal />,
  document.getElementById("root")
);
</code>```

Pressing Enter is recognized but logging to the console gives me:

```<code>Uncaught TypeError: Cannot read property 'state' of undefined
    at handleKey (index.js:24)
</code>```

What am I missing here?

答:
You have 2 issues :

You bound handleChange but you forgot to bind handleKey in the constructor .

Better is to not use manual binding , but to use arrow function instead.

```<code>  handleKey = (e)  => {
   //....... ( See second issue )
  }

  handleChange = (e) => {
    this.setState({value: e.target.value});
  }
</code>```

Second issue is how to know "enter" key is pressed . Use

```<code> const keyCode = e.keyCode || e.which;
 if (keyCode === 13) {
   // You code when "Enter" is pressed
 }
</code>```

The demo below should work fine.

    class Terminal extends React.Component {
      // no need explicit constructor !
      state = { value: '', cmds: [] };

      handleKey = e => {
        const keyCode = event.keyCode || event.which;
        if (keyCode === 13) {
          this.setState(({ cmds, value }) => ({
            value: '',
            cmds: [value, ...cmds]
          }));
        }
      };

      handleChange = e => {
        this.setState({ value: e.target.value });
      };

      render() {
        return (

              My Prompt: >
              <input
                type="text"
                value={this.state.value}
                onKeyUp={this.handleKey}
                onChange={this.handleChange}
              />

            {this.state.cmds.map(cmd =>

                {cmd}

            )}

        );
      }
    }

    ReactDOM.render(<Terminal />, document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root" /></code>```

Body:
I'm taking my first steps with React and I struggle with setting and getting states of an input element.

The application shall render a simple input element without a submit button.

When pressing Enter the current value of the text field shall be written to the console.

So far I've added two event handlers for onKeyUp (checking if Enter was pressed) and another for onChange to output the text field's value.

This is my current code:

import React, { Component } from "react";
import ReactDOM from "react-dom";

class Terminal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ""};
    this.handleChange = this.handleChange.bind(this);
  }

  handleKey(e) {
    if (e.key === "Enter") {
      console.log("Enter key pressed");
      console.log(this.state.value);
    }
  }

  handleChange(e) {
    this.setState({value: e.target.value});
  }

  render() {
    return (

        My Prompt: >
        <input type="text" value={this.state.value} onKeyUp={this.handleKey} onChange={this.handleChange} />

    );
  }
}

ReactDOM.render(
  <Terminal />,
  document.getElementById("root")
);

Pressing Enter is recognized but logging to the console gives me:

Uncaught TypeError: Cannot read property 'state' of undefined
    at handleKey (index.js:24)

What am I missing here?

Body:
You have 2 issues :

You bound handleChange but you forgot to bind handleKey in the constructor .

Better is to not use manual binding , but to use arrow function instead.

  handleKey = (e)  => {
   //....... ( See second issue )
  }

  handleChange = (e) => {
    this.setState({value: e.target.value});
  }

Second issue is how to know "enter" key is pressed . Use

 const keyCode = e.keyCode || e.which;
 if (keyCode === 13) {
   // You code when "Enter" is pressed
 }

The demo below should work fine.

    class Terminal extends React.Component {
      // no need explicit constructor !
      state = { value: '', cmds: [] };

      handleKey = e => {
        const keyCode = event.keyCode || event.which;
        if (keyCode === 13) {
          this.setState(({ cmds, value }) => ({
            value: '',
            cmds: [value, ...cmds]
          }));
        }
      };

      handleChange = e => {
        this.setState({ value: e.target.value });
      };

      render() {
        return (
          <div>
            <div>
              <span>My Prompt: > </span>
              <input
                type="text"
                value={this.state.value}
                onKeyUp={this.handleKey}
                onChange={this.handleChange}
              />
            </div>
            {this.state.cmds.map(cmd =>
              <div>
                {cmd}
              </div>
            )}
          </div>
        );
      }
    }

    ReactDOM.render(<Terminal />, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root" />


问:
Calling static method of class loaded via different ClassLoader isn't working. Is this expected?
I have the following class which uses a simple customer ClassLoader to load a class and then call a static method directly on it:

```<code>public class App {

    public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        MyCustClassLoader loader = new MyCustClassLoader();
        Class<?> c = loader.findClass("classloading.FooObservable");
        Object ob = c.newInstance();
        Method md = c.getDeclaredMethod("addListener", Listener.class);

        FooListener fooListener = new FooListener("app class loader");
//        md.invoke(ob, fooListener); <<< works it I uncomment this.
        FooObservable.addListener(fooListener);

        md = c.getMethod("fooDidSomething");
        md.invoke(ob);
        md.invoke(ob);
        md.invoke(ob);
    }

}
</code>```

My custom class loader looks like this:

```<code>package classloading;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MyCustClassLoader extends ClassLoader {
    @Override
    public Class<?> findClass(String name) {
        byte[] bt = loadClassData(name);
        return defineClass(name, bt, 0, bt.length);
    }
    private byte[] loadClassData(String className) {
        //read class
        InputStream is = getClass().getClassLoader().getResourceAsStream(className.replace(".", "/")+".class");
        ByteArrayOutputStream byteSt = new ByteArrayOutputStream();
        //write into byte
        int len =0;
        try {
            while((len=is.read())!=-1){
                byteSt.write(len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //convert into byte array
        return byteSt.toByteArray();
    }

}
</code>```

The static method in question is defined in class FooObservable which contains a list of listeners and a notify method that can be called to notify listeners that something has happened:

```<code>package classloading;

import java.util.ArrayList;
import java.util.List;

public class FooObservable {

        private static List<Listener> listeners = new ArrayList<Listener>();
        int x = 0;

        public static void addListener(Listener l) {
            listeners.add(l);
        }

        public void fooDidSomething() {
            x++;
            for (Listener l : listeners) {
                l.notify(x);
            }
        }

    }
</code>```

It doesn't seem to work, in that nothing is printed. However, when I uncomment the line md.invoke class App above and comment out the static call FooObservable.addListener, it works and I see:

```<code>foo listener (app class loader) notified: 1
foo listener (app class loader) notified: 2
foo listener (app class loader) notified: 3
</code>```

Why is this happening? Is it down to the fact that when the line is uncommented, the static call addListener is invoked against FooObservable which is loaded using the Java AppClassLoader and as such is reloaded with an empty list of listeners?

答:
This line:

```<code>FooObservable.addListener(fooListener);
</code>```

is creating a different instance of FooObservable, created by the default classloader. Because it's a different classloader, it's a totally different object. Calls against the md.<> are against the FooObservable from your class loader. Those are two different instances of the same static class (that's part of the point of classloaders - you can have different instances of the same class).

If instead of calling md.invoke(ob) you called FooObservable.fooDidSomething(), you would see a successful result (from the parent classloader instance).

Without calling md.addListener (the commented out line), the version loaded by your classloader has no listeners.

Body:
I have the following class which uses a simple customer ClassLoader to load a class and then call a static method directly on it:

public class App {

    public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        MyCustClassLoader loader = new MyCustClassLoader();
        Class<?> c = loader.findClass("classloading.FooObservable");
        Object ob = c.newInstance();
        Method md = c.getDeclaredMethod("addListener", Listener.class);

        FooListener fooListener = new FooListener("app class loader");
//        md.invoke(ob, fooListener); <<< works it I uncomment this.
        FooObservable.addListener(fooListener);

        md = c.getMethod("fooDidSomething");
        md.invoke(ob);
        md.invoke(ob);
        md.invoke(ob);
    }

}

My custom class loader looks like this:

package classloading;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MyCustClassLoader extends ClassLoader {
    @Override
    public Class<?> findClass(String name) {
        byte[] bt = loadClassData(name);
        return defineClass(name, bt, 0, bt.length);
    }
    private byte[] loadClassData(String className) {
        //read class
        InputStream is = getClass().getClassLoader().getResourceAsStream(className.replace(".", "/")+".class");
        ByteArrayOutputStream byteSt = new ByteArrayOutputStream();
        //write into byte
        int len =0;
        try {
            while((len=is.read())!=-1){
                byteSt.write(len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //convert into byte array
        return byteSt.toByteArray();
    }

}

The static method in question is defined in class FooObservable which contains a list of listeners and a notify method that can be called to notify listeners that something has happened:

package classloading;

import java.util.ArrayList;
import java.util.List;

public class FooObservable {

        private static List<Listener> listeners = new ArrayList<Listener>();
        int x = 0;

        public static void addListener(Listener l) {
            listeners.add(l);
        }

        public void fooDidSomething() {
            x++;
            for (Listener l : listeners) {
                l.notify(x);
            }
        }

    }

It doesn't seem to work, in that nothing is printed. However, when I uncomment the line md.invoke class App above and comment out the static call FooObservable.addListener, it works and I see:

foo listener (app class loader) notified: 1
foo listener (app class loader) notified: 2
foo listener (app class loader) notified: 3

Why is this happening? Is it down to the fact that when the line is uncommented, the static call addListener is invoked against FooObservable which is loaded using the Java AppClassLoader and as such is reloaded with an empty list of listeners?

Body:
This line:

FooObservable.addListener(fooListener);

is creating a different instance of FooObservable, created by the default classloader. Because it's a different classloader, it's a totally different object. Calls against the md.<> are against the FooObservable from your class loader. Those are two different instances of the same static class (that's part of the point of classloaders - you can have different instances of the same class).

If instead of calling md.invoke(ob) you called FooObservable.fooDidSomething(), you would see a successful result (from the parent classloader instance).

Without calling md.addListener (the commented out line), the version loaded by your classloader has no listeners.


问:
Python attribute name with a variable in it
I am making a desktop programm with Qt+Python and currently I am facing a problem calling some attributes with variable in their names

```<code>self.checkBox_Answer1.clear()
self.checkBox_Answer2.clear()
self.checkBox_Answer3.clear()
self.checkBox_Answer4.clear()
</code>```

Number is the variable, so I want something like

```<code>self."checkBox_Answer%d" % (A).clear()
</code>```

where "A" is my variable which is counted, but coding this way doesnt work

Also tried

```<code>self.str("checkBox_Answer"+"%d" % (A)).clear()
self.checkBox_Answer+"%d" % (A).clear()
</code>```

and nothing works

I know I can do something like

```<code>if A == 1:
    self.checkBox_Answer1.clear()
if A == 2:
    self.checkBox_Answer2.clear()
if A == 3:
    self.checkBox_Answer3.clear()
if A == 4:
    self.checkBox_Answer4.clear()
</code>```

But isn't there more pythonic way to do this stuff?

答:
You can use reflection to get the name of the attribute using getattr. It will affect your performance but it's a cleanest way than a map. </p>

<p>It will looks like: </p>

```<code>getattr(self, "checkBox_Answer"+"%d" % (A))
</code>```

Body:
I am making a desktop programm with Qt+Python and currently I am facing a problem calling some attributes with variable in their names

self.checkBox_Answer1.clear()
self.checkBox_Answer2.clear()
self.checkBox_Answer3.clear()
self.checkBox_Answer4.clear()

Number is the variable, so I want something like

self."checkBox_Answer%d" % (A).clear()

where "A" is my variable which is counted, but coding this way doesnt work

Also tried

self.str("checkBox_Answer"+"%d" % (A)).clear()
self.checkBox_Answer+"%d" % (A).clear()

and nothing works

I know I can do something like

if A == 1:
    self.checkBox_Answer1.clear()
if A == 2:
    self.checkBox_Answer2.clear()
if A == 3:
    self.checkBox_Answer3.clear()
if A == 4:
    self.checkBox_Answer4.clear()

But isn't there more pythonic way to do this stuff?

Body:
You can use reflection to get the name of the attribute using getattr. It will affect your performance but it's a cleanest way than a map.

It will looks like:

getattr(self, "checkBox_Answer"+"%d" % (A))


问:
Can I execute npm install upon the installation of a NuGet package?
I'm creating a NuGet package which contains TypeScript dependencies...node_modules stuff. I don't want to include the node_modules as part of the package, so I'd prefer to execute npm install after the package installation completes. I've installed the package on a test website, and if I manually execute npm install it works.

I can put it in the readme to execute npm install after the package is completed, but I'd prefer to execute it automatically when the install is complete. Is there any way to make that happen?

答:
Historically, we could write an Install.ps1 PowerShell script to invoke certain actions when installing a NuGet package. However, as of NuGet version 3, this feature is no longer supported:

Powershell script support was modified to no longer execute install and uninstall scripts, but init scripts are still executed.

The Init.ps1 script described above allows us to execute actions when a someone installs our package. Although the blog post above suggests that we can still use Init.ps1 scripts in our packages, the lack of recent documentation for this feature and a comment from a NuGet developer seem to indicate that Init.ps1 is also deprecated and that the behavior may not be available in the future. This makes sense if we consider that NuGet also aims to support Mac and Linux for Mono/.NET Core projects, and these systems do not yet include ubiquitous support for PowerShell like Windows (but they may eventually).

For these reasons, I cannot recommend at this time that we automate the package's post-install steps using NuGet's built-in features. The script that runs npm install must also handle challenges on systems where the npm program is missing or not available in the PATH, and some users may not like the idea of the package installing and running arbritrary code. I think it's fair for the project in question to simply instruct the end user in the README to run npm install after installation. Projects with more complex post-installation steps can instruct end users to run a script that executes each step. If you still wish to try using Init.ps1, continue reading:

The current NuGet docs omit information about Init.ps1, but older documentation from 2007 contains this description:

Init.ps1 runs the first time a package is installed in a solution. If the same package is installed into additional projects in the solution, the script is not run during those installations. The script also runs every time the solution is opened. For example, if you install a package, close Visual Studio, and then start Visual Studio and open the solution, the Init.ps1script runs again.

  ...

  These files should be located in the tools directory of your package.

So, we can create an Init.ps1 file in the tools/ directory for our package which might look like the following:

param($installPath, $toolsPath, $package, $project)

Set-Location Path\To\Project\With\Node\Dependencies
npm install
```

...and then generate the NuGet package. The param() statement for the NuGet convention-based scripts provides the following values:

$installPath is the path to your package install

$toolsPath is the path to the tools directory under the package

$package is your package

$project is the project you are installing the application to. Note: This will be null in Init.ps1. It doesn't have a reference to a particular project because it runs at the solution level.

Because this script runs whenever we load a solution, it could slow down Visual Studio. We can add a condition to the script that checks if the packages are installed before running npm. Note that this functionality is restricted to NuGet operations run from Visual Studio or the Package Manager Console and likely will not work using the standalone NuGet CLI program because of the coupling of these scripts to projects and solutions.

Discussion to reintroduce Install.ps1 to NuGet

Body:
Historically, we could write an Install.ps1 PowerShell script to invoke certain actions when installing a NuGet package. However, as of NuGet version 3, this feature is no longer supported:

Powershell script support was modified to no longer execute install and uninstall scripts, but init scripts are still executed.

The Init.ps1 script described above allows us to execute actions when a someone installs our package. Although the blog post above suggests that we can still use Init.ps1 scripts in our packages, the lack of recent documentation for this feature and a comment from a NuGet developer seem to indicate that Init.ps1 is also deprecated and that the behavior may not be available in the future. This makes sense if we consider that NuGet also aims to support Mac and Linux for Mono/.NET Core projects, and these systems do not yet include ubiquitous support for PowerShell like Windows (but they may eventually).

For these reasons, I cannot recommend at this time that we automate the package's post-install steps using NuGet's built-in features. The script that runs npm install must also handle challenges on systems where the npm program is missing or not available in the PATH, and some users may not like the idea of the package installing and running arbritrary code. I think it's fair for the project in question to simply instruct the end user in the README to run npm install after installation. Projects with more complex post-installation steps can instruct end users to run a script that executes each step. If you still wish to try using Init.ps1, continue reading:

The current NuGet docs omit information about Init.ps1, but older documentation from 2007 contains this description:

Init.ps1 runs the first time a package is installed in a solution. If the same package is installed into additional projects in the solution, the script is not run during those installations. The script also runs every time the solution is opened. For example, if you install a package, close Visual Studio, and then start Visual Studio and open the solution, the Init.ps1script runs again.

  ...

  These files should be located in the tools directory of your package.

So, we can create an Init.ps1 file in the tools/ directory for our package which might look like the following:

param($installPath, $toolsPath, $package, $project)

Set-Location Path\To\Project\With\Node\Dependencies
npm install

...and then generate the NuGet package. The param() statement for the NuGet convention-based scripts provides the following values:

$installPath is the path to your package install

$toolsPath is the path to the tools directory under the package

$package is your package

$project is the project you are installing the application to. Note: This will be null in Init.ps1. It doesn't have a reference to a particular project because it runs at the solution level.

Because this script runs whenever we load a solution, it could slow down Visual Studio. We can add a condition to the script that checks if the packages are installed before running npm. Note that this functionality is restricted to NuGet operations run from Visual Studio or the Package Manager Console and likely will not work using the standalone NuGet CLI program because of the coupling of these scripts to projects and solutions.

Discussion to reintroduce Install.ps1 to NuGet


问:
NodeJS Mongoose not working properly
I have a problem with NodeJS and Mongoose. The connection to the DB stands but I can't get any data from there. I can connect to /api/buckets as well with no problems. Here is my code:

app.js

```<code>var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

Bucket = require('./models/bucket');

// Connect to Mongoose
mongoose.connect('mongodb://localhost/worldbucket', function (err) {
    if (err) throw err;
    console.log('Successfully connected');
});

app.get('/', function (req, res) {
    res.send('Please use sth other');
});

app.get('/api/buckets', function (req, res) {
    Bucket.getBuckets(function (err, buckets) {
        console.log("funkt");
        if (err) {
            throw err;
        }
        res.json(buckets);
    });
});

app.listen(3000);
console.log('Running on port 3000');
</code>```

and bucket.js:

```<code>var mongoose = require('mongoose');

// Bucket Schema
var bucketSchema = mongoose.Schema({
    id: mongoose.Schema.Types.ObjectId,
    creator: String,
    text: String,
    fulfilment: String,
    latitude: Number,
    longtitude: Number
});

var  Bucket = mongoose.model('bucket', bucketSchema);

module.exports = Bucket;

// get Buckets
module.exports.getBuckets = (callback, limit) => {
    Bucket.find(callback).limit(limit);
}
</code>```

I hope you can help me.

Thanks in advance

答:
Check the name of your collection in mongo - it should be called buckets not bucket.  It needs to be plural.  Apart from that your code works, I have tested it.

```<code>> db
worldbucket
> db.buckets.insert({"creator":"me","text":"hello world"})
WriteResult({ "nInserted" : 1 })
> db.buckets.find()
{ "_id" : ObjectId("5a0a154a29642fd7a970420e"), "creator" : "me", "text" : "hello world" }

$ curl http://localhost:3000/api/buckets
[{"_id":"5a0a154a29642fd7a970420e","creator":"me","text":"hello world"}]
</code>```

There is another SO thread on this topic here: Why does mongoose always add an s to the end of my collection name

Title: NodeJS Mongoose not working properly

Body:
I have a problem with NodeJS and Mongoose. The connection to the DB stands but I can't get any data from there. I can connect to /api/buckets as well with no problems. Here is my code:

app.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

Bucket = require('./models/bucket');

// Connect to Mongoose
mongoose.connect('mongodb://localhost/worldbucket', function (err) {
    if (err) throw err;
    console.log('Successfully connected');
});

app.get('/', function (req, res) {
    res.send('Please use sth other');
});

app.get('/api/buckets', function (req, res) {
    Bucket.getBuckets(function (err, buckets) {
        console.log("funkt");
        if (err) {
            throw err;
        }
        res.json(buckets);
    });
});

app.listen(3000);
console.log('Running on port 3000');

and bucket.js:

var mongoose = require('mongoose');

// Bucket Schema
var bucketSchema = mongoose.Schema({
    id: mongoose.Schema.Types.ObjectId,
    creator: String,
    text: String,
    fulfilment: String,
    latitude: Number,
    longtitude: Number
});

var  Bucket = mongoose.model('bucket', bucketSchema);

module.exports = Bucket;

// get Buckets
module.exports.getBuckets = (callback, limit) => {
    Bucket.find(callback).limit(limit);
}

I hope you can help me.

Thanks in advance

Body:
Check the name of your collection in mongo - it should be called buckets not bucket.  It needs to be plural.  Apart from that your code works, I have tested it.

> db
worldbucket
> db.buckets.insert({"creator":"me","text":"hello world"})
WriteResult({ "nInserted" : 1 })
> db.buckets.find()
{ "_id" : ObjectId("5a0a154a29642fd7a970420e"), "creator" : "me", "text" : "hello world" }

$ curl http://localhost:3000/api/buckets
[{"_id":"5a0a154a29642fd7a970420e","creator":"me","text":"hello world"}]

There is another SO thread on this topic here: Why does mongoose always add an s to the end of my collection name


问:
Can value after get "?" store in database just by loading the page?
If user open domain.com/article?username=bob then a new row get insert in database table under usernames with the value bob just by loading the page, is it possible ? if yes then how i can achieve this ?

Just like google analytics, if you have analytics on and open domain.com/article?utm_campaign=bob then google analytics store value for bob in their database including visitor's information just on loading the page.

Please pardon my English, Thanks

答:
Assuming you have previously created and connected to a database. Use PHP's $_GET variable to return an array of all parameters in the URL.

Using your example URL: domain.com/article?username=bob

```<code><?php
    // (connect to database here)

    $username = $_GET['username']; // bob
    $sql = "INSERT INTO table_name (column_name) VALUES ('".$username."')";

    // (execute $sql variable here)
?>
</code>```

Body:
Assuming you have previously created and connected to a database. Use PHP's $_GET variable to return an array of all parameters in the URL.

Using your example URL: domain.com/article?username=bob

<?php
    // (connect to database here)

    $username = $_GET['username']; // bob
    $sql = "INSERT INTO table_name (column_name) VALUES ('".$username."')";

    // (execute $sql variable here)
?>


问:
Set footer on bottom (adapted to content) with Angular 4 and Bootstrap 4
¿How can i make a footer stay on bottom of a website with the following structure?:

```<code><html>
    <head>
    </head>

    <body>
        <app-root></app-root>
    </body>

</html>
</code>```

So, the app-root is the main component in angular, inside this component i have the following structure:

```<code><app-navbar></app-navbar>
<div class="container">
    <div class="row">

        <div class="col-12 p-0">
            <app-information *ngIf="title == 'information'"></app-information>
            <app-form *ngIf="title == 'form'"></app-form>
            <app-proyects *ngIf="title == 'proyects'"></app-proyects>
            <app-blog *ngIf="title == 'blog'"></app-blog>
            <app-courses *ngIf="title == 'coursess'"></cursos>
        </div>

    </div>
</div>
<app-footer></app-footer>
</code>```

So, just for understanding, the divs inside the col-12 div are shown depending on a variable called title setted up by pressing buttons on the navbar.
The case is that not all of those divs have content that exceedes the screen size, and the footer goes upwards.

Inside my footer i have this structure:

```<code><footer class="bg-inf-blue" >
    <div class="container p-0">
        <div class="row text-white py-3">
            <div class="col-6 h6 p-0">Contact</div>
            <div class="col-6 h6">Social Media</div>
            <div class="col-2 p-0">
                <ul class="list-unstyled">
                    <li class="h6">Place 1</li>
                    <li>Place 1 address</li>
                    <li>XXX XXX-XXXX</li>
                </ul>
            </div>
            <div class="col-2">
                <ul class="list-unstyled">
                    <li class="h6">Place 2</li>
                    <li>Place 2 address</li>
                    <li>XXX XXX-XXXX</li>
                </ul>
            </div>
            <div class="col-2">
                <ul class="list-unstyled">
                    <li class="h6">Place 3</li>
                    <li>Place 3 address</li>
                    <li>XXX XXX-XXXX</li>
                </ul>
            </div>
            <div class="col-6 align-items-center">
                <a href="https://www.facebook.com/address/" target="blank"><img src="../assets/facebook-logo-button.png" height="40px"></a>
                <a href="https://twitter.com/address" target="blank"><img src="../assets/twitter-logo-button.png" height="40px"></a>
            </div>
            <div class="col-12 p-0">
                <small>Lorem ipsum dolor sit amet consectetur</small>
            </div>
        </div>
    </div>
</footer>
</code>```

what i need is that the footer to stay on the bottom of the screen when the content between the  and  is too short to fill the screen.

If there's a solution with CSS, i'm working with Twitter Bootstrap 4, if there's a solution with typescript, i'm working with Angular 4.

答:
There are a lot of ways to set footer on bottom.
This is one of them:

```<code><div class="wrapper container">

    ... // your html code here

    <div class="push"></div>

</div>
<app-footer></app-footer>

<style>

.wrapper{
    min-height: 100%;
    margin-bottom: -170px;
}

* html .wrapper{
    height: 100%;
}

.push{
    height: 170px;
}

</style>
</code>```

170px is a height of the footer in my case.

Body:
¿How can i make a footer stay on bottom of a website with the following structure?:

        <app-root></app-root>

So, the app-root is the main component in angular, inside this component i have the following structure:

<app-navbar></app-navbar>

            <app-information *ngIf="title == 'information'"></app-information>
            <app-form *ngIf="title == 'form'"></app-form>
            <app-proyects *ngIf="title == 'proyects'"></app-proyects>
            <app-blog *ngIf="title == 'blog'"></app-blog>
            <app-courses *ngIf="title == 'coursess'"></cursos>

<app-footer></app-footer>

So, just for understanding, the divs inside the col-12 div are shown depending on a variable called title setted up by pressing buttons on the navbar.
The case is that not all of those divs have content that exceedes the screen size, and the footer goes upwards.

Inside my footer i have this structure:

Contact

Social Media

Place 1

Place 1 address

XXX XXX-XXXX

Place 2

Place 2 address

XXX XXX-XXXX

Place 3

Place 3 address

XXX XXX-XXXX

                Lorem ipsum dolor sit amet consectetur

what i need is that the footer to stay on the bottom of the screen when the content between the  and  is too short to fill the screen.

If there's a solution with CSS, i'm working with Twitter Bootstrap 4, if there's a solution with typescript, i'm working with Angular 4.

Body:
There are a lot of ways to set footer on bottom.
This is one of them:

<div class="wrapper container">

    ... // your html code here

    <div class="push"></div>

</div>
<app-footer></app-footer>

<style>

.wrapper{
    min-height: 100%;
    margin-bottom: -170px;
}

* html .wrapper{
    height: 100%;
}

.push{
    height: 170px;
}

</style>

170px is a height of the footer in my case.


问:
What is the best software to host a ruby on rails application on production?
Is webrick the only good option?
I know there is a way of using apache, but is it better than webrick?</p>

答:
Phusion Passenger... it's much better than WEBrick. Passenger is the de-facto standard for deploying on Apache. It also has options to run on an Nginx environment, or as a standalone server (like WEBrick). See this question about Passenger Standalone.

There are other less commonly used options, notably including Mongrel.

Also, you might be interested in Heroku, which I use. It's a cloud based production server, and has free deployment options for small sites. Heroku takes care of all the server-side for you, which is a real relief if you're not a server admin (I'm not).

ContentLicense: CC BY-SA 2.5


问:
How to check 2 charAt(i)
I have this lines:

```<code>812.12 135.14 646.17 1
812.12 135.14 646.18 1
812.12 135.14 646.19 10
812.12 135.14 646.20 10
812.12 135.14 646.21 100
812.12 135.14 646.22 100
</code>```

I want to delete only the last group so I did code like this:

```<code>if(lines[i].charAt(lines[i].length())-1>= '0'&&lines[i].charAt(lines[i].length()-1)<= '9'){
    lines[i] = lines[i].substring(0, lines[i].length()-1);
   }

   else if(lines[i].charAt(lines[i].length())>='10'+c&&lines[i].charAt(lines[i].length()-1)<='99'){
   lines[i] = lines[i].substring(0, lines[i].length()-2);
        }

   else if(lines[i].charAt(lines[i].length())>='100'&&lines[i].charAt(lines[i].length()-1)<='999){
   lines[i] = lines[i].substring(0, lines[i].length()-3);
 }
</code>```

And it's now working for me I need help please

答:
It isn't working it says a wrong on this line:

```<code>lines[i] = lines[i].substring(0, index);
</code>```

@Everyone

Title: How to check 2 charAt(i)

Body:
I have this lines:

812.12 135.14 646.17 1
812.12 135.14 646.18 1
812.12 135.14 646.19 10
812.12 135.14 646.20 10
812.12 135.14 646.21 100
812.12 135.14 646.22 100

I want to delete only the last group so I did code like this:

if(lines[i].charAt(lines[i].length())-1>= '0'&&lines[i].charAt(lines[i].length()-1)<= '9'){
    lines[i] = lines[i].substring(0, lines[i].length()-1);
   }

   else if(lines[i].charAt(lines[i].length())>='10'+c&&lines[i].charAt(lines[i].length()-1)<='99'){
   lines[i] = lines[i].substring(0, lines[i].length()-2);
        }

   else if(lines[i].charAt(lines[i].length())>='100'&&lines[i].charAt(lines[i].length()-1)<='999){
   lines[i] = lines[i].substring(0, lines[i].length()-3);
 }

And it's now working for me I need help please

Body:
It isn't working it says a wrong on this line:

lines[i] = lines[i].substring(0, index);

@Everyone


问:
pandas Date get numeric Time intervall
i have the following dataframe example with the Date and Interval:

```<code>       Date     Interval
0   2013-08-01  14:00:00
1   2013-08-01  14:15:00
2   2013-08-01  14:30:00
3   2013-08-01  14:45:00
4   2013-08-01  15:00:00
        ...
</code>```

What i want is a new Column where the Interval is mapped like:

```<code>00:00:00 = 1
00:15:00 = 2
00:30:00 = 3
00:45:00 = 4
    ...
23:45:00 = 96
</code>```

So every 15Minutes is 1 Intervall.
The rows in the dataframe are mixed, so i cant start a counter and increase the value. i need to use the time value in the Interval Column to get the mapped value in the new Column

i tried:

```<code>dates = pandas.to_datetime(df['Interval'])
df['IntervalMapped']= dates.dt.hour * 2 + dates.dt.minute//15 + 1
</code>```

but thats wrong

Title: pandas Date get numeric Time intervall

Body:
i have the following dataframe example with the Date and Interval:

       Date     Interval
0   2013-08-01  14:00:00
1   2013-08-01  14:15:00
2   2013-08-01  14:30:00
3   2013-08-01  14:45:00
4   2013-08-01  15:00:00
        ...

What i want is a new Column where the Interval is mapped like:

00:00:00 = 1
00:15:00 = 2
00:30:00 = 3
00:45:00 = 4
    ...
23:45:00 = 96

So every 15Minutes is 1 Intervall.
The rows in the dataframe are mixed, so i cant start a counter and increase the value. i need to use the time value in the Interval Column to get the mapped value in the new Column

i tried:

dates = pandas.to_datetime(df['Interval'])
df['IntervalMapped']= dates.dt.hour * 2 + dates.dt.minute//15 + 1

but thats wrong

Body:
IIUC, I think you want this:

 df['timestamp'] = pd.to_datetime(df['Date'] + ' ' + df['Interval'])
 df['IntervalMap'] = df['timestamp'].dt.hour.mul(4) + df['timestamp'].dt.minute.floordiv(15) + 1

Output:

         Date  Interval           timestamp  IntervalMap
0  2013-08-01  14:00:00 2013-08-01 14:00:00           57
1  2013-08-01  14:15:00 2013-08-01 14:15:00           58
2  2013-08-01  14:30:00 2013-08-01 14:30:00           59
3  2013-08-01  14:45:00 2013-08-01 14:45:00           60
4  2013-08-01  15:00:00 2013-08-01 15:00:00           61


答:
Create a series with minimum and maximum dates+interval and map that to the datetime column</p>

```<code>df['datetime'] = pd.to_datetime(df['Date'] + ' ' + df['Interval'])

rng = pd.date_range(df['datetime'].min(), df['datetime'].max(), freq = '15T')
s = pd.Series(np.arange(1, len(rng)+1, 1), index = rng)

df['IntervalMapped'] = df['datetime'].map(s)
df.drop('datetime', axis = 1, inplace = True)

    Date        Interval    IntervalMapped
0   2013-08-01  14:00:00    1
1   2013-08-01  14:15:00    2
2   2013-08-01  14:30:00    3
3   2013-08-01  14:45:00    4
4   2013-08-01  15:00:00    5
</code>```

Title: pandas Date get numeric Time intervall

Body:
Create a series with minimum and maximum dates+interval and map that to the datetime column

df['datetime'] = pd.to_datetime(df['Date'] + ' ' + df['Interval'])

rng = pd.date_range(df['datetime'].min(), df['datetime'].max(), freq = '15T')
s = pd.Series(np.arange(1, len(rng)+1, 1), index = rng)

df['IntervalMapped'] = df['datetime'].map(s)
df.drop('datetime', axis = 1, inplace = True)

    Date        Interval    IntervalMapped
0   2013-08-01  14:00:00    1
1   2013-08-01  14:15:00    2
2   2013-08-01  14:30:00    3
3   2013-08-01  14:45:00    4
4   2013-08-01  15:00:00    5


问:
R plot over a background image with coordinates
I have a factory layout in png format shown below.
And I have item moving activity data with coordinates ( starts from (0,0) and ends at (100,100)) like:

```<code>x y
0 4
2 5
4 100
</code>```

(0,4) means item showing in this position and I want to plot a dot. (0,100) indicates the lower-right endpoint.

I expected certain area has darker color if it visited more frequently.

How to plot the activity data into picture file with the right scale respected to the size of the pic?

答:
```<code>library(png)
library(grid)
library(ggplot2)

d <- data.frame(x=c(0,2,4), y= c(4,5,100))

r <- png::readPNG('factory.png')
rg <- grid::rasterGrob(r, width=unit(1,"npc"), height=unit(1,"npc"))

ggplot(d, aes(x,y)) +
  annotation_custom(rg) +
  geom_point(colour="red") +
  scale_x_continuous(expand=c(0,0), lim=c(0,100)) +
  scale_y_continuous(expand=c(0,0), lim=c(0,100)) +
  theme_void() +
  theme(aspect.ratio = nrow(r)/ncol(r))
</code>```

Body:
I have a factory layout in png format shown below.
And I have item moving activity data with coordinates ( starts from (0,0) and ends at (100,100)) like:

x y
0 4
2 5
4 100

(0,4) means item showing in this position and I want to plot a dot. (0,100) indicates the lower-right endpoint.

I expected certain area has darker color if it visited more frequently.

How to plot the activity data into picture file with the right scale respected to the size of the pic?


问:
YouCompleteMe can't find local header files
I currently have a project that is structured as so

```<code>project
|
|----src/
|   |
|   |----test.cpp
|
|----include/
|   |
|   |----test.hpp
|
|----.ycm_extra_conf.py
</code>```

But I can't get YouCompleteMe to recognize test.hpp when it's include in test.cpp

```<code>#include "test.hpp"
</code>```

This is the output of my :YcmDebugInfo

```<code>Printing YouCompleteMe debug information...
-- Client logfile: /tmp/ycm_tcrryhfo.log
-- Server Python interpreter: /usr/bin/python2.7
-- Server Python version: 2.7.14
-- Server has Clang support compiled in: True
-- Clang version: clang version 3.9.1 (tags/RELEASE_391/final)
-- Extra configuration file found and loaded
-- Extra configuration path: /home/jake/project/.ycm_extra_conf.py
-- C-family completer debug information:
--   Compilation database path: None
--   Flags: ['-std=c++11', '-x', 'c++', '-Wall', '-I', 'include', '-isystem', '/usr/include', '-resource-dir=/home/jake/.local/share/nvim/plugged/YouCompleteMe/third_party/ycmd/ycmd/../clang_includes', '-fspell-checking']
-- Server running at: http://127.0.0.1:59337
-- Server process ID: 21577
-- Server logfiles:
--   /tmp/ycmd_59337_stdout_kndkmx3g.log
--   /tmp/ycmd_59337_stderr__xriaszp.log
</code>```

There are no errors present in the server log files, but the client logfile has a few errors that ultimately begins with this:

```<code>Traceback (most recent call last):
  File "/home/jake/.local/share/nvim/plugged/YouCompleteMe/autoload/../python/ycm/client/base_request.py", line 214, in HandleServerException
yield
  File "/home/jake/.local/share/nvim/plugged/YouCompleteMe/autoload/../python/ycm/youcompleteme.py", line 237, in CheckIfServerIsReady
'ready' )
  File "/home/jake/.local/share/nvim/plugged/YouCompleteMe/autoload/../python/ycm/client/base_request.py", line 68, in GetDataFromHandler
timeout ) )
  File "/home/jake/.local/share/nvim/plugged/YouCompleteMe/autoload/../python/ycm/client/base_request.py", line 180, in JsonFromFuture
response = future.result()
  File "/usr/lib64/python3.4/concurrent/futures/_base.py", line 402, in result
return self.__get_result()
  File "/usr/lib64/python3.4/concurrent/futures/_base.py", line 354, in __get_result
raise self._exception
  File "/home/jake/.local/share/nvim/plugged/YouCompleteMe/autoload/../python/ycm/unsafe_thread_pool_executor.py", line 43, in run
result = self.fn(*self.args, **self.kwargs)
  File "/home/jake/.local/share/nvim/plugged/YouCompleteMe/third_party/ycmd/third_party/requests/requests/sessions.py", line 468, in request
resp = self.send(prep, **send_kwargs)
  File "/home/jake/.local/share/nvim/plugged/YouCompleteMe/third_party/ycmd/third_party/requests/requests/sessions.py", line 576, in send
r = adapter.send(request, **kwargs)
  File "/home/jake/.local/share/nvim/plugged/YouCompleteMe/third_party/ycmd/third_party/requests/requests/adapters.py", line 437, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=34155): Max retries exceeded with url: /ready (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x7f32a77aa048>: Failed to establish a new connection: [Errno 111] Connection refused',))
</code>```

Other than this everything seems to be working although it will offer variables that are out of scope as suggestions when autocompleting (Suggests member variables of different classes).

I followed the full installation guide and set my external clang to /usr/lib/libclang.so

I have no idea what's causing this.

答:
The default .ycm_extra_conf.py doesn't look for headers in nearby include directories.

This lookup is done in JDevlieghere's configuration, which I adapted to also add a flag for the include path root (in function FlagsForInclude):

import os
import os.path
import fnmatch
import logging
import ycm_core
import re

BASE_FLAGS = [
        '-Wall',
        '-Wextra',
        '-Werror',
        '-Wno-long-long',
        '-Wno-variadic-macros',
        '-fexceptions',
        '-ferror-limit=10000',
        '-DNDEBUG',
        '-std=c++1z',
        '-xc++',
        '-I/usr/lib/',
        '-I/usr/include/'
        ]

SOURCE_EXTENSIONS = [
        '.cpp',
        '.cxx',
        '.cc',
        '.c',
        '.m',
        '.mm'
        ]

SOURCE_DIRECTORIES = [
        'src',
        'lib'
        ]

HEADER_EXTENSIONS = [
        '.h',
        '.hxx',
        '.hpp',
        '.hh'
        ]

HEADER_DIRECTORIES = [
        'include'
        ]

BUILD_DIRECTORY = 'build';

def IsHeaderFile(filename):
    extension = os.path.splitext(filename)[1]
    return extension in HEADER_EXTENSIONS

def GetCompilationInfoForFile(database, filename):
    if IsHeaderFile(filename):
        basename = os.path.splitext(filename)[0]
        for extension in SOURCE_EXTENSIONS:
            # Get info from the source files by replacing the extension.
            replacement_file = basename + extension
            if os.path.exists(replacement_file):
                compilation_info = database.GetCompilationInfoForFile(replacement_file)
                if compilation_info.compiler_flags_:
                    return compilation_info
            # If that wasn't successful, try replacing possible header directory with possible source directories.
            for header_dir in HEADER_DIRECTORIES:
                for source_dir in SOURCE_DIRECTORIES:
                    src_file = replacement_file.replace(header_dir, source_dir)
                    if os.path.exists(src_file):
                        compilation_info = database.GetCompilationInfoForFile(src_file)
                        if compilation_info.compiler_flags_:
                            return compilation_info
        return None
    return database.GetCompilationInfoForFile(filename)

def FindNearest(path, target, build_folder=None):
    candidate = os.path.join(path, target)
    if(os.path.isfile(candidate) or os.path.isdir(candidate)):
        logging.info("Found nearest " + target + " at " + candidate)
        return candidate;

    parent = os.path.dirname(os.path.abspath(path));
    if(parent == path):
        raise RuntimeError("Could not find " + target);

    if(build_folder):
        candidate = os.path.join(parent, build_folder, target)
        if(os.path.isfile(candidate) or os.path.isdir(candidate)):
            logging.info("Found nearest " + target + " in build folder at " + candidate)
            return candidate;

    return FindNearest(parent, target, build_folder)

def MakeRelativePathsInFlagsAbsolute(flags, working_directory):
    if not working_directory:
        return list(flags)
    new_flags = []
    make_next_absolute = False
    path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ]
    for flag in flags:
        new_flag = flag

        if make_next_absolute:
            make_next_absolute = False
            if not flag.startswith('/'):
                new_flag = os.path.join(working_directory, flag)

        for path_flag in path_flags:
            if flag == path_flag:
                make_next_absolute = True
                break

            if flag.startswith(path_flag):
                path = flag[ len(path_flag): ]
                new_flag = path_flag + os.path.join(working_directory, path)
                break

        if new_flag:
            new_flags.append(new_flag)
    return new_flags

def FlagsForClangComplete(root):
    try:
        clang_complete_path = FindNearest(root, '.clang_complete')
        clang_complete_flags = open(clang_complete_path, 'r').read().splitlines()
        return clang_complete_flags
    except:
        return None

def FlagsForInclude(root):
    try:
        include_path = FindNearest(root, 'include')
        flags = []
        for dirroot, dirnames, filenames in os.walk(include_path):
            flags = flags + ["-I" + dirroot]
            for dir_path in dirnames:
                real_path = os.path.join(dirroot, dir_path)
                flags = flags + ["-I" + real_path]
        return flags
    except:
        return None

def FlagsForCompilationDatabase(root, filename):
    try:
        # Last argument of next function is the name of the build folder for
        # out of source projects
        compilation_db_path = FindNearest(root, 'compile_commands.json', BUILD_DIRECTORY)
        compilation_db_dir = os.path.dirname(compilation_db_path)
        logging.info("Set compilation database directory to " + compilation_db_dir)
        compilation_db =  ycm_core.CompilationDatabase(compilation_db_dir)
        if not compilation_db:
            logging.info("Compilation database file found but unable to load")
            return None
        compilation_info = GetCompilationInfoForFile(compilation_db, filename)
        if not compilation_info:
            logging.info("No compilation info for " + filename + " in compilation database")
            return None
        return MakeRelativePathsInFlagsAbsolute(
                compilation_info.compiler_flags_,
                compilation_info.compiler_working_dir_)
    except:
        return None

def FlagsForFile(filename):
    root = os.path.realpath(filename);
    compilation_db_flags = FlagsForCompilationDatabase(root, filename)
    if compilation_db_flags:
        final_flags = compilation_db_flags
    else:
        final_flags = BASE_FLAGS
        clang_flags = FlagsForClangComplete(root)
        if clang_flags:
            final_flags = final_flags + clang_flags
        include_flags = FlagsForInclude(root)
        if include_flags:
            final_flags = final_flags + include_flags
    return {
            'flags': final_flags,
            'do_cache': True
            }
```

Body:
I currently have a project that is structured as so

project
|
|----src/
|   |
|   |----test.cpp
|
|----include/
|   |
|   |----test.hpp
|
|----.ycm_extra_conf.py

But I can't get YouCompleteMe to recognize test.hpp when it's include in test.cpp

#include "test.hpp"

This is the output of my :YcmDebugInfo

Printing YouCompleteMe debug information...
-- Client logfile: /tmp/ycm_tcrryhfo.log
-- Server Python interpreter: /usr/bin/python2.7
-- Server Python version: 2.7.14
-- Server has Clang support compiled in: True
-- Clang version: clang version 3.9.1 (tags/RELEASE_391/final)
-- Extra configuration file found and loaded
-- Extra configuration path: /home/jake/project/.ycm_extra_conf.py
-- C-family completer debug information:
--   Compilation database path: None
--   Flags: ['-std=c++11', '-x', 'c++', '-Wall', '-I', 'include', '-isystem', '/usr/include', '-resource-dir=/home/jake/.local/share/nvim/plugged/YouCompleteMe/third_party/ycmd/ycmd/../clang_includes', '-fspell-checking']
-- Server running at: http://127.0.0.1:59337
-- Server process ID: 21577
-- Server logfiles:
--   /tmp/ycmd_59337_stdout_kndkmx3g.log
--   /tmp/ycmd_59337_stderr__xriaszp.log

There are no errors present in the server log files, but the client logfile has a few errors that ultimately begins with this:

Traceback (most recent call last):
  File "/home/jake/.local/share/nvim/plugged/YouCompleteMe/autoload/../python/ycm/client/base_request.py", line 214, in HandleServerException
yield
  File "/home/jake/.local/share/nvim/plugged/YouCompleteMe/autoload/../python/ycm/youcompleteme.py", line 237, in CheckIfServerIsReady
'ready' )
  File "/home/jake/.local/share/nvim/plugged/YouCompleteMe/autoload/../python/ycm/client/base_request.py", line 68, in GetDataFromHandler
timeout ) )
  File "/home/jake/.local/share/nvim/plugged/YouCompleteMe/autoload/../python/ycm/client/base_request.py", line 180, in JsonFromFuture
response = future.result()
  File "/usr/lib64/python3.4/concurrent/futures/_base.py", line 402, in result
return self.__get_result()
  File "/usr/lib64/python3.4/concurrent/futures/_base.py", line 354, in __get_result
raise self._exception
  File "/home/jake/.local/share/nvim/plugged/YouCompleteMe/autoload/../python/ycm/unsafe_thread_pool_executor.py", line 43, in run
result = self.fn(*self.args, **self.kwargs)
  File "/home/jake/.local/share/nvim/plugged/YouCompleteMe/third_party/ycmd/third_party/requests/requests/sessions.py", line 468, in request
resp = self.send(prep, **send_kwargs)
  File "/home/jake/.local/share/nvim/plugged/YouCompleteMe/third_party/ycmd/third_party/requests/requests/sessions.py", line 576, in send
r = adapter.send(request, **kwargs)
  File "/home/jake/.local/share/nvim/plugged/YouCompleteMe/third_party/ycmd/third_party/requests/requests/adapters.py", line 437, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=34155): Max retries exceeded with url: /ready (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x7f32a77aa048>: Failed to establish a new connection: [Errno 111] Connection refused',))

Other than this everything seems to be working although it will offer variables that are out of scope as suggestions when autocompleting (Suggests member variables of different classes).

I followed the full installation guide and set my external clang to /usr/lib/libclang.so

I have no idea what's causing this.


问:
Checking Symbolic Equation Equality in Matlab
How can one check if symbolic eq1 is equal to symbolic eq2 in Matlab:</p>

```<code>syms a x y
eq1 = a*(x+y)
eq2 = a*x + a*y
</code>```

答:
For symbolic math and Matlab R2012a+, in general it's best to use isAlways to check if an equality or inequality holds. For your example,

```<code>isAlways(eq1==eq2)
</code>```

returns logical true (1). The isAlways function considers assumptions and can gracefully handle undecidable conditions. The solution from @gnovice can be used in older versions of Matlab, but will fail by throwing an error when an expression can't be proved, e.g., logical(simplify(2*x >= x)).

Body:
How can one check if symbolic eq1 is equal to symbolic eq2 in Matlab:

syms a x y
eq1 = a*(x+y)
eq2 = a*x + a*y

Body:
For symbolic math and Matlab R2012a+, in general it's best to use isAlways to check if an equality or inequality holds. For your example,

isAlways(eq1==eq2)

returns logical true (1). The isAlways function considers assumptions and can gracefully handle undecidable conditions. The solution from @gnovice can be used in older versions of Matlab, but will fail by throwing an error when an expression can't be proved, e.g., logical(simplify(2*x >= x)).


问:
Ignoring a malformed part of a JSON object while parsing it, in Julia
I have the following JSON string in my DataFrame

```<code>{\"id\": 312, \"type\": \"Symbol\", \"children\": {\"right\": {\"id\": 313, \"type\": \"BinaryOperation\", \"children\": {\"right\": {\"id\": 314, \"type\": \"Fraction\", \"children\": {\"right\": {\"id\": 317, \"type\": \"Brackets\", \"children\": {\"argument\": {\"id\": 318, \"type\": \"Fn\", \"children\": {\"right\": {\"id\": 320, \"type\": \"BinaryOperation\", \"children\": {\"right\": {\"id\": 321, \"type\": \"Num\", \"properties\": {\"significand\": \"1\"}}}, \"properties\": {\"operation\": \"+\"}}, \"argument\": {\"id\": 319, \"type\": \"Symbol\", \"properties\": {\"letter\": \"x\"}}}, \"properties\": {\"name\": \"ln\", \"allowSubscript\": false}}}, \"properties\": {\"type\": \"round\"}}, \"numerator\": {\"id\": 315, \"type\": \"Num\", \"properties\": {\"significand\": \"1\"}}, \"denominator\": {\"id\": 316, \"type\": \"Symbol\", \"properties\": {\"letter\": \"x\"}}}}}, \"properties\": {\"operation\": \"−\"}}}, \"position\": {\"x\": 114.97000305175781, \"y\": 231}, \"expression\": {\"latex\": \"k - \\frac{1}{x}\\left(\\ln(x) + 1\\right)\", \"python\": \"k - (1)/(x) * (ln(x) + 1)\"}, \"properties\": {\"letter\": \"k\"}}
</code>```

Any parser will choke on .expression.latex because of the escaped slashes. Apparently, \f and \r are fine, but there needs to be an escaped slash in front of an l, thus that string for key latex should read more like

```<code>\"k - \\frac{1}{x}\\\\left(\\\\ln(x) + 1\\right)\"
</code>```

which JSON.parse now parses fine. Now, I could simply replace an escaped l with one with more escaping (\\\l) but in practice I don't even need to parse that part of the object at all, that is, I can drop the expression key entirely. Is there a way of catching the error and telling the parser that it's OK to drop it and go ahead with the rest, or should I just suck it up and add extra escaping?

答:
Since there are no escaped values in the JSON string replacing the backslashes with escaped backslashes can bring the string to a parsable format. Try:

```<code>using JSON
unescaped = ".... <string from question> ...."
escaped = replace(unescaped, "\\", "\\\\")
JSON.Parser.parse(escaped)
</code>```

Giving:

```<code>Dict{String,Any} with 6 entries:
  "expression" => Dict{String,Any}(Pair{String,Any}("latex", "k - \\frac{1}{x}\\left(\\ln(x) + 1\\right)"),Pair{String,Any}("pyt…
  "properties" => Dict{String,Any}(Pair{String,Any}("letter", "k"))
  "id"         => 312
  "position"   => Dict{String,Any}(Pair{String,Any}("x", 114.97),Pair{String,Any}("y", 231))
  "type"       => "Symbol"
  "children"   => Dict{String,Any}(Pair{String,Any}("right", Dict{String,Any}(Pair{String,Any}("properties", Dict{String,Any}(Pa…
</code>```

Update

Perhaps a better solution would be to target the replacement to just the latex field in expression in the following way (assuming it is the only source of trouble and there are no problems like the comments mentions):

```<code>newjson = replace(json, r"\"latex\": \"([^\"]*)\"", s -> replace(s,"\\","\\\\"))
</code>```

Update 2

The problem arises because JSON.Parser.parse handles escaping, while LaTeX can accidentally introduce these escape sequences. As suggested by Liso in the comments:

```<code>escaped = replace(unescaped, r"\\([^\"\\/bfnrt])", s"\\\\\1")
</code>```

would escape the backslash in the unescaped string and thus avoid unnecessary handling by JSON.Parser.parse. Note the list of escaped characters is in a dictionary accessible as JSON.Common.ESCAPES.

Body:
I have the following JSON string in my DataFrame

{\"id\": 312, \"type\": \"Symbol\", \"children\": {\"right\": {\"id\": 313, \"type\": \"BinaryOperation\", \"children\": {\"right\": {\"id\": 314, \"type\": \"Fraction\", \"children\": {\"right\": {\"id\": 317, \"type\": \"Brackets\", \"children\": {\"argument\": {\"id\": 318, \"type\": \"Fn\", \"children\": {\"right\": {\"id\": 320, \"type\": \"BinaryOperation\", \"children\": {\"right\": {\"id\": 321, \"type\": \"Num\", \"properties\": {\"significand\": \"1\"}}}, \"properties\": {\"operation\": \"+\"}}, \"argument\": {\"id\": 319, \"type\": \"Symbol\", \"properties\": {\"letter\": \"x\"}}}, \"properties\": {\"name\": \"ln\", \"allowSubscript\": false}}}, \"properties\": {\"type\": \"round\"}}, \"numerator\": {\"id\": 315, \"type\": \"Num\", \"properties\": {\"significand\": \"1\"}}, \"denominator\": {\"id\": 316, \"type\": \"Symbol\", \"properties\": {\"letter\": \"x\"}}}}}, \"properties\": {\"operation\": \"−\"}}}, \"position\": {\"x\": 114.97000305175781, \"y\": 231}, \"expression\": {\"latex\": \"k - \\frac{1}{x}\\left(\\ln(x) + 1\\right)\", \"python\": \"k - (1)/(x) * (ln(x) + 1)\"}, \"properties\": {\"letter\": \"k\"}}

Any parser will choke on .expression.latex because of the escaped slashes. Apparently, \f and \r are fine, but there needs to be an escaped slash in front of an l, thus that string for key latex should read more like

\"k - \\frac{1}{x}\\\\left(\\\\ln(x) + 1\\right)\"

which JSON.parse now parses fine. Now, I could simply replace an escaped l with one with more escaping (\\\l) but in practice I don't even need to parse that part of the object at all, that is, I can drop the expression key entirely. Is there a way of catching the error and telling the parser that it's OK to drop it and go ahead with the rest, or should I just suck it up and add extra escaping?

Body:
Since there are no escaped values in the JSON string replacing the backslashes with escaped backslashes can bring the string to a parsable format. Try:

using JSON
unescaped = ".... <string from question> ...."
escaped = replace(unescaped, "\\", "\\\\")
JSON.Parser.parse(escaped)

Giving:

Dict{String,Any} with 6 entries:
  "expression" => Dict{String,Any}(Pair{String,Any}("latex", "k - \\frac{1}{x}\\left(\\ln(x) + 1\\right)"),Pair{String,Any}("pyt…
  "properties" => Dict{String,Any}(Pair{String,Any}("letter", "k"))
  "id"         => 312
  "position"   => Dict{String,Any}(Pair{String,Any}("x", 114.97),Pair{String,Any}("y", 231))
  "type"       => "Symbol"
  "children"   => Dict{String,Any}(Pair{String,Any}("right", Dict{String,Any}(Pair{String,Any}("properties", Dict{String,Any}(Pa…

Update

Perhaps a better solution would be to target the replacement to just the latex field in expression in the following way (assuming it is the only source of trouble and there are no problems like the comments mentions):

newjson = replace(json, r"\"latex\": \"([^\"]*)\"", s -> replace(s,"\\","\\\\"))

Update 2

The problem arises because JSON.Parser.parse handles escaping, while LaTeX can accidentally introduce these escape sequences. As suggested by Liso in the comments:

escaped = replace(unescaped, r"\\([^\"\\/bfnrt])", s"\\\\\1")

would escape the backslash in the unescaped string and thus avoid unnecessary handling by JSON.Parser.parse. Note the list of escaped characters is in a dictionary accessible as JSON.Common.ESCAPES.


问:
PHP MySQL not returning 1 for login
My code below doesn't go to if ( $loginsuccess == 1 ). Everytime i try logging in it directs me to the else{ part of my code.

```<code><?PHP
    session_start();

    $userid = $_POST['userid'];
    $password = $_POST['password'];
    $loginsuccess = 0;

    $con = mysqli_connect('localhost', 'root');

    if (!$con)
      {
      die('Could not connect: ' . mysqli_error($con));
      }

    mysqli_select_db($con, 'btr');

    $result = mysqli_query("SELECT * FROM user WHERE UserID='" . $userid . "'");

    while($row = mysqli_fetch_array($result))
    {

          if ( $row['password'] == $password ){
              $loginsuccess = 1;
          }
    }

    mysqli_close($con);

?>
</code>```

<!DOCTYPE html>

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.css" />

<title>Test</title>

<?PHP

 if ( $loginsuccess == 1 ){

  $_SESSION['userid'] = $userid;

?>

        Test

 Login successful. You will be redirected to main page in 3 seconds...

 Back

      Test

<?PHP

 } else{

  unset($_SESSION['userid']);

?>

 Test

 Invalid id or password. You will be redirected to login page in 3 seconds...

 Login

      Test

<?PHP

 }

?>

```
</div>
</div>
</p>

<p>could it be the data pass from the previous page ? </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?PHP
 session_start();
?>

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.css" />
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=true" type="text/javascript"></script>
<script type="text/javascript">
<!--
function redirect_index(){
    window.location = "menu.php"
}
function redirect_login(){
    window.location = "login.php"
}
//-->
</script>
<title>/title>
</head>
<body>

<div data-role="page">
    <div data-role="header">
      <h1>
        Login
      </h1>
    </div>
    <div data-role="content">
      <form method="post" action="login_script.php">

        <div data-role="fieldcontain">
          <label for="userid">
            ID
          </label>
          <input type="text" name="userid" id="userid" value=""/>
        </div>
        <div data-role="fieldcontain">
          <label for="password">
            Password
          </label>

          <input type="password" name="password" id="password" value=""/>
        </div>
        <input type="submit" value="Login" data-role="button" data-inline="true"/>
 </form>

    </div>
    <div data-role="footer">

    </div>
  </div>

</body>
</html></code>```

答:
Please check this line of your code:

```<code>$result = mysqli_query("SELECT * FROM user WHERE UserID='" . $userid . "'");
</code>```

I think the SQL query doesn't need the single quote. (like this: SELECT * FROM user WHERE UserID='userid') If you use the single quotes the userid is interpreted as text and not as number. In this case it wouldn't find any entry for a user and in a row no password.

Try this line instead:

```<code>$result = mysqli_query("SELECT * FROM user WHERE UserID=" . $userid);
</code>```

Title: PHP MySQL not returning 1 for login

Body:
My code below doesn't go to if ( $loginsuccess == 1 ). Everytime i try logging in it directs me to the else{ part of my code.

<?PHP
    session_start();

    $userid = $_POST['userid'];
    $password = $_POST['password'];
    $loginsuccess = 0;

    $con = mysqli_connect('localhost', 'root');

    if (!$con)
      {
      die('Could not connect: ' . mysqli_error($con));
      }

    mysqli_select_db($con, 'btr');

    $result = mysqli_query("SELECT * FROM user WHERE UserID='" . $userid . "'");

    while($row = mysqli_fetch_array($result))
    {

          if ( $row['password'] == $password ){
              $loginsuccess = 1;
          }
    }

    mysqli_close($con);

?>

<!DOCTYPE html>

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.css" />

<title>Test</title>

<?PHP

 if ( $loginsuccess == 1 ){

  $_SESSION['userid'] = $userid;

?>

        Test

 Login successful. You will be redirected to main page in 3 seconds...

 Back

      Test

<?PHP

 } else{

  unset($_SESSION['userid']);

?>

 Test

 Invalid id or password. You will be redirected to login page in 3 seconds...

 Login

      Test

<?PHP

 }

?>

could it be the data pass from the previous page ?

<?PHP
 session_start();
?>

<!DOCTYPE html>

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.css" />

<title>/title>

        Login

      <form method="post" action="login_script.php">

            ID

          <input type="text" name="userid" id="userid" value=""/>

            Password

          <input type="password" name="password" id="password" value=""/>

        <input type="submit" value="Login" data-role="button" data-inline="true"/>
 </form>

Body:
Please check this line of your code:

$result = mysqli_query("SELECT * FROM user WHERE UserID='" . $userid . "'");

I think the SQL query doesn't need the single quote. (like this: SELECT * FROM user WHERE UserID='userid') If you use the single quotes the userid is interpreted as text and not as number. In this case it wouldn't find any entry for a user and in a row no password.

Try this line instead:

$result = mysqli_query("SELECT * FROM user WHERE UserID=" . $userid);


问:
How to wget a URL with HTTPS
I want to download "https://www.luisaviaroma.com/en-us/shop/home" with wget. I have tried wget --no-cookie --no-check-certificate https://www.luisaviaroma.com/en-us/shop/home. But it shows
HTTP request sent, awaiting response... and no more response. How should I download the page with Wget?

答:
It seems this page at that URL is only accessible using HTTP/2, for instance using cURL:

curl -v 'https://www.luisaviaroma.com/en-us/shop/home' \
     -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'
```

<p>which gives:</p>

```* Using HTTP/2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x55d1310c6da0)
> GET /en-us/shop/home HTTP/1.1
> Host: www.luisaviaroma.com
> Accept: */*
> User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
>
* Connection state changed (MAX_CONCURRENT_STREAMS updated)!
< HTTP/2 200
< content-type: text/html; charset=utf-8
< server: Microsoft-IIS/8.5
< x-aspnet-version: 4.0.30319
< x-powered-by: ASP.NET
< access-control-allow-origin: *
< x-akamai-transformed: 9 - 0 pmb=mTOE,2
< expires: Mon, 13 Nov 2017 21:34:13 GMT
< cache-control: max-age=0, no-cache, no-store
< pragma: no-cache
< date: Mon, 13 Nov 2017 21:34:13 GMT
```

<p>But when forcing to HTTP 1.0 or HTTP 1.1,</p>

<pre class="lang-bash prettyprint-override"><code>curl -v 'https://www.luisaviaroma.com/en-us/shop/home' \
     -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36' \
     --http1.0
</code>```

it gives a different result:

```<code>> GET /en-us/shop/home HTTP/1.0
> Host: www.luisaviaroma.com
> Accept: */*
> User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Server: Apache
< ETag: "9c027fecce6719909433b8a37b2b403a:1493300815"
< Last-Modified: Thu, 27 Apr 2017 13:46:55 GMT
< Accept-Ranges: bytes
< Content-Length: 31186
< Content-Type: text/html
< Expires: Mon, 13 Nov 2017 21:36:19 GMT
< Cache-Control: max-age=0, no-cache, no-store
< Pragma: no-cache
< Date: Mon, 13 Nov 2017 21:36:19 GMT
< Connection: close
</code>```

Using HTTP 1.0 or HTTP 1.1, we hit a different server serving a different page while using HTTP 2.0 it gives the expected page.

Using cURL which support HTTP 2.0 you will be able to download this page, for instance to save it under homepage.html:

curl 'https://www.luisaviaroma.com/en-us/shop/home' \
     -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36' \
     -o homepage.html
```

ContentLicense: CC BY-SA 4.0

Title: How to wget a URL with HTTPS

Body:
It seems this page at that URL is only accessible using HTTP/2, for instance using cURL:

curl -v 'https://www.luisaviaroma.com/en-us/shop/home' \
     -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'

which gives:

* Using HTTP/2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x55d1310c6da0)
> GET /en-us/shop/home HTTP/1.1
> Host: www.luisaviaroma.com
> Accept: */*
> User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
>
* Connection state changed (MAX_CONCURRENT_STREAMS updated)!
< HTTP/2 200
< content-type: text/html; charset=utf-8
< server: Microsoft-IIS/8.5
< x-aspnet-version: 4.0.30319
< x-powered-by: ASP.NET
< access-control-allow-origin: *
< x-akamai-transformed: 9 - 0 pmb=mTOE,2
< expires: Mon, 13 Nov 2017 21:34:13 GMT
< cache-control: max-age=0, no-cache, no-store
< pragma: no-cache
< date: Mon, 13 Nov 2017 21:34:13 GMT

But when forcing to HTTP 1.0 or HTTP 1.1,

curl -v 'https://www.luisaviaroma.com/en-us/shop/home' \
     -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36' \
     --http1.0

it gives a different result:

> GET /en-us/shop/home HTTP/1.0
> Host: www.luisaviaroma.com
> Accept: */*
> User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Server: Apache
< ETag: "9c027fecce6719909433b8a37b2b403a:1493300815"
< Last-Modified: Thu, 27 Apr 2017 13:46:55 GMT
< Accept-Ranges: bytes
< Content-Length: 31186
< Content-Type: text/html
< Expires: Mon, 13 Nov 2017 21:36:19 GMT
< Cache-Control: max-age=0, no-cache, no-store
< Pragma: no-cache
< Date: Mon, 13 Nov 2017 21:36:19 GMT
< Connection: close

Using HTTP 1.0 or HTTP 1.1, we hit a different server serving a different page while using HTTP 2.0 it gives the expected page.

Using cURL which support HTTP 2.0 you will be able to download this page, for instance to save it under homepage.html:

curl 'https://www.luisaviaroma.com/en-us/shop/home' \
     -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36' \
     -o homepage.html


问:
MS Project: Loop through filtered tasks
From a MS-Project I'd like to copy to an excel sheet the task names that meet the criteria of a filter. Let's say filter dumb tasks.
I was trying something but it's not working:

```<code>Dim b As Task

For Each b In ActiveProject.TaskFilters("dumb tasks")
    'code to copy to excel
Next
</code>```

答:
To loop through only the tasks that are visible after applying a filter, select all tasks and loop through the collection of visible tasks.

```<code>Sub LoopThroughFilteredTasks()

    Dim CurrentTaskUID As Long
    CurrentTaskUID = ActiveCell.Task.UniqueID

    FilterApply "dumb tasks"
    SelectAll
    Dim FilteredTasks As Tasks
    Set FilteredTasks = ActiveSelection.Tasks
    Dim tsk As Task
    For Each tsk In FilteredTasks
        ' do something
    Next tsk
    FilterApply "&All Tasks"

    Application.Find "Unique ID", "equals", CurrentTaskUID

End Sub
</code>```

Note 1: While not necessary, users generally appreciate the active selection being restored at the end of the macro, thus the CurrentTaskUID lines.

Note 2: Since filters can be complex, it is preferable to use the actual filter rather than try to replicate it in code.

Title: MS Project: Loop through filtered tasks

Body:
From a MS-Project I'd like to copy to an excel sheet the task names that meet the criteria of a filter. Let's say filter dumb tasks.
I was trying something but it's not working:

Dim b As Task

For Each b In ActiveProject.TaskFilters("dumb tasks")
    'code to copy to excel
Next

Body:
To loop through only the tasks that are visible after applying a filter, select all tasks and loop through the collection of visible tasks.

Sub LoopThroughFilteredTasks()

    Dim CurrentTaskUID As Long
    CurrentTaskUID = ActiveCell.Task.UniqueID

    FilterApply "dumb tasks"
    SelectAll
    Dim FilteredTasks As Tasks
    Set FilteredTasks = ActiveSelection.Tasks
    Dim tsk As Task
    For Each tsk In FilteredTasks
        ' do something
    Next tsk
    FilterApply "&All Tasks"

    Application.Find "Unique ID", "equals", CurrentTaskUID

End Sub

Note 1: While not necessary, users generally appreciate the active selection being restored at the end of the macro, thus the CurrentTaskUID lines.

Note 2: Since filters can be complex, it is preferable to use the actual filter rather than try to replicate it in code.


问:
How to find if 3 numbers in a set of size N exactly sum up to M
I want to know how I can implement a better solution than O(N^3). Its similar to the knapsack and subset problems. In my question N<=8000, so i started computing sums of pairs of numbers and stored them in an array. Then I would binary search in the sorted set for each (M-sum[i]) value but the problem arises how will I keep track of the indices which summed up to sum[i]. I know I could declare extra space but my Sums array already has a size of 64 million, and hence I couldn't complete my O(N^2) solution. Please advice if I can do some optimization or if I need some totally different technique.</p>

答:
This appears to work for me...

```<code>#include <iostream>
#include <set>
#include <algorithm>
using namespace std;

int main(void)
{
  set<long long> keys;

  // By default this set is sorted
  set<short> N;
  N.insert(4);
  N.insert(8);
  N.insert(19);
  N.insert(5);
  N.insert(12);
  N.insert(35);
  N.insert(6);
  N.insert(1);

  typedef set<short>::iterator iterator;

  const short M = 18;

  for(iterator i(N.begin()); i != N.end() && *i < M; ++i)
  {
    short d1 = M - *i; // subtract the value at this location
    // if there is more to "consume"
    if (d1 > 0)
    {
      // ignore below i as we will have already scanned it...
      for(iterator j(i); j != N.end() && *j < M; ++j)
      {
        short d2 = d1 - *j; // again "consume" as much as we can
        // now the remainder must eixst in our set N
        if (N.find(d2) != N.end())
        {
          // means that the three numbers we've found, *i (from first loop), *j (from second loop) and d2 exist in our set of N
          // now to generate the unique combination, we need to generate some form of key for our keys set
          // here we take advantage of the fact that all the numbers fit into a short, we can construct such a key with a long long (8 bytes)

          // the 8 byte key is made up of 2 bytes for i, 2 bytes for j and 2 bytes for d2
          // and is formed in sorted order

          long long key = *i; // first index is easy
          // second index slightly trickier, if it's less than j, then this short must be "after" i
          if (*i < *j)
            key = (key << 16) | *j;
          else
            key |= (static_cast<int>(*j) << 16); // else it's before i

          // now the key is either: i | j, or j | i (where i & j are two bytes each, and the key is currently 4 bytes)

          // third index is a bugger, we have to scan the key in two byte chunks to insert our third short
          if ((key & 0xFFFF) < d2)
            key = (key << 16) | d2;  // simple, it's the largest of the three
          else if (((key >> 16) & 0xFFFF) < d2)
            key = (((key << 16) | (key & 0xFFFF)) & 0xFFFF0000FFFFLL) | (d2 << 16); // its less than j but greater i
          else
            key |= (static_cast<long long>(d2) << 32); // it's less than i

          // Now if this unique key already exists in the hash, this won't insert an entry for it
          keys.insert(key);
        }
        // else don't care...
      }
    }
  }
  // tells us how many unique combinations there are
  cout << "size: " << keys.size() << endl;
  // prints out the 6 bytes for representing the three numbers
  for(set<long long>::iterator it (keys.begin()), end(keys.end()); it != end; ++it)
     cout << hex << *it << endl;

  return 0;
}
</code>```

Okay, here is attempt two: this generates the output:

```<code>start: 19
size: 4
10005000c
400060008
500050008
600060006
</code>```

As you can see from there, the first "key" is the three shorts (in hex), 0x0001, 0x0005, 0x000C (which is 1, 5, 12 = 18), etc.

Okay, cleaned up the code some more, realised that the reverse iteration is pointless..

My Big O notation is not the best (never studied computer science), however I think the above is something like, O(N) for outer and O(NlogN) for inner, reason for log N is that std::set::find() is logarithmic - however if you replace this with a hashed set, the inner loop could be as good as O(N) - please someone correct me if this is crap...

Body:
This appears to work for me...

#include <iostream>
#include <set>
#include <algorithm>
using namespace std;

int main(void)
{
  set<long long> keys;

  // By default this set is sorted
  set<short> N;
  N.insert(4);
  N.insert(8);
  N.insert(19);
  N.insert(5);
  N.insert(12);
  N.insert(35);
  N.insert(6);
  N.insert(1);

  typedef set<short>::iterator iterator;

  const short M = 18;

  for(iterator i(N.begin()); i != N.end() && *i < M; ++i)
  {
    short d1 = M - *i; // subtract the value at this location
    // if there is more to "consume"
    if (d1 > 0)
    {
      // ignore below i as we will have already scanned it...
      for(iterator j(i); j != N.end() && *j < M; ++j)
      {
        short d2 = d1 - *j; // again "consume" as much as we can
        // now the remainder must eixst in our set N
        if (N.find(d2) != N.end())
        {
          // means that the three numbers we've found, *i (from first loop), *j (from second loop) and d2 exist in our set of N
          // now to generate the unique combination, we need to generate some form of key for our keys set
          // here we take advantage of the fact that all the numbers fit into a short, we can construct such a key with a long long (8 bytes)

          // the 8 byte key is made up of 2 bytes for i, 2 bytes for j and 2 bytes for d2
          // and is formed in sorted order

          long long key = *i; // first index is easy
          // second index slightly trickier, if it's less than j, then this short must be "after" i
          if (*i < *j)
            key = (key << 16) | *j;
          else
            key |= (static_cast<int>(*j) << 16); // else it's before i

          // now the key is either: i | j, or j | i (where i & j are two bytes each, and the key is currently 4 bytes)

          // third index is a bugger, we have to scan the key in two byte chunks to insert our third short
          if ((key & 0xFFFF) < d2)
            key = (key << 16) | d2;  // simple, it's the largest of the three
          else if (((key >> 16) & 0xFFFF) < d2)
            key = (((key << 16) | (key & 0xFFFF)) & 0xFFFF0000FFFFLL) | (d2 << 16); // its less than j but greater i
          else
            key |= (static_cast<long long>(d2) << 32); // it's less than i

          // Now if this unique key already exists in the hash, this won't insert an entry for it
          keys.insert(key);
        }
        // else don't care...
      }
    }
  }
  // tells us how many unique combinations there are
  cout << "size: " << keys.size() << endl;
  // prints out the 6 bytes for representing the three numbers
  for(set<long long>::iterator it (keys.begin()), end(keys.end()); it != end; ++it)
     cout << hex << *it << endl;

  return 0;
}

Okay, here is attempt two: this generates the output:

start: 19
size: 4
10005000c
400060008
500050008
600060006

As you can see from there, the first "key" is the three shorts (in hex), 0x0001, 0x0005, 0x000C (which is 1, 5, 12 = 18), etc.

Okay, cleaned up the code some more, realised that the reverse iteration is pointless..

My Big O notation is not the best (never studied computer science), however I think the above is something like, O(N) for outer and O(NlogN) for inner, reason for log N is that std::set::find() is logarithmic - however if you replace this with a hashed set, the inner loop could be as good as O(N) - please someone correct me if this is crap...