问:
java scp problem
I am having a situation here which I need to resolve. I have to upload particular elements of an xml file to upload it to a server, managed to do that, and I created a demo method to check if the file is being uploaded to the server or not.

My xml file has the structure,

```<code><config>
 <engine>
    <eid>1</eid>
    <sometextelement>text</sometextelement>
 </engine>

 <engine>
    <eid>2</eid>
    <sometextelement>text</sometextelement>
 </engine>

 <engine>
    <eid>3</eid>
    <sometextelement>text</sometextelement>
 </engine>

</config>
</code>```

and here is my servlet code:

```<code>protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("application/json");
        //response.setHeader("Cache-Control", "no-cache");
         PrintWriter out = response.getWriter();
         JSONObject obj = new JSONObject();
         String value = request.getParameter("value");
            String message = "";
            String update = "";
            Element element = null;
            Element root = null;
            XMLOutputter xmlOutputter = new XMLOutputter();
        try{
        doc = saxBuilder.build("E:/workbench j2ee/cPEP_UI/WebContent/engine.xml");

        }catch(Exception e){
            e.printStackTrace();
        }
        root = doc.getRootElement();
        List list = doc.getRootElement().getChildren();
        Iterator itr = list.iterator();
        while(itr.hasNext()){
             element = (Element)itr.next();
            System.out.println("Entered 1");
          File f = File.createTempFile("engine_",".xml");
           System.out.println(f);
            xmlOutputter.output(element, new FileWriter(f));

            putFile(f);
        }

         // xmlOutputter.output(doc, new FileWriter("E:/workbench j2ee/cPEP_UI/WebContent/engine.xml"));

        // System.out.println("hello from system");
        // out.println("hello");

    }

    public void putFile(File f){
         System.out.println("File String: "+f.toString());
         Connection Conn = null;
          try {
           Conn = new Connection("ftp.someserver.co.uk",22);
           ConnectionInfo info = Conn.connect();
           Conn.authenticateWithPassword("webmaster@someserver.co.uk", "mypass");
           SCPClient SCP = new SCPClient(Conn);
           SCP.put(f.toString(), "/public_html/webmaster", "0755");
           Conn.close();
          } catch (Exception e) {
           try {
            Conn.close();
           } catch (Exception e1) {}
    }
    }
</code>```

Now, From the above code I am getting file created for engine 1, engine 2 and engine 3, and thats what I wanted, but now I want it to upload to the server too. and the putFile code is not working at all.The port is also perfect. Whats wrong then?
any ideas?

Heres the error:

```<code>java.io.IOException: There was a problem while connecting to ftp.someserver.co.uk:22
    at ch.ethz.ssh2.Connection.connect(Connection.java:699)
    at ch.ethz.ssh2.Connection.connect(Connection.java:490)
    at Push_Individual_Engine.putFile(Push_Individual_Engine.java:106)
    at Push_Individual_Engine.doPost(Push_Individual_Engine.java:81)
    at Push_Individual_Engine.doGet(Push_Individual_Engine.java:47)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:662)
Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:529)
    at ch.ethz.ssh2.transport.TransportManager.establishConnection(TransportManager.java:340)
    at ch.ethz.ssh2.transport.TransportManager.initialize(TransportManager.java:448)
    at ch.ethz.ssh2.Connection.connect(Connection.java:643)
    ... 18 more
</code>```

答: As you mentioned this error usually occurs either if Ip/domain name or port is incorrect, did you try doing a telnet from the same box as your java program is running on? Could be a firewall issue if port and name are ok or a dns issue if your box cant resolve the domain correctly.</p>

Title: java scp problem

Body:
I am having a situation here which I need to resolve. I have to upload particular elements of an xml file to upload it to a server, managed to do that, and I created a demo method to check if the file is being uploaded to the server or not.

My xml file has the structure,

<config>
 <engine>
    <eid>1</eid>
    <sometextelement>text</sometextelement>
 </engine>

 <engine>
    <eid>2</eid>
    <sometextelement>text</sometextelement>
 </engine>

 <engine>
    <eid>3</eid>
    <sometextelement>text</sometextelement>
 </engine>

</config>

and here is my servlet code:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("application/json");
        //response.setHeader("Cache-Control", "no-cache");
         PrintWriter out = response.getWriter();
         JSONObject obj = new JSONObject();
         String value = request.getParameter("value");
            String message = "";
            String update = "";
            Element element = null;
            Element root = null;
            XMLOutputter xmlOutputter = new XMLOutputter();
        try{
        doc = saxBuilder.build("E:/workbench j2ee/cPEP_UI/WebContent/engine.xml");

        }catch(Exception e){
            e.printStackTrace();
        }
        root = doc.getRootElement();
        List list = doc.getRootElement().getChildren();
        Iterator itr = list.iterator();
        while(itr.hasNext()){
             element = (Element)itr.next();
            System.out.println("Entered 1");
          File f = File.createTempFile("engine_",".xml");
           System.out.println(f);
            xmlOutputter.output(element, new FileWriter(f));

            putFile(f);
        }

         // xmlOutputter.output(doc, new FileWriter("E:/workbench j2ee/cPEP_UI/WebContent/engine.xml"));

        // System.out.println("hello from system");
        // out.println("hello");

    }

    public void putFile(File f){
         System.out.println("File String: "+f.toString());
         Connection Conn = null;
          try {
           Conn = new Connection("ftp.someserver.co.uk",22);
           ConnectionInfo info = Conn.connect();
           Conn.authenticateWithPassword("webmaster@someserver.co.uk", "mypass");
           SCPClient SCP = new SCPClient(Conn);
           SCP.put(f.toString(), "/public_html/webmaster", "0755");
           Conn.close();
          } catch (Exception e) {
           try {
            Conn.close();
           } catch (Exception e1) {}
    }
    }

Now, From the above code I am getting file created for engine 1, engine 2 and engine 3, and thats what I wanted, but now I want it to upload to the server too. and the putFile code is not working at all.The port is also perfect. Whats wrong then?
any ideas?

Heres the error:

java.io.IOException: There was a problem while connecting to ftp.someserver.co.uk:22
    at ch.ethz.ssh2.Connection.connect(Connection.java:699)
    at ch.ethz.ssh2.Connection.connect(Connection.java:490)
    at Push_Individual_Engine.putFile(Push_Individual_Engine.java:106)
    at Push_Individual_Engine.doPost(Push_Individual_Engine.java:81)
    at Push_Individual_Engine.doGet(Push_Individual_Engine.java:47)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:662)
Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:529)
    at ch.ethz.ssh2.transport.TransportManager.establishConnection(TransportManager.java:340)
    at ch.ethz.ssh2.transport.TransportManager.initialize(TransportManager.java:448)
    at ch.ethz.ssh2.Connection.connect(Connection.java:643)
    ... 18 more


来源: stackexchange

问:
How to fail setup in Locust?
I'm doing a verification in my Locust setup and if that fails, I would like locust to exit immediately.

To do that, I'm raising an exception, but locust continues with the tests until time limit is reached.

I'd like for it to not even start the tests if setup fails. Is there a way to do that?

Locust code

```<code>class MyLocust(Locust):
    task_set = MyTaskSet

    def setup(self):
        if True:
            raise ValueError('Setup failed')
</code>```

stdout / stderr:

locust -f MyTest.py --no-web -c 10 -r 10 -t 5s

INFO/locust.main: Run time limit set to 5 seconds
INFO/locust.main: Starting Locust 0.11.0
INFO/locust.runners: Hatching and swarming 10 clients at the rate 10 clients/s...
    Name                                                          # reqs      # fails     Avg     Min     Max  |  Median   req/s
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
    Total                                                              0     0(0.00%)                                       0.00

ERROR/stderr: Traceback (most recent call last):
ERROR/stderr:
ERROR/stderr: File "src/gevent/greenlet.py", line 766, in gevent._greenlet.Greenlet.run
ERROR/stderr:
ERROR/stderr: File "/venv_37_1/lib/python3.7/site-packages/locust/runners.py", line 114, in start_locust
    locust().run(runner=self)
ERROR/stderr:
ERROR/stderr: File "/venv_37_1/lib/python3.7/site-packages/locust/core.py", line 192, in __init__
    super(HttpLocust, self).__init__()
ERROR/stderr:
ERROR/stderr: File "/venv_37_1/lib/python3.7/site-packages/locust/core.py", line 143, in __init__
    self.setup()
ERROR/stderr:
ERROR/stderr: File "/MyTest.py", line 220, in setup
    raise ValueError('Setup failed')
ERROR/stderr:
ERROR/stderr: ValueError: Setup failed
ERROR/stderr:
ERROR/stderr: 2019-09-25T21:43:39Z
ERROR/stderr:
ERROR/stderr: <Greenlet at 0x12c8c2950: start_locust(<class 'MyTest.LoadTest'>)> failed with ValueError
INFO/locust.runners: All locusts hatched: LoadTest: 10
    Name                                                          # reqs      # fails     Avg     Min     Max  |  Median   req/s
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
    Total                                                              0     0(0.00%)                                       0.00

    Name                                                          # reqs      # fails     Avg     Min     Max  |  Median   req/s
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
    Total                                                              0     0(0.00%)                                       0.00

INFO/locust.main: Time limit reached. Stopping Locust.
INFO/locust.main: Shutting down (exit code 0), bye.
INFO/locust.main: Cleaning up runner...
INFO/locust.main: Running teardowns...
```

As you can see from ^ only exits when time limit is reached, even though setup failed.

答:
You could always use quit() to quit Locust all together. Another option would be to use raise StopLocust():

```<code>class MyLocust(Locust):
    task_set = MyTaskSet

    def setup(self):
        if True:
            raise StopLocust()
</code>```

Also, check this out Stopping a locust

ContentLicense: CC BY-SA 4.0

Title: How to fail setup in Locust?

Body:
I'm doing a verification in my Locust setup and if that fails, I would like locust to exit immediately.

To do that, I'm raising an exception, but locust continues with the tests until time limit is reached.

I'd like for it to not even start the tests if setup fails. Is there a way to do that?

Locust code

class MyLocust(Locust):
    task_set = MyTaskSet

    def setup(self):
        if True:
            raise ValueError('Setup failed')

stdout / stderr:

locust -f MyTest.py --no-web -c 10 -r 10 -t 5s

INFO/locust.main: Run time limit set to 5 seconds
INFO/locust.main: Starting Locust 0.11.0
INFO/locust.runners: Hatching and swarming 10 clients at the rate 10 clients/s...
    Name                                                          # reqs      # fails     Avg     Min     Max  |  Median   req/s
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
    Total                                                              0     0(0.00%)                                       0.00

ERROR/stderr: Traceback (most recent call last):
ERROR/stderr:
ERROR/stderr: File "src/gevent/greenlet.py", line 766, in gevent._greenlet.Greenlet.run
ERROR/stderr:
ERROR/stderr: File "/venv_37_1/lib/python3.7/site-packages/locust/runners.py", line 114, in start_locust
    locust().run(runner=self)
ERROR/stderr:
ERROR/stderr: File "/venv_37_1/lib/python3.7/site-packages/locust/core.py", line 192, in __init__
    super(HttpLocust, self).__init__()
ERROR/stderr:
ERROR/stderr: File "/venv_37_1/lib/python3.7/site-packages/locust/core.py", line 143, in __init__
    self.setup()
ERROR/stderr:
ERROR/stderr: File "/MyTest.py", line 220, in setup
    raise ValueError('Setup failed')
ERROR/stderr:
ERROR/stderr: ValueError: Setup failed
ERROR/stderr:
ERROR/stderr: 2019-09-25T21:43:39Z
ERROR/stderr:
ERROR/stderr: <Greenlet at 0x12c8c2950: start_locust(<class 'MyTest.LoadTest'>)> failed with ValueError
INFO/locust.runners: All locusts hatched: LoadTest: 10
    Name                                                          # reqs      # fails     Avg     Min     Max  |  Median   req/s
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
    Total                                                              0     0(0.00%)                                       0.00

    Name                                                          # reqs      # fails     Avg     Min     Max  |  Median   req/s
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
    Total                                                              0     0(0.00%)                                       0.00

INFO/locust.main: Time limit reached. Stopping Locust.
INFO/locust.main: Shutting down (exit code 0), bye.
INFO/locust.main: Cleaning up runner...
INFO/locust.main: Running teardowns...

As you can see from ^ only exits when time limit is reached, even though setup failed.

Body:
You could always use quit() to quit Locust all together. Another option would be to use raise StopLocust():

class MyLocust(Locust):
    task_set = MyTaskSet

    def setup(self):
        if True:
            raise StopLocust()

Also, check this out Stopping a locust


问:
Why wraping the useContext with useRef does not give any warning to add it as dependency while using it inside the useEffect hook?
When I was using the useContext inside the useEffect it was giving me an warning saying it has to be added as a dependency.
But when I wrapped it inside a useRef it is not giving any warning.

Before - when it was giving warning.

```<code>const myContext = useContext(MyContext);
....
useEffect(() => {
    //Some Logic
    myContext.setSprinnerVisibility(true);
  }, []);
</code>```

After - when it was not giving any warning

```<code>const myContextRef = useRef(useContext(MyContext));
....
useEffect(() => {
    //Some Logic
    myContextRef.current.setSprinnerVisibility(true);
  }, []);
</code>```

答: useRef initializes with whatever value is found in the parentheses. No dependency check needed since later changes won't update the useRef. On the other hand, useEffect reacts to the dependency changes. Any variables that can change need to be recorded in the dependency array. myContextRef object reference doesn't change but the values within it may change.

Body:
When I was using the useContext inside the useEffect it was giving me an warning saying it has to be added as a dependency.
But when I wrapped it inside a useRef it is not giving any warning.

Before - when it was giving warning.

const myContext = useContext(MyContext);
....
useEffect(() => {
    //Some Logic
    myContext.setSprinnerVisibility(true);
  }, []);

After - when it was not giving any warning

const myContextRef = useRef(useContext(MyContext));
....
useEffect(() => {
    //Some Logic
    myContextRef.current.setSprinnerVisibility(true);
  }, []);


问:
Swift how to get response.statuscode in swiftui view
I am trying insert into db use post method in swift
and i can not get the response.statusCode of post method in swiftui view
how can i fix it.
the variable self.resp should be 201 in view when I insert successfully, but
it was 0.

import SwiftUI

struct ContentView: View {
  @State var resp:Int  = 0
    var body: some View {
        VStack{
        Text("Hello, World!")
        Button(action: {
            self.resp = postAdd()
            print("view\(self.resp)")
        }) {
            Text(/*@START_MENU_TOKEN@*/"Button"/*@END_MENU_TOKEN@*/)

                .background(self.resp == 201 ? Color.green : Color.gray)
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
func postAdd() ->Int{
            let url = URL(string: "http://localhost:3000/user")
            var request = URLRequest(url: url!)
    var resp = 0
                       request.httpMethod = "POST"
                        let urlstr = "id=5&name=aaa"

            request.httpBody = urlstr.data(using: .utf8)!
            let session = URLSession.shared
            session.dataTask(with: request) { (data, response, error) in
                if error == nil, let data = data, let response = response as? HTTPURLResponse {
                                   print("Content-Type: \(response.allHeaderFields["Content-Type"] ?? "")")
                                      print("statusCode: \(response.statusCode)")
                    resp = response.statusCode
                    print(String(data: data, encoding: .utf8) ?? "")
                }
            }.resume()
    return resp
        }```

答:
try this:

as i wrote in the comment - you have to know which calls are async and which are sync. I hope you know what sync and async calls are - if not, please google for it. if yes: the data task call is async and so it returns directly the resp = 0 value. After some time when the urlrequest is ready, it continuous in this line : "{ (data, response, error) in", but here it cannot return a value anymore because the method already returned a value. So with the completion pattern you can be sure you will get called when the async call is ready.

```<code>struct ContentView: View {
    @State var resp:Int  = 0
    var body: some View {
        VStack{
            Text("Hello, World!")
            Button(action: {
                postAdd() { response in
                    self.resp = response

                    print("view\(self.resp)")
                }
            }) {
                Text(/*@START_MENU_TOKEN@*/"Button"/*@END_MENU_TOKEN@*/)
                    .background(self.resp == 201 ? Color.green : Color.gray)
            }
        }
    }
}

func postAdd(completion:@escaping(Int)->()) {
    let url = URL(string: "http://localhost:3000/user")
    var request = URLRequest(url: url!)
    request.httpMethod = "POST"
    let urlstr = "id=5&name=aaa"

    request.httpBody = urlstr.data(using: .utf8)!
    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if error == nil, let data = data, let response = response as? HTTPURLResponse {
            print("Content-Type: \(response.allHeaderFields["Content-Type"] ?? "")")
            print("statusCode: \(response.statusCode)")
            completion(response.statusCode)
            print(String(data: data, encoding: .utf8) ?? "")
        } else {
            completion(404)
        }
    }.resume()

}
</code>```

Body:
try this:

as i wrote in the comment - you have to know which calls are async and which are sync. I hope you know what sync and async calls are - if not, please google for it. if yes: the data task call is async and so it returns directly the resp = 0 value. After some time when the urlrequest is ready, it continuous in this line : "{ (data, response, error) in", but here it cannot return a value anymore because the method already returned a value. So with the completion pattern you can be sure you will get called when the async call is ready.

struct ContentView: View {
    @State var resp:Int  = 0
    var body: some View {
        VStack{
            Text("Hello, World!")
            Button(action: {
                postAdd() { response in
                    self.resp = response

                    print("view\(self.resp)")
                }
            }) {
                Text(/*@START_MENU_TOKEN@*/"Button"/*@END_MENU_TOKEN@*/)
                    .background(self.resp == 201 ? Color.green : Color.gray)
            }
        }
    }
}

func postAdd(completion:@escaping(Int)->()) {
    let url = URL(string: "http://localhost:3000/user")
    var request = URLRequest(url: url!)
    request.httpMethod = "POST"
    let urlstr = "id=5&name=aaa"

    request.httpBody = urlstr.data(using: .utf8)!
    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if error == nil, let data = data, let response = response as? HTTPURLResponse {
            print("Content-Type: \(response.allHeaderFields["Content-Type"] ?? "")")
            print("statusCode: \(response.statusCode)")
            completion(response.statusCode)
            print(String(data: data, encoding: .utf8) ?? "")
        } else {
            completion(404)
        }
    }.resume()

}


问:
Pandas how to apply multiple functions to dataframe
Is there a way to apply a list of functions to each column in a DataFrame like the DataFrameGroupBy.agg function does?  I found an ugly way to do it like this:</p>

```<code>df=pd.DataFrame(dict(one=np.random.uniform(0,10,100), two=np.random.uniform(0,10,100)))
df.groupby(np.ones(len(df))).agg(['mean','std'])

        one                 two
       mean       std      mean       std
1  4.802849  2.729528  5.487576  2.890371
</code>```

答:
I tried to apply three functions into a column and it works</p>

```<code>#removing new line character
rem_newline = lambda x : re.sub('\n',' ',x).strip()

#character lower and removing spaces
lower_strip = lambda x : x.lower().strip()

df = df['users_name'].apply(lower_strip).apply(rem_newline).str.split('(',n=1,expand=True)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there a way to apply a list of functions to each column in a DataFrame like the DataFrameGroupBy.agg function does?  I found an ugly way to do it like this:

df=pd.DataFrame(dict(one=np.random.uniform(0,10,100), two=np.random.uniform(0,10,100)))
df.groupby(np.ones(len(df))).agg(['mean','std'])

        one                 two
       mean       std      mean       std
1  4.802849  2.729528  5.487576  2.890371

Body:
I tried to apply three functions into a column and it works

#removing new line character
rem_newline = lambda x : re.sub('\n',' ',x).strip()

#character lower and removing spaces
lower_strip = lambda x : x.lower().strip()

df = df['users_name'].apply(lower_strip).apply(rem_newline).str.split('(',n=1,expand=True)


问:
Want to show the data in a dropdown every item as an option
```<code>class DropDown extends Component {
    constructor(){
        super()
        this.state = {
            item: [],
            isLoaded: true,
        }
    }
// here I have fetch the data from api
    componentDidMount() {
        fetch('link')
            .then((response) => response.json())
            .then((responseJson) => {
                this.setState({
                    isLoaded: false,
                    item: responseJson.drawingInfo.renderer.uniqueValueInfos,

                })

            })

    }

    render() {
        const {item} = this.state;

// here I have map the array of data. And now wanna show it in a dropdown where every item is an option an we can select them

        const itemDropdown = item.map((division, index)=> (
            <div key={index}>

                    <option>{division.value}</option>

            </div>

        ))

        return (
{/*here I tried to show the data as dropdown option...but I got one option where all the data resides*/}
            <div>
                <ReactBootStrap.DropdownButton variant = 'transparent' id = "dropdown-button" title="Dropdown button" >
                    < ReactBootStrap.Dropdown.Item > {itemDropdown} </ReactBootStrap.Dropdown.Item>

                </ReactBootStrap.DropdownButton>

            </div>
        );

    }
}
</code>```

答:
react bootstrap dropdown makes working with react & bootstrap a bit easier:</p>

```<code>render (){
 const {item} = this.state;
  return (
    <DropdownButton title="Dropdown">
    { item.map((division, index)=> (
          <MenuItem>{division}</MenuItem>
    )
    </DropdownButton>
  );
}
</code>```

Body:
class DropDown extends Component {
    constructor(){
        super()
        this.state = {
            item: [],
            isLoaded: true,
        }
    }
// here I have fetch the data from api
    componentDidMount() {
        fetch('link')
            .then((response) => response.json())
            .then((responseJson) => {
                this.setState({
                    isLoaded: false,
                    item: responseJson.drawingInfo.renderer.uniqueValueInfos,

                })

            })

    }

    render() {
        const {item} = this.state;

// here I have map the array of data. And now wanna show it in a dropdown where every item is an option an we can select them

        const itemDropdown = item.map((division, index)=> (

                    <option>{division.value}</option>

        ))

        return (
{/*here I tried to show the data as dropdown option...but I got one option where all the data resides*/}

                <ReactBootStrap.DropdownButton variant = 'transparent' id = "dropdown-button" title="Dropdown button" >
                    < ReactBootStrap.Dropdown.Item > {itemDropdown} </ReactBootStrap.Dropdown.Item>

                </ReactBootStrap.DropdownButton>

        );

    }
}

Body:
react bootstrap dropdown makes working with react & bootstrap a bit easier:

render (){
 const {item} = this.state;
  return (
    <DropdownButton title="Dropdown">
    { item.map((division, index)=> (
          <MenuItem>{division}</MenuItem>
    )
    </DropdownButton>
  );
}


问:
java.lang.illegalargumentexception no query defined for that name [...]
I have a native query in plsql like this;

```<code>create or replace package body DBPK_Monitoring is
  PROCEDURE monitoring_Search(cur OUT SYS_REFCURSOR,) is
    query       VARCHAR(30000);
    whereClause VARCHAR(10000);

  BEGIN
    whereClause := whereClause || '  and   ( cnt.contract_status!=7)';

    query := ' select itemTitle as "itemTitle", numberOfRow as "numberOfRow" ,
               orderNumber as "orderNumber",createDate as "createDate",
               priorityNumber as  "priorityNumber"
        from buy_buy_order bbo
       inner join buy_buy_order_item bbi
          on bbi.buy_order_id = bbo.id
        left outer join core_User_Role shoUserRole
          on shoUserRole.id = bbi.buy_Expert_Id

         ' || whereClause || ' order by ' || orderBy ||
             ') e  WHERE e.rowNO>  ' || lower_Bound || ' and e.rowNO<=' ||
             upper_Bound;
    OPEN cur FOR query
  end monitoring_Search;

end DBPK_Monitoring;
</code>```

I use of this query in repository with hql like this :

```<code> Session session = getSession();
        Query query = session.getNamedQuery("monitoring_Search").setResultTransformer(Transformers.aliasToBean(MonitoringDto.class));
        int firstResultIndex = searchOption.getPageNumber() * searchOption.getPageSize();
        query.setInteger("lower_Bound", firstResultIndex);
        query.setParameter("upper_Bound", firstResultIndex + searchOption.getPageSize());
        query.setString("orderBy", searchOption.getOrder());
        query.setParameter("buyOrderNumber", buyOrderNumber);
        List<MonitoringDto> list = query.list();
        int count = (list.size() > 0L) ? list.get(0).getNumberOfRow() : 0;
        return new QueryResult<MonitoringDto>(searchOption.getPageNumber(), count, searchOption.getPageSize(), list);
</code>```

When I run program, I get this error:

java.lang.illegalargumentexception no query defined for that name
  [monitoring_Search]

How can I fix this?

答:
you have to define monitoring_search as a Hibernate named query , you can see the detail about this in this link : https://www.baeldung.com/hibernate-named-query
have a nice day and kiss people around you ;)</p>

Body:
I have a native query in plsql like this;

create or replace package body DBPK_Monitoring is
  PROCEDURE monitoring_Search(cur OUT SYS_REFCURSOR,) is
    query       VARCHAR(30000);
    whereClause VARCHAR(10000);

  BEGIN
    whereClause := whereClause || '  and   ( cnt.contract_status!=7)';

    query := ' select itemTitle as "itemTitle", numberOfRow as "numberOfRow" ,
               orderNumber as "orderNumber",createDate as "createDate",
               priorityNumber as  "priorityNumber"
        from buy_buy_order bbo
       inner join buy_buy_order_item bbi
          on bbi.buy_order_id = bbo.id
        left outer join core_User_Role shoUserRole
          on shoUserRole.id = bbi.buy_Expert_Id

         ' || whereClause || ' order by ' || orderBy ||
             ') e  WHERE e.rowNO>  ' || lower_Bound || ' and e.rowNO<=' ||
             upper_Bound;
    OPEN cur FOR query
  end monitoring_Search;

end DBPK_Monitoring;

I use of this query in repository with hql like this :

 Session session = getSession();
        Query query = session.getNamedQuery("monitoring_Search").setResultTransformer(Transformers.aliasToBean(MonitoringDto.class));
        int firstResultIndex = searchOption.getPageNumber() * searchOption.getPageSize();
        query.setInteger("lower_Bound", firstResultIndex);
        query.setParameter("upper_Bound", firstResultIndex + searchOption.getPageSize());
        query.setString("orderBy", searchOption.getOrder());
        query.setParameter("buyOrderNumber", buyOrderNumber);
        List<MonitoringDto> list = query.list();
        int count = (list.size() > 0L) ? list.get(0).getNumberOfRow() : 0;
        return new QueryResult<MonitoringDto>(searchOption.getPageNumber(), count, searchOption.getPageSize(), list);

When I run program, I get this error:

java.lang.illegalargumentexception no query defined for that name
  [monitoring_Search]

How can I fix this?


问:
How to fix the issue:Your PHP installation appears to be missing the MySQL extension
Environment:os and apache and php and mariadb version.

```<code>uname -a
Linux MiWiFi-R3-srv 4.9.0-11-amd64 #1 SMP Debian 4.9.189-3+deb9u2 (2019-11-11) x86_64 GNU/Linux

sudo apachectl -v
Server version: Apache/2.4.25 (Debian)
Server built:   2019-10-13T15:43:54

php -v
PHP 7.0.33-0+deb9u6 (cli) (built: Oct 24 2019 18:50:20) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.33-0+deb9u6, Copyright (c) 1999-2017, by Zend Technologies
</code>```

Login mariadb with password and input status:

```<code>Server:         MariaDB
Server version:     10.1.41-MariaDB-0+deb9u1 Debian 9.9
</code>```

Check php-mysql:

```<code>sudo dpkg -l php-mysql
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name           Version      Architecture Description
+++-==============-============-============-=================================
ii  php-mysql      1:7.0+49     all          MySQL module for PHP [default]
</code>```

Get the mysql.so library:

```<code>sudo find  /  -name  "*mysql.so"
/usr/lib/php/20151012/pdo_mysql.so
</code>```

Chekc all modules which contain mysql:

```<code>php -m |grep  mysql
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php/20151012/php_pdo_mysql.so' - /usr/lib/php/20151012/php_pdo_mysql.so: cannot open shared object file: No such file or directory in Unknown on line 0
mysqli
mysqlnd
pdo_mysql

sudo vim  /etc/php/7.0/fpm/php.ini
</code>```

Rewrite

```<code>; ... or under UNIX:
;
;extension=mysql.so
</code>```

as

```<code>extension=mysqli.so
</code>```

or

```<code>extension=mysqlnd.so
</code>```

or

```<code>extension=pdo_mysql.so
</code>```

Restart apache2 and mariadb database,the issue remains ,none of the three format can work,how to fix then?

答:
Remove php and related packages.

```<code>sudo apt-get autoremove php7*
sudo find /etc -name "*php*" |xargs  rm -rf
sudo apt purge `dpkg -l | grep php| awk '{print $2}' |tr "\n" " "`
</code>```

Check.

```<code>dpkg -l | grep php7.0
</code>```

Install.

```<code>sudo apt-get install php php-mysql
</code>```

At last my issue solved.

Body:
Environment:os and apache and php and mariadb version.

uname -a
Linux MiWiFi-R3-srv 4.9.0-11-amd64 #1 SMP Debian 4.9.189-3+deb9u2 (2019-11-11) x86_64 GNU/Linux

sudo apachectl -v
Server version: Apache/2.4.25 (Debian)
Server built:   2019-10-13T15:43:54

php -v
PHP 7.0.33-0+deb9u6 (cli) (built: Oct 24 2019 18:50:20) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.33-0+deb9u6, Copyright (c) 1999-2017, by Zend Technologies

Login mariadb with password and input status:

Server:         MariaDB
Server version:     10.1.41-MariaDB-0+deb9u1 Debian 9.9

Check php-mysql:

sudo dpkg -l php-mysql
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name           Version      Architecture Description
+++-==============-============-============-=================================
ii  php-mysql      1:7.0+49     all          MySQL module for PHP [default]

Get the mysql.so library:

sudo find  /  -name  "*mysql.so"
/usr/lib/php/20151012/pdo_mysql.so

Chekc all modules which contain mysql:

php -m |grep  mysql
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php/20151012/php_pdo_mysql.so' - /usr/lib/php/20151012/php_pdo_mysql.so: cannot open shared object file: No such file or directory in Unknown on line 0
mysqli
mysqlnd
pdo_mysql

sudo vim  /etc/php/7.0/fpm/php.ini

Rewrite

; ... or under UNIX:
;
;extension=mysql.so

as

extension=mysqli.so

or

extension=mysqlnd.so

or

extension=pdo_mysql.so

Restart apache2 and mariadb database,the issue remains ,none of the three format can work,how to fix then?

Body:
Remove php and related packages.

sudo apt-get autoremove php7*
sudo find /etc -name "*php*" |xargs  rm -rf
sudo apt purge `dpkg -l | grep php| awk '{print $2}' |tr "\n" " "`

Check.

dpkg -l | grep php7.0

Install.

sudo apt-get install php php-mysql

At last my issue solved.


问:
A dataframe of n column given and I want to count frequency of a particular number from each column
'''
dataframe is like

1  2  4  ....n

0  2  0  ....n

1  0  4  ....n

0  0  4  ....n

now i want to count 1 from column 1, count 2 from column 2,count 4 from column 3 and so on.

but i also want to count few values by adding columns like

1+2  ,        1+4     ,    2+4   ,   1+2+4

0+2  ,        0+0     ,    2+0   ,   0+2+0

1+0  ,         1+4    ,     0+4  ,    1+0+4

0+0  ,         0+4    ,     0+4  ,    0+0+4

Count 3      count 5   count 6     count 7  from above columns respectively.

count 1 from column a, 2 from column b, 3 from column a+b, 4 from column c, 5 from column a+c, 6 from column b+c, 7 from column a+b+c. like this.

Store all these values/number in list, array or dataframe like

Values/Number , Title , Frequency

1 , a , 2

2 , b , 2

3 , a+b , 1

4 , c , 3

5 , a+c , 2

6 , b+c , 1

7 , a+b+c , 1

'''

答:
Use previous solution first:

```<code>from itertools import chain, combinations
#https://stackoverflow.com/a/5898031
comb = chain(*map(lambda x: combinations(df.columns, x), range(2, len(df.columns)+1)))

cols = df.columns
for c in comb:
    df[f'{"+".join(c)}'] = df.loc[:, c].sum(axis=1)
print (df)
   a  b  c  a+b  a+c  b+c  a+b+c
0  1  2  4    3    5    6      7
1  0  2  0    2    0    2      2
2  1  0  4    1    5    4      5
3  0  0  4    0    4    4      4

df1 = df.apply(pd.value_counts)
print (df1)
     a    b    c  a+b  a+c  b+c  a+b+c
0  2.0  2.0  1.0  1.0  1.0  NaN    NaN
1  2.0  NaN  NaN  1.0  NaN  NaN    NaN
2  NaN  2.0  NaN  1.0  NaN  1.0    1.0
3  NaN  NaN  NaN  1.0  NaN  NaN    NaN
4  NaN  NaN  3.0  NaN  1.0  2.0    1.0
5  NaN  NaN  NaN  NaN  2.0  NaN    1.0
6  NaN  NaN  NaN  NaN  NaN  1.0    NaN
7  NaN  NaN  NaN  NaN  NaN  NaN    1.0
</code>```

And then DataFrame.agg with DataFrame.idxmax and DataFrame.max for new DataFrame, DataFrame.reset_index for column from index and last rename columns:

```<code>c = {'index':'Values/Number','idxmax':'Title','max':'Frequency'}
df2 = df1.agg(['idxmax','max'], axis=1).reset_index().rename(columns=c)
print (df2)
   Values/Number  Title Frequency
0              0      a         2
1              1      a         2
2              2      b         2
3              3    a+b         1
4              4      c         3
5              5    a+c         2
6              6    b+c         1
7              7  a+b+c         1
</code>```

Body:
Use previous solution first:

from itertools import chain, combinations
#https://stackoverflow.com/a/5898031
comb = chain(*map(lambda x: combinations(df.columns, x), range(2, len(df.columns)+1)))

cols = df.columns
for c in comb:
    df[f'{"+".join(c)}'] = df.loc[:, c].sum(axis=1)
print (df)
   a  b  c  a+b  a+c  b+c  a+b+c
0  1  2  4    3    5    6      7
1  0  2  0    2    0    2      2
2  1  0  4    1    5    4      5
3  0  0  4    0    4    4      4

df1 = df.apply(pd.value_counts)
print (df1)
     a    b    c  a+b  a+c  b+c  a+b+c
0  2.0  2.0  1.0  1.0  1.0  NaN    NaN
1  2.0  NaN  NaN  1.0  NaN  NaN    NaN
2  NaN  2.0  NaN  1.0  NaN  1.0    1.0
3  NaN  NaN  NaN  1.0  NaN  NaN    NaN
4  NaN  NaN  3.0  NaN  1.0  2.0    1.0
5  NaN  NaN  NaN  NaN  2.0  NaN    1.0
6  NaN  NaN  NaN  NaN  NaN  1.0    NaN
7  NaN  NaN  NaN  NaN  NaN  NaN    1.0

And then DataFrame.agg with DataFrame.idxmax and DataFrame.max for new DataFrame, DataFrame.reset_index for column from index and last rename columns:

c = {'index':'Values/Number','idxmax':'Title','max':'Frequency'}
df2 = df1.agg(['idxmax','max'], axis=1).reset_index().rename(columns=c)
print (df2)
   Values/Number  Title Frequency
0              0      a         2
1              1      a         2
2              2      b         2
3              3    a+b         1
4              4      c         3
5              5    a+c         2
6              6    b+c         1
7              7  a+b+c         1


问:
Can I use React Bootstrap with Next.js?
Does anyone know if you can use react-bootstrap with Next.js? I am using the latest versions of both, I can provide code at this point, but right now my app is not throwing any errors, it is just not registering any of my react-bootstrap components. Maybe there is some trick that I have not been able to find on the internet? I can provide code or file structure if that helps. Thanks in advance!

next.config.js

```<code>const withCSS = require('@zeit/next-css')

module.exports = withCSS({
    /* my next config */
})
</code>```

pages/index.js

```<code>import Badge from 'react-bootstrap/Badge';
import "../public/css/bootstrap.css";
const Index = () => (
    <div>
        <p className='display-4'>Hello</p>
        <Badge>Heading</Badge>
    </div>
)

export default Index;
</code>```

package.json

```<code>{
  "name": "vacation-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@zeit/next-css": "^1.0.1",
    "next": "^9.1.1",
    "react": "^16.10.2",
    "react-bootstrap": "^1.0.0-beta.14",
    "react-dom": "^16.10.2"
  }
}
</code>```

答:
Yup, you can use it, by providing CDN link inside your  tag in pages/index.js.

import Head from 'next/head';
import Badge from 'react-bootstrap/Badge';
import "../public/css/bootstrap.css";
const Index = () => (

      <link
        rel="stylesheet"
        href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
        crossorigin="anonymous"
      />

Hello

        <Badge>Heading</Badge>

)

export default Index;```

Hope it works!!!

Title: Can I use React Bootstrap with Next.js?

Body:
Does anyone know if you can use react-bootstrap with Next.js? I am using the latest versions of both, I can provide code at this point, but right now my app is not throwing any errors, it is just not registering any of my react-bootstrap components. Maybe there is some trick that I have not been able to find on the internet? I can provide code or file structure if that helps. Thanks in advance!

next.config.js

const withCSS = require('@zeit/next-css')

module.exports = withCSS({
    /* my next config */
})

pages/index.js

import Badge from 'react-bootstrap/Badge';
import "../public/css/bootstrap.css";
const Index = () => (

Hello

        <Badge>Heading</Badge>

)

export default Index;

package.json

{
  "name": "vacation-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@zeit/next-css": "^1.0.1",
    "next": "^9.1.1",
    "react": "^16.10.2",
    "react-bootstrap": "^1.0.0-beta.14",
    "react-dom": "^16.10.2"
  }
}

Body:
Yup, you can use it, by providing CDN link inside your <head> tag in pages/index.js.

import Head from 'next/head';
import Badge from 'react-bootstrap/Badge';
import "../public/css/bootstrap.css";
const Index = () => (
    <Head>
      <link
        rel="stylesheet"
        href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
        crossorigin="anonymous"
      />
    </Head>
    <div>
        <p className='display-4'>Hello</p>
        <Badge>Heading</Badge>
    </div>
)

export default Index;

Hope it works!!!


问:
Bring UIButton above UIScrollview
I want to make a floating button inside UIViewController using uiscrollview. I try using xib before and it work, but some functionality not working when I select item. but when I use ui code it work selecting, the problem is I try to bring the button above uiscrollview like I did in xib file. but it didn't show up, please help. this is my code setup. let me know if you need to see the other uicode. thank you</p>

```<code>    private func setupScrollView() {
        view.addSubview(scrollView)
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        scrollView.contentSize.height = 2000

        NSLayoutConstraint.activate([
            scrollView.topAnchor.constraint(equalTo: view.topAnchor),
            scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
        ])
    }

    private func setupAbsenceBtn() {
        view.insertSubview(startAbsenceBtn, aboveSubview: scrollView)

        NSLayoutConstraint.activate([
            startAbsenceBtn.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            startAbsenceBtn.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            startAbsenceBtn.heightAnchor.constraint(equalToConstant: 55),
            startAbsenceBtn.widthAnchor.constraint(equalToConstant: 307)
        ])

    }
</code>```

答:
startAbsenceBtn.translatesAutoresizingMaskIntoConstraints = false
is missing.

Title: Bring UIButton above UIScrollview

Body:
I want to make a floating button inside UIViewController using uiscrollview. I try using xib before and it work, but some functionality not working when I select item. but when I use ui code it work selecting, the problem is I try to bring the button above uiscrollview like I did in xib file. but it didn't show up, please help. this is my code setup. let me know if you need to see the other uicode. thank you

    private func setupScrollView() {
        view.addSubview(scrollView)
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        scrollView.contentSize.height = 2000

        NSLayoutConstraint.activate([
            scrollView.topAnchor.constraint(equalTo: view.topAnchor),
            scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
        ])
    }

    private func setupAbsenceBtn() {
        view.insertSubview(startAbsenceBtn, aboveSubview: scrollView)

        NSLayoutConstraint.activate([
            startAbsenceBtn.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            startAbsenceBtn.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            startAbsenceBtn.heightAnchor.constraint(equalToConstant: 55),
            startAbsenceBtn.widthAnchor.constraint(equalToConstant: 307)
        ])

    }


问:
Typescript: What is the correct type for a Timeout?
What is the correct type when dealing with timers? I have tried Timeout and number

```<code>  let debounceResize: any;
//                     ^ What should this be?
  window.addEventListener('resize', () => {
    clearTimeout(debounceResize);
    debounceResize = setTimeout(calcCanvasSize, 500);
  });
</code>```

答:
In a Web Browser app, setTimeout returns a number.

This setup requires the DOM library (or equivalent).

In a NodeJS app, setTimeout returns a NodeJS.Timeout.

```<code>npm install @types/node --save-dev`.
</code>```

Body:
What is the correct type when dealing with timers? I have tried Timeout and number

  let debounceResize: any;
//                     ^ What should this be?
  window.addEventListener('resize', () => {
    clearTimeout(debounceResize);
    debounceResize = setTimeout(calcCanvasSize, 500);
  });

Body:
In a Web Browser app, setTimeout returns a number.

This setup requires the DOM library (or equivalent).

In a NodeJS app, setTimeout returns a NodeJS.Timeout.

npm install @types/node --save-dev`.


问:
GitHub Actions CI Conditional Regex
I'm trying to move my CI workflow from CircleCI to GitHub Actions. The last major struggle I'm facing is with deployment.

Currently my workflow is such that when I push a tag to my GitHub repo, it will run the tests, then run the deployment. Only thing is CircleCI filters tags to only run the job if the tag matches the regex: /v[0-9]+(\.[0-9]+)*/.

How can I check to ensure the tag I pushed matches the regex pattern above before running the deployment?

I currently have the following GitHub Actions yml file:

```<code>name: CI
on: [create]

jobs:
  # ...

  deploy:
    runs-on: ubuntu-latest
    if: github.event.ref_type == 'tag' && github.event.ref == SOMETHING HERE
    steps:
      - uses: actions/checkout@v1
      # ...
</code>```

Under the if block, I need to change github.event.ref == SOMETHING HERE to be something else. I have looked in the Contexts and expression syntax for GitHub Actions documentation page. But due to how flexible and powerful GitHub Actions is, it seems like there should be a method or way to do this, or at least some type of workaround.

How can I ensure the tag (github.event.ref) matches the regex pattern (/v[0-9]+(\.[0-9]+)*/)?

答:
As per docs, you can do this:

```<code>on:
  create:
    tags:
      - "v[0-9]+.[0-9]+"
</code>```

I tried the above and can confirm it works. This is not full regex capability but should suffice for your needs.

Title: GitHub Actions CI Conditional Regex

Body:
I'm trying to move my CI workflow from CircleCI to GitHub Actions. The last major struggle I'm facing is with deployment.

Currently my workflow is such that when I push a tag to my GitHub repo, it will run the tests, then run the deployment. Only thing is CircleCI filters tags to only run the job if the tag matches the regex: /v[0-9]+(\.[0-9]+)*/.

How can I check to ensure the tag I pushed matches the regex pattern above before running the deployment?

I currently have the following GitHub Actions yml file:

name: CI
on: [create]

jobs:
  # ...

  deploy:
    runs-on: ubuntu-latest
    if: github.event.ref_type == 'tag' && github.event.ref == SOMETHING HERE
    steps:
      - uses: actions/checkout@v1
      # ...

Under the if block, I need to change github.event.ref == SOMETHING HERE to be something else. I have looked in the Contexts and expression syntax for GitHub Actions documentation page. But due to how flexible and powerful GitHub Actions is, it seems like there should be a method or way to do this, or at least some type of workaround.

How can I ensure the tag (github.event.ref) matches the regex pattern (/v[0-9]+(\.[0-9]+)*/)?

Body:
As per docs, you can do this:

on:
  create:
    tags:
      - "v[0-9]+.[0-9]+"

I tried the above and can confirm it works. This is not full regex capability but should suffice for your needs.


问:
Validate an URL
Currently, I am using Angular 5. I tried to validate an URL as follows:

HTML:

```<code><div class="form-group col-sm-6">
  <input formControlName="s_url" type="url" class="form-control" id="kk" placeholder="url">
  <error-display [displayError]="isValid('s_url')" errMsg="This field is required!"></error-display>
</div>
</code>```

In validate.ts file, I have this pattern:

```<code>s_url: new FormControl('', [
  Validators.required,
  Validators.pattern("/^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/")
]),
</code>```

But with the pattern, error message is shown even when  a correct url is typed.

答:
I think this regex is more complete:

```<code>const urlRegex = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/;
this.form = this.fb.group({
      s_url: ['', [Validators.required, Validators.pattern(urlRegex)]],
    });

</code>```

Please for pattern check here

Title: Validate an URL

Body:
Currently, I am using Angular 5. I tried to validate an URL as follows:

HTML:

  <input formControlName="s_url" type="url" class="form-control" id="kk" placeholder="url">
  <error-display [displayError]="isValid('s_url')" errMsg="This field is required!"></error-display>

In validate.ts file, I have this pattern:

s_url: new FormControl('', [
  Validators.required,
  Validators.pattern("/^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/")
]),

But with the pattern, error message is shown even when  a correct url is typed.

Body:
I think this regex is more complete:

const urlRegex = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/;
this.form = this.fb.group({
      s_url: ['', [Validators.required, Validators.pattern(urlRegex)]],
    });

Please for pattern check here


问:
Laravel: Image not loading
I am trying to load an image in Laravel. The image is loading in a header.blade.php file. It is working fine on other pages but when it comes to localhost:8000/edit/id, It just doesn't work. I am loading Image like this:

```<code><a href="{!! URL::to('/') !!}">
   <img src="images/logo.png" />
</a>
</code>```

My Route:

```<code>Route::get('edit/{id}', array('uses' => 'HomeController@edit'));
</code>```

My Controller:

```<code> public function edit($id) {
    $reg = Register::find($id);
    $user = User::where('email', Session::get('email'))->first();
    if ($reg->user_id == $user->id) {
        return View::make('edit')
                        ->with('id', $id);
    } else {
        return Redirect::to('dashboard')->with('wrong', 'Sorry! Something Went Wrong!');
    }
}
</code>```

My image directory: public/images/logo.png

It is working fine on other pages like localhost:8000/about but it doesn't work on localhost/edit/2, any help?

答:
```<code><img src="public/storage/cover_images/image_name.format"  class="img-resposive">
</code>```

it will load your picture otherwise check the path to image and previlages of the folders you can load image only from a public path due to security reasons

Title: Laravel: Image not loading

Body:
I am trying to load an image in Laravel. The image is loading in a header.blade.php file. It is working fine on other pages but when it comes to localhost:8000/edit/id, It just doesn't work. I am loading Image like this:

My Route:

Route::get('edit/{id}', array('uses' => 'HomeController@edit'));

My Controller:

 public function edit($id) {
    $reg = Register::find($id);
    $user = User::where('email', Session::get('email'))->first();
    if ($reg->user_id == $user->id) {
        return View::make('edit')
                        ->with('id', $id);
    } else {
        return Redirect::to('dashboard')->with('wrong', 'Sorry! Something Went Wrong!');
    }
}

My image directory: public/images/logo.png

It is working fine on other pages like localhost:8000/about but it doesn't work on localhost/edit/2, any help?

Body:
<img src="public/storage/cover_images/image_name.format"  class="img-resposive">

it will load your picture otherwise check the path to image and previlages of the folders you can load image only from a public path due to security reasons


问:
Why isn't the "gets()" function declared when I include stdio.h?
```<code>#include <stdio.h>

int main() {
   char str[50];

   printf("Enter a string : ");
   gets(str);

   printf("You entered: %s", str);

   return (0);
}
</code>```

In my code, why isn't the gets() function declared? It shows me a bunch of errors such as:

```<code>In function ‘int main()’:
 error: ‘gets’ was not declared in this scope
gets(str);
    ^~~~
[Finished in 0.2s with exit code 1]
</code>```

I want to know why this kind of problem occurs?

答:
I am assuming you are wanting to get keyboard input from the user?

If you are using c++ you can use cin >> str

If you are using c you will want scanf("%s", &str)

gets was deprecated in C++11 and removed from C++14

Body:
#include <stdio.h>

int main() {
   char str[50];

   printf("Enter a string : ");
   gets(str);

   printf("You entered: %s", str);

   return (0);
}

In my code, why isn't the gets() function declared? It shows me a bunch of errors such as:

In function ‘int main()’:
 error: ‘gets’ was not declared in this scope
gets(str);
    ^~~~
[Finished in 0.2s with exit code 1]

I want to know why this kind of problem occurs?


问:
How to check for openCV on Ubuntu 9.10
How can I confirm if openCV is properly installed in my computer ? Is there any quick command line for it ? I am on Ubuntu 9.10 </p>

答:
Open your terminal and type this command:
python3 -c "import cv2; print(cv2.__version__)"

This works on my system

Title: How to check for openCV on Ubuntu 9.10


问:
Parent Selector of Several Elements Back
I can not figure out how to select an element (several elements back) from a specific element that has a certain title attribute.

For example, using the following example code, I am trying to target the first <renderer> element...

```<code><renderer class="scope">
   <div id="content" class="scope">
      <renderer class="scope">
         <div class="scope">
            <div id="details" class="scope">
               <a title="Foo Bar" href="#">LINK TEXT</a>
            </div>
         </div>
      </renderer>
   </div>
</renderer>
</code>```

I have tried many variation including this...

```<code>renderer:has a[title*="Foo Bar"] {
    opacity: 0.2 !important;
}
</code>```

Other things that I have tried don't even come close to working either (even JavaScript).... But possibly because every answer I found on here or other sites are not related to this issue enough to solve the problem.

How can I target and style the first <renderer> element (or at least 2 levels back) if the link title has specific text in it?

答:
As of Feb 2020, the :has CSS pseudo-class is not currently supported by any browser.

JS solution

If you're not sure how high up the DOM your renderer is you might need to recursively call Element.closest() in order to find it.

function getHighestRenderer(el) {
  const closestRenderer = el.parentNode.closest("renderer");
  if (closestRenderer) {
    return getHighestRenderer(closestRenderer);
  }
  return el;
}

const titleToMatch = "Foo Bar";
const detailsLinks = document.querySelectorAll(".details a");

detailsLinks.forEach(link => {
  if (titleToMatch === link.getAttribute("title")) {
    getHighestRenderer(link).classList.add("foobar");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.foobar {
  border: 1px dotted blue;
  padding: 10px;
  display: block;
}</code>```

<renderer class="scope">

    <renderer class="scope">

          LINK TEXT  - title: Not Foo Bar

    </renderer>

</renderer>

<renderer class="scope">

    <renderer class="scope">

          LINK TEXT - title: Not Foo Bar

    </renderer>

</renderer>

<renderer class="scope">

    <renderer class="scope">

          LINK TEXT - title: Foo Bar

    </renderer>

</renderer>```

Body:
I can not figure out how to select an element (several elements back) from a specific element that has a certain title attribute.

For example, using the following example code, I am trying to target the first <renderer> element...

<renderer class="scope">

      <renderer class="scope">

               LINK TEXT

      </renderer>

</renderer>

I have tried many variation including this...

renderer:has a[title*="Foo Bar"] {
    opacity: 0.2 !important;
}

Other things that I have tried don't even come close to working either (even JavaScript).... But possibly because every answer I found on here or other sites are not related to this issue enough to solve the problem.

How can I target and style the first <renderer> element (or at least 2 levels back) if the link title has specific text in it?

Body:
As of Feb 2020, the :has CSS pseudo-class is not currently supported by any browser.

JS solution

If you're not sure how high up the DOM your renderer is you might need to recursively call Element.closest() in order to find it.

function getHighestRenderer(el) {
  const closestRenderer = el.parentNode.closest("renderer");
  if (closestRenderer) {
    return getHighestRenderer(closestRenderer);
  }
  return el;
}

const titleToMatch = "Foo Bar";
const detailsLinks = document.querySelectorAll(".details a");

detailsLinks.forEach(link => {
  if (titleToMatch === link.getAttribute("title")) {
    getHighestRenderer(link).classList.add("foobar");
  }
});

.foobar {
  border: 1px dotted blue;
  padding: 10px;
  display: block;
}

<renderer class="scope">
  <div id="content" class="scope">
    <renderer class="scope">
      <div class="scope">
        <div id="" class="details scope">
          <a title="Not Foo Bar" href="#">LINK TEXT  - title: Not Foo Bar</a>
        </div>
      </div>
    </renderer>
  </div>
</renderer>

<renderer class="scope">
  <div id="content" class="scope">
    <renderer class="scope">
      <div class="scope">
        <div id="" class="details scope">
          <a title="Not Foo Bar" href="#">LINK TEXT - title: Not Foo Bar</a>
        </div>
      </div>
    </renderer>
  </div>
</renderer>

<renderer class="scope">
  <div id="content" class="scope">
    <renderer class="scope">
      <div class="scope">
        <div id="" class="details scope">
          <a title="Foo Bar" href="#">LINK TEXT - title: Foo Bar</a>
        </div>
      </div>
    </renderer>
  </div>
</renderer>


问:
What errors does FileManager throw?
What are all the errors that can be thrown by FileManager's methods? Specifically, I'm interested in the errors throwable by attributesOfItem(atPath:).

This is how I want to use it:

do {
    let inode = try FileManager.default.attributesOfItem(atPath: somePath)[.systemFileNumber]
} catch SomeError.someSpecificError (let someContext) {
    /* implementation omitted... */
}
```

答:
It can be like the following (see more file related constants in documentation for CocoaError)

```<code>do {
    let inode = try FileManager.default.attributesOfItem(atPath: somePath)[.systemFileNumber]
} catch CocoaError.fileNoSuchFile {
    print("Error: no such file exists")
} catch CocoaError.fileReadNoPermission {
    print("Error: you don't have permissions")
} catch {
    // something unknown
}
</code>```

Title: What errors does FileManager throw?

Body:
It can be like the following (see more file related constants in documentation for CocoaError)

do {
    let inode = try FileManager.default.attributesOfItem(atPath: somePath)[.systemFileNumber]
} catch CocoaError.fileNoSuchFile {
    print("Error: no such file exists")
} catch CocoaError.fileReadNoPermission {
    print("Error: you don't have permissions")
} catch {
    // something unknown
}


问:
this.shift = {x:this.x, y:this.y} works but not this.shift.x = this.x and this.shift.y = this.y?
```<code>this.x = (Math.random()*canvasWidth);
this.y = (Math.random()*canvasHeight);

(1) this.shift = {x: this.x, y: this.y};

(2) this.shift.x = this.x;
    this.shift.y = this.y;
</code>```

Hi guys, I am playing with canvas and on my way to create a particle system.

The first (1) one will work but not the second (2) one why?
I am getting an error saying "Cannot set property 'x' of undefined" when debug using Chrome dev tools.

Any idea?

答:
Because in example #2 there is no "shift" property of the "this" object, so the runtime cannot resolve any "x" (or "y") property thereof.  You could make it work by first assigning the "shift" object:</p>

```<code>this.shift = {};
this.shift.x = this.x;
this.shift.y = this.y;
</code>```

Body:
this.x = (Math.random()*canvasWidth);
this.y = (Math.random()*canvasHeight);

(1) this.shift = {x: this.x, y: this.y};

(2) this.shift.x = this.x;
    this.shift.y = this.y;

Hi guys, I am playing with canvas and on my way to create a particle system.

The first (1) one will work but not the second (2) one why?
I am getting an error saying "Cannot set property 'x' of undefined" when debug using Chrome dev tools.

Any idea?

Body:
Because in example #2 there is no "shift" property of the "this" object, so the runtime cannot resolve any "x" (or "y") property thereof.  You could make it work by first assigning the "shift" object:

this.shift = {};
this.shift.x = this.x;
this.shift.y = this.y;


问:
FormControl displaying ",required(control)" as its value
When my form loads the default values in my inputs is

,required(control) {        return isEmptyInputValue(control.value) ? { 'required': true } : null;    }

The way I have my template set up looks like this

```<code><form [formGroup]="SvgFormData" (ngSubmit)="onSubmit()">

    <section class="text-control-section">

        <label class="control-label">
            <p class="articleText">title:</p>

            <input class="text-control" type="text" formControlName="title" />

        </label>

        <label class="control-label">
            <p class="articleText">graphic id:</p>

            <input class="text-control" type="text" formControlName="graphicId" />

        </label>

    </section>

</form>
</code>```

This component recieves the FormGroup data from its' parent component through an @Input().  I'm ultimately making an app for parsing and saving SVG to my database in JSON format.  The parser returns a data object which I pass into a custom function to generate the entire FormGroup while filling in the values of the FormControls.  I want to be able to edit this data before saving it to the database which is why I'm bothering to make it into a form even though it's already technically completed.  the Top level function looks like this.

```<code>export function CreateGraphicObjectForm(data?: OvaadSvgDataObject): FormGroup{
    let graphicObjectForm: FormGroup = new FormGroup({
      title          : new FormControl([(data ? data.title     : ''), Validators.required]),
      graphicId      : new FormControl([(data ? data.graphicId : ''), Validators.required]),
      viewBox        : CreateViewBoxForm((data ? data.viewBox : undefined)),
      coreAttributes : new FormArray([]),
      coreStyles     : new FormArray([]),
      elements       : new FormArray([])
    });

    if(data.coreAttributes.length > 0){
      data.coreAttributes.forEach((a: OvaadGraphicAttribute)=>{

        let coreAttrArray: FormArray = graphicObjectForm.get('coreAttributes') as FormArray;

        coreAttrArray.push(CreateAttributeForm(a));

      });
    }

    if(data.coreStyles.length > 0){
      data.coreStyles.forEach((a: OvaadSvgStyleProperty)=>{

        let coreStyleArray: FormArray = graphicObjectForm.get('coreStyles') as FormArray;

        coreStyleArray.push(CreateStylePropertyForm(a));

      });
    }

    if(data.elements.length > 0){
      data.elements.forEach((a: OvaadGraphicObject)=>{

        let elementArray: FormArray = graphicObjectForm.get('elements') as FormArray;

        elementArray.push(CreateGraphicElementForm(a));

      });
    }

    return graphicObjectForm as FormGroup;
  }
</code>```

The title and graphicId controls are defined at this level of the function so I don't think it's necessary to share all the other functions and interfaces used.  So this is how the form is created before being passed into my component where I try to connect to them in the template.  Does anyone know why I'm getting this result and what I need to do differently to suit my use case?

答:
The problem here is forming FormControls, try this -

title: new FormControl((data ? data.title : ''), [Validators.required]),
graphicId: new FormControl((data ? data.graphicId  : ''), [Validators.required]),

Body:
When my form loads the default values in my inputs is

,required(control) {        return isEmptyInputValue(control.value) ? { 'required': true } : null;    }

The way I have my template set up looks like this

<form [formGroup]="SvgFormData" (ngSubmit)="onSubmit()">

title:

            <input class="text-control" type="text" formControlName="title" />

graphic id:

            <input class="text-control" type="text" formControlName="graphicId" />

</form>

This component recieves the FormGroup data from its' parent component through an @Input().  I'm ultimately making an app for parsing and saving SVG to my database in JSON format.  The parser returns a data object which I pass into a custom function to generate the entire FormGroup while filling in the values of the FormControls.  I want to be able to edit this data before saving it to the database which is why I'm bothering to make it into a form even though it's already technically completed.  the Top level function looks like this.

export function CreateGraphicObjectForm(data?: OvaadSvgDataObject): FormGroup{
    let graphicObjectForm: FormGroup = new FormGroup({
      title          : new FormControl([(data ? data.title     : ''), Validators.required]),
      graphicId      : new FormControl([(data ? data.graphicId : ''), Validators.required]),
      viewBox        : CreateViewBoxForm((data ? data.viewBox : undefined)),
      coreAttributes : new FormArray([]),
      coreStyles     : new FormArray([]),
      elements       : new FormArray([])
    });

    if(data.coreAttributes.length > 0){
      data.coreAttributes.forEach((a: OvaadGraphicAttribute)=>{

        let coreAttrArray: FormArray = graphicObjectForm.get('coreAttributes') as FormArray;

        coreAttrArray.push(CreateAttributeForm(a));

      });
    }

    if(data.coreStyles.length > 0){
      data.coreStyles.forEach((a: OvaadSvgStyleProperty)=>{

        let coreStyleArray: FormArray = graphicObjectForm.get('coreStyles') as FormArray;

        coreStyleArray.push(CreateStylePropertyForm(a));

      });
    }

    if(data.elements.length > 0){
      data.elements.forEach((a: OvaadGraphicObject)=>{

        let elementArray: FormArray = graphicObjectForm.get('elements') as FormArray;

        elementArray.push(CreateGraphicElementForm(a));

      });
    }

    return graphicObjectForm as FormGroup;
  }

The title and graphicId controls are defined at this level of the function so I don't think it's necessary to share all the other functions and interfaces used.  So this is how the form is created before being passed into my component where I try to connect to them in the template.  Does anyone know why I'm getting this result and what I need to do differently to suit my use case?


问:
How to download Angular 7?
I am able to find this version of Angular js.
https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js

I have read that version 7 is available now. The above version is 1.7 which seems to be very old as compared to 7.

I am learning Angular js.

Where can I download any new version of Angular js?

答:
If you navigate to: docs.angularjs.org

You could spot the notice:

This site and all of its contents are referring to AngularJS (version
  1.x), if you are looking for the latest Angular, please visit angular.io

To be short, AngularJS (1.x versions) is not Angular (even though Angular descends from AngularJS);

Not sure you're a web developer but nowdays in the javascript world the most of projects uses Nodejs and npm (package manager) to getting started projects. And Angular does too. So, in order to get latest angular, you could:

```<code>$ # from console
$ npm install -g @angular/cli
$ # creating a new angular project
$ ng new my-app
$ # running the app
$ cd my-app && ng serve --open
</code>```

The official doc is a good place to start: https://angular.io/guide/setup-local

Title: How to download Angular 7?

Body:
If you navigate to: docs.angularjs.org

You could spot the notice:

This site and all of its contents are referring to AngularJS (version
  1.x), if you are looking for the latest Angular, please visit angular.io

To be short, AngularJS (1.x versions) is not Angular (even though Angular descends from AngularJS);

Not sure you're a web developer but nowdays in the javascript world the most of projects uses Nodejs and npm (package manager) to getting started projects. And Angular does too. So, in order to get latest angular, you could:

$ # from console
$ npm install -g @angular/cli
$ # creating a new angular project
$ ng new my-app
$ # running the app
$ cd my-app && ng serve --open

The official doc is a good place to start: https://angular.io/guide/setup-local


问:
Problem with hdf5r finding libhdf5_hl.so.100 file
I'm trying to correctly load the R package hdf5r, well actually I want to use a dependency of hdf5r, but I'm running into problems with the hdf5r package. I've installed the hdf5r package, and no errors occurred during the installation. But when I load the package I get the following error:

```<code>> library(hdf5r)
Error: package or namespace load failed for ‘hdf5r’ in dyn.load(file, DLLpath = DLLpath, ...):
 unable to load shared object '/usr/lib64/R/library/hdf5r/libs/hdf5r.so':
  libhdf5_hl.so.100: cannot open shared object file: No such file or directory
</code>```

I have checked that both
/usr/lib64/R/library/hdf5r/libs/hdf5r.so and the libhdf5_hl.so.100 files are present on my system. I installed the hdf5 package from source into /usr/local and have added the path /usr/local/lib to the LD_LIBRARY_PATH variable in my /usr/lib64/R/etc/Renviron file

```<code>> Sys.getenv("LD_LIBRARY_PATH")
[1] "/usr/local/lib"
</code>```

I am on a RedHat 7 machine.

答:
I had the same problem, hdf5r can be loaded in the teminal R, however, it can't be loaded in the rstudio-server.

load the lib manully in r before load the hdf5r package

```<code>dyn.load('<your hdf5r lib path>/libhdf5_hl.so.100')
library(hdf5r)
</code>```

Body:
I'm trying to correctly load the R package hdf5r, well actually I want to use a dependency of hdf5r, but I'm running into problems with the hdf5r package. I've installed the hdf5r package, and no errors occurred during the installation. But when I load the package I get the following error:

> library(hdf5r)
Error: package or namespace load failed for ‘hdf5r’ in dyn.load(file, DLLpath = DLLpath, ...):
 unable to load shared object '/usr/lib64/R/library/hdf5r/libs/hdf5r.so':
  libhdf5_hl.so.100: cannot open shared object file: No such file or directory

I have checked that both
/usr/lib64/R/library/hdf5r/libs/hdf5r.so and the libhdf5_hl.so.100 files are present on my system. I installed the hdf5 package from source into /usr/local and have added the path /usr/local/lib to the LD_LIBRARY_PATH variable in my /usr/lib64/R/etc/Renviron file

> Sys.getenv("LD_LIBRARY_PATH")
[1] "/usr/local/lib"

I am on a RedHat 7 machine.

Body:
I had the same problem, hdf5r can be loaded in the teminal R, however, it can't be loaded in the rstudio-server.

load the lib manully in r before load the hdf5r package

dyn.load('<your hdf5r lib path>/libhdf5_hl.so.100')
library(hdf5r)


问:
Remove Leading spaces of every index in ArrayList
So, everything is working fine except the trim function. I don't know if it's working or not.

Actually I am making an inverted index using ArrayList. Fetching lines from files, splitting into words (tokenizing) and removing punctuation. When I get to the part of removing stopwords it doesn't match with the stopwords provided in file. I think this is because of the leading space of every index of ArrayList.

StopWords List :

```<code>a, is, the, of, all, and, to, can, be, as, once, for, at, am, are, has, have, had, up, his, her, in, on, no, we, do
</code>```

My Strategy:

```<code>String [] TempArray = new String[word.size()];

for (int i = 0; i < word.size(); i++) {
    word.set(i, word.get(i).toLowerCase());
    word.set(i, word.get(i).replaceAll("[^a-zA-Z]", ""));
}

for (int i = 0; i < word.size(); i++) {
    TempArray[i] = word.get(i);
    TempArray[i] = TempArray[i].trim();
    word.set(i, TempArray[i]);
    System.out.println(word.get(i));
}
</code>```

Output:

```<code>[a, blunder, by, anton, chekhov, , an, illustration, for, the, story, a, blunder, by, the, author, anton, chekhov, portrait, of, ivan, lazhechnikov...]
</code>```

Any kind of suggestions would be appreciated!

答:
Just to extend a bit @Andronicus's answer, this will remove also empty strings from resulting array.</p>

```<code>Arrays.stream(TempArray)
    .filter(Objects::nonNull)
    .map(String::trim)
    .filter(!String::isEmpty)
    .toArray(String[]::new);
</code>```

Body:
So, everything is working fine except the trim function. I don't know if it's working or not.

Actually I am making an inverted index using ArrayList. Fetching lines from files, splitting into words (tokenizing) and removing punctuation. When I get to the part of removing stopwords it doesn't match with the stopwords provided in file. I think this is because of the leading space of every index of ArrayList.

StopWords List :

a, is, the, of, all, and, to, can, be, as, once, for, at, am, are, has, have, had, up, his, her, in, on, no, we, do

My Strategy:

String [] TempArray = new String[word.size()];

for (int i = 0; i < word.size(); i++) {
    word.set(i, word.get(i).toLowerCase());
    word.set(i, word.get(i).replaceAll("[^a-zA-Z]", ""));
}

for (int i = 0; i < word.size(); i++) {
    TempArray[i] = word.get(i);
    TempArray[i] = TempArray[i].trim();
    word.set(i, TempArray[i]);
    System.out.println(word.get(i));
}

Output:

[a, blunder, by, anton, chekhov, , an, illustration, for, the, story, a, blunder, by, the, author, anton, chekhov, portrait, of, ivan, lazhechnikov...]

Any kind of suggestions would be appreciated!

Body:
Just to extend a bit @Andronicus's answer, this will remove also empty strings from resulting array.

Arrays.stream(TempArray)
    .filter(Objects::nonNull)
    .map(String::trim)
    .filter(!String::isEmpty)
    .toArray(String[]::new);


问:
how to connect to database from wordpress shortcode
How would I make this database echo out these a tags. the code words on a seperate but wont work on the short code

```<code>function get_repair_prices(){
$servername = "localhost";
$username = "localseo_prices";
$password = "******";
$dbname = "localseo_getitfixed";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM repair_prices";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
      echo "<a href=''>".$row['btn_name']."</a>";
    }
} else {
    echo "0 results";
}
$conn->close();

}
add_shortcode('price_shortcode', 'get_prices');
</code>```

it works as a seperate php file but will not output the data as shortcode

答:
Try this:</p>

```<code>function get_repair_prices($atts){
    $servername = "localhost";
    $username = "localseo_prices";
    $password = "******";
    $dbname = "localseo_getitfixed";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT * FROM repair_prices";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
          echo "<a href=''>".$row['btn_name']."</a>";
        }
    } else {
        echo "0 results";
    }
    $conn->close();

}
add_shortcode('price_shortcode', 'get_repair_prices');
</code>```

Body:
How would I make this database echo out these a tags. the code words on a seperate but wont work on the short code

function get_repair_prices(){
$servername = "localhost";
$username = "localseo_prices";
$password = "******";
$dbname = "localseo_getitfixed";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM repair_prices";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
      echo "".$row['btn_name']."";
    }
} else {
    echo "0 results";
}
$conn->close();

}
add_shortcode('price_shortcode', 'get_prices');

it works as a seperate php file but will not output the data as shortcode

Body:
Try this:

function get_repair_prices($atts){
    $servername = "localhost";
    $username = "localseo_prices";
    $password = "******";
    $dbname = "localseo_getitfixed";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT * FROM repair_prices";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
          echo "<a href=''>".$row['btn_name']."</a>";
        }
    } else {
        echo "0 results";
    }
    $conn->close();

}
add_shortcode('price_shortcode', 'get_repair_prices');


问:
Why does gcc produce this weird assembly vs clang?
I was trying to figure out differences between gcc and clang and how they handle std::vector. Can anyone with more knowledge explain why gcc and clang produce such different output?

gcc 9.2: https://godbolt.org/z/AFN46d
clang 9.0: https://godbolt.org/z/kEkpWE

The program:

#include <vector>

int foo(int a) {
    auto vec = std::vector<int>{};
    vec.push_back(1);
    vec.push_back(2);
    return vec[1] * a;
}
int main () {
    return foo(5) + foo(4);
}
```

<p>clang produces pretty understandable assembly. However, gcc produces this weird stuff:</p>

```void std::vector<int, std::allocator<int> >::_M_realloc_insert<int>(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, int&&):
        movabs  rcx, 2305843009213693951
        push    r15
        push    r14
        push    r13
        push    r12
        push    rbp
        push    rbx
        sub     rsp, 24
        mov     r12, QWORD PTR [rdi+8]
        mov     r8, QWORD PTR [rdi]
        mov     rax, r12
        sub     rax, r8
        sar     rax, 2
        cmp     rax, rcx
        je      .L16
        mov     r15, rdx
        mov     rdx, rsi
        mov     rbp, rdi
        mov     r13, rsi
        sub     rdx, r8
        test    rax, rax
        je      .L11
        movabs  r14, 9223372036854775804
        lea     rsi, [rax+rax]
        cmp     rax, rsi
        jbe     .L17
```

Where are these magic numbers coming from?

答:
GCC tries to be on the safe side and emits some additional checks. The first constant you're seeing is merely

```<code>__gnu_cxx::__numeric_traits<ptrdiff_t>::__max / sizeof(int)
</code>```

and constitutes the largest possible size of vector of ints on x86-64.

The second constant appears to be just

```<code>__gnu_cxx::__numeric_traits<ptrdiff_t>::__max
</code>```

rounded down to be divisible by sizeof(int).

In general, those things come from various max_size() methods in libstdc++. It is possible that clang is capable of proving some checks unnecessary.

Body:
I was trying to figure out differences between gcc and clang and how they handle std::vector. Can anyone with more knowledge explain why gcc and clang produce such different output?

gcc 9.2: https://godbolt.org/z/AFN46d
clang 9.0: https://godbolt.org/z/kEkpWE

The program:

#include <vector>

int foo(int a) {
    auto vec = std::vector<int>{};
    vec.push_back(1);
    vec.push_back(2);
    return vec[1] * a;
}
int main () {
    return foo(5) + foo(4);
}

clang produces pretty understandable assembly. However, gcc produces this weird stuff:

void std::vector<int, std::allocator<int> >::_M_realloc_insert<int>(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, int&&):
        movabs  rcx, 2305843009213693951
        push    r15
        push    r14
        push    r13
        push    r12
        push    rbp
        push    rbx
        sub     rsp, 24
        mov     r12, QWORD PTR [rdi+8]
        mov     r8, QWORD PTR [rdi]
        mov     rax, r12
        sub     rax, r8
        sar     rax, 2
        cmp     rax, rcx
        je      .L16
        mov     r15, rdx
        mov     rdx, rsi
        mov     rbp, rdi
        mov     r13, rsi
        sub     rdx, r8
        test    rax, rax
        je      .L11
        movabs  r14, 9223372036854775804
        lea     rsi, [rax+rax]
        cmp     rax, rsi
        jbe     .L17

Where are these magic numbers coming from?

Body:
GCC tries to be on the safe side and emits some additional checks. The first constant you're seeing is merely

__gnu_cxx::__numeric_traits<ptrdiff_t>::__max / sizeof(int)

and constitutes the largest possible size of vector of ints on x86-64.

The second constant appears to be just

__gnu_cxx::__numeric_traits<ptrdiff_t>::__max

rounded down to be divisible by sizeof(int).

In general, those things come from various max_size() methods in libstdc++. It is possible that clang is capable of proving some checks unnecessary.


问:
creating unprotected pdfs using mPDF
I use mPDF to create pdfs. Now I need to create pdf files unprotected. With SetProtection () I have everything enabled but the pdf is still SECURED. Can somewhere set up to make the pdf file completely unprotected?

Thank you for your help

答:
try it to after wirteHTML(); and before output();</p>

```<code>$mpdf->SetProtection(array(), '123456', '123456');
</code>```

Title: creating unprotected pdfs using mPDF

Body:
try it to after wirteHTML(); and before output();

$mpdf->SetProtection(array(), '123456', '123456');


问:
Flutter Custom Widget for ListView
How to make this type of ListView in flutter?

答:
You can create a custom stateful listViewItem widget and build the listview using ListViewBuilder.

```<code>Widget build(BuildContext context) {
   return YourWidget();
}
</code>```

In your listview:

```<code>Widget buildListView() {
  ListView.builder(
    controller: _controller,
    itemCount: _itemCount,
    itemBuilder: (BuildContext context, int index) {
      return YourWidget(item: items[index]);
  }
}
</code>```

Title: Flutter Custom Widget for ListView

Body:
You can create a custom stateful listViewItem widget and build the listview using ListViewBuilder.

Widget build(BuildContext context) {
   return YourWidget();
}

In your listview:

Widget buildListView() {
  ListView.builder(
    controller: _controller,
    itemCount: _itemCount,
    itemBuilder: (BuildContext context, int index) {
      return YourWidget(item: items[index]);
  }
}


问:
Reclaim memory from Tab Bar Controller after leaving
From a Navigation Controller, my app moves to a Tab Bar Controller and then back.  The memory usage jumps 35MB with the data I have in the tab bar controller view controllers.  When moving back from the Tab Bar Controller, I'd like to reclaim that memory.  Can that be done?</p>

答: It is done automatically untill there is a memory leak. Check if tab bar controller is dellocated when moving back.</p>


问:
rsacryptoserviceprovider using x509 certificates c#
i am using a certificate generated by makecert which has both private and public key.
The java side uses this public key to encrypt the data and .net decrypts it back.

I am trying to decrypt Java's encrypted 64 bit encoded string and getting bad data.

To see if all is good on.Net end, I frist tried to encrypt with the public key and then decrypt with  private using the same certificate. My code looks like this.

```<code>X509Certificate2 cert = GetCert(key, StoreName.My, StoreLocation.LocalMachine);
RSACryptoServiceProvider provider =  (RSACryptoServiceProvider)cert.PrivateKey;

RSACryptoServiceProvider publicprovider = (RSACryptoServiceProvider)cert.PublicKey.Key;

if (cert.HasPrivateKey)
    MessageBox.Show("Got private key");

byte[] encrypted = publicprovider.Encrypt(Encoding.UTF8.GetBytes(text), false);
byte[] decryptedBytes = provider.Decrypt(encrypted, false);
</code>```

Even here I am getting the error. Am i Missing something?

The certificate looks valid with both public and private key.

答:
I stumbled across this page when I was trying to find examples of makcert usage with x509 certificates and rsa using c#, and unfortunately it only provided part of the solution. I put all the bits together in a blog entry that people might be interested in, and it can be found here:
http://nick-howard.blogspot.com/2011/05/makecert-x509-certificates-and-rsa.html</p>

Body:
i am using a certificate generated by makecert which has both private and public key.
The java side uses this public key to encrypt the data and .net decrypts it back.

I am trying to decrypt Java's encrypted 64 bit encoded string and getting bad data.

To see if all is good on.Net end, I frist tried to encrypt with the public key and then decrypt with  private using the same certificate. My code looks like this.

X509Certificate2 cert = GetCert(key, StoreName.My, StoreLocation.LocalMachine);
RSACryptoServiceProvider provider =  (RSACryptoServiceProvider)cert.PrivateKey;

RSACryptoServiceProvider publicprovider = (RSACryptoServiceProvider)cert.PublicKey.Key;

if (cert.HasPrivateKey)
    MessageBox.Show("Got private key");

byte[] encrypted = publicprovider.Encrypt(Encoding.UTF8.GetBytes(text), false);
byte[] decryptedBytes = provider.Decrypt(encrypted, false);

Even here I am getting the error. Am i Missing something?

The certificate looks valid with both public and private key.


问:
Bootstrap tagsinput not working
I just came across Bootstrap tagsinput and I am trying it out, but I cant seem to get it working.

I added the following at the top of my layout :

```<code><link rel="stylesheet" href="~/Scripts/bootstrap_tagsinput/bootstrap-tagsinput.css">
</code>```

And I added the following at the bottom of my layout :

```<code><script src="~/Scripts/bootstrap_tagsinput/bootstrap-tagsinput.js"></script>
</code>```

Then in my partial page I added the following :

```<code><input type="text" value="" data-role="tagsinput" id="tags" class="form-control">
</code>```

Below is an image of what is happening, instead of the tags showing:

To my understanding, this should work. What am I missing ?

答:
I think that because it's a partial view and it appears after the library is loaded, it doesn't get applied.

I had exactly the same problem. My Index page had all the libraries included but the partial view never used them.

I had to add this to the partial view Razor to force it to apply after load.

```<code><script>
    $(function () {
        $('input[data-role=tagsinput]').tagsinput();
    }
    );
</script>
</code>```

Title: Bootstrap tagsinput not working

Body:
I just came across Bootstrap tagsinput and I am trying it out, but I cant seem to get it working.

I added the following at the top of my layout :

<link rel="stylesheet" href="~/Scripts/bootstrap_tagsinput/bootstrap-tagsinput.css">

And I added the following at the bottom of my layout :

Then in my partial page I added the following :

<input type="text" value="" data-role="tagsinput" id="tags" class="form-control">

Below is an image of what is happening, instead of the tags showing:

To my understanding, this should work. What am I missing ?

Body:
I think that because it's a partial view and it appears after the library is loaded, it doesn't get applied.

I had exactly the same problem. My Index page had all the libraries included but the partial view never used them.

I had to add this to the partial view Razor to force it to apply after load.

<script>
    $(function () {
        $('input[data-role=tagsinput]').tagsinput();
    }
    );
</script>


问:
Add icon to Laravelcollective submit button
I'm trying to add a trash icon to submit button and I tried this :

```<code>{!! Form::submit('', ['class' => 'btn btn-warning btn-sm fa fa-trash']) !!}
</code>```

but the icon won't show. How to solve this ? thanks in advance!

答:
there are not possible try it
laravel collective form given very competition

```<code><button class='btn btn-primary' type='submit' value='submit'>
<i class='fa fa-save'> </i> Save
</code>```

Body:
I'm trying to add a trash icon to submit button and I tried this :

{!! Form::submit('', ['class' => 'btn btn-warning btn-sm fa fa-trash']) !!}

but the icon won't show. How to solve this ? thanks in advance!

Body:
there are not possible try it
laravel collective form given very competition

<button class='btn btn-primary' type='submit' value='submit'>
<i class='fa fa-save'> </i> Save


问:
How do we give constraint on foreign key column based on ERD cardinality?
Let's say I have a 2 tables like below :

Department:

```<code>DeptId   Name
</code>```

Employee:

```<code>EmpId  Name    DeptId
</code>```

Here I have a 0-to-many relationship between Department and Employee table.

Now when I read the relationship from Department to Employee, it says 1 department can have 0 or more employees.

Does this mean while creating Employee table, I will set DepartmentId (foreign key) as null due to zero or many relationship?

And how do we represent 1 or many relationship like for eg If relationship in ERD says 1 department can have 0 or more employees then DepartmentId (foreign key) will be non nullable in Employee table?

Basically I am just trying to understand how do we give constraint on foreign key based on ERD cardinality (1 to many relation,1 to zero or more relationship).

Can anyone please help me clear this confusion? I will really really appreciate that :)

答:
I will set DepartmentId(Foreign key) as null due to zero or many
  relationship?

No, the Foreign key should be not null. Imagine you have no employee in table Employee with DeptId = 1. So it represents the Department has zero relationships.

Otherwise, the Employee table contains multiple items with DeptId = 2, So it represents the 1-n relationships between Department and Employee table.

Body:
Let's say I have a 2 tables like below :

Department:

DeptId   Name

Employee:

EmpId  Name    DeptId

Here I have a 0-to-many relationship between Department and Employee table.

Now when I read the relationship from Department to Employee, it says 1 department can have 0 or more employees.

Does this mean while creating Employee table, I will set DepartmentId (foreign key) as null due to zero or many relationship?

And how do we represent 1 or many relationship like for eg If relationship in ERD says 1 department can have 0 or more employees then DepartmentId (foreign key) will be non nullable in Employee table?

Basically I am just trying to understand how do we give constraint on foreign key based on ERD cardinality (1 to many relation,1 to zero or more relationship).

Can anyone please help me clear this confusion? I will really really appreciate that :)