问:
Auth::viaRemember() doesnot work (means always return false even after successful login) in laravel 5.4
I make use of php artisan make:auth in laravel 5.4, as we know laravel default login only supports email so, I put login() in AuthController like below (login working)-

```<code>public function login(Request $request)
{
    $remember = ($request->input('remember')=='1')?true:false;
    // this will remember the user as given in laravel documentation.
    if (Auth::attempt(['user_name' => $request->user_name, 'password' => $request->password],$remember)) {
        return redirect()->intended('admin');
    }

    elseif (Auth::attempt(['email'=> $request->user_name, 'password' => $request->password],$remember)) {

            return redirect()->intended('admin');
    }

    else {
        return redirect('/login')->with(['error'=>'Invalid user name and password'])
                                 ->withInput();

    }
}
</code>```

Now, whenever session expired simply typing url should redirect to admin/dashboard, But couldnot do so... By default it redirects to login page.

I put Auth::viaRemember() in constructor of AuthContoller class before checking for middleware like below-

```<code>public function __construct()
{
    // login with  remember me before checking whether its logged in or not
    Auth::viaRemember();
    $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
</code>```

What i follow in stack overflow -

Via Remember me always return false -this link is similar to mine

viaRemember not work - laravel

Laravel 5 viaRemember() always false

Laravel: Implement Auth::viaRemember() across the website

答:
```<code>public function __construct()
{
    Auth::viaRemember()
    Auth::check();
    Auth::viaRemember();
    $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
</code>```

try this

Body:
I make use of php artisan make:auth in laravel 5.4, as we know laravel default login only supports email so, I put login() in AuthController like below (login working)-

public function login(Request $request)
{
    $remember = ($request->input('remember')=='1')?true:false;
    // this will remember the user as given in laravel documentation.
    if (Auth::attempt(['user_name' => $request->user_name, 'password' => $request->password],$remember)) {
        return redirect()->intended('admin');
    }

    elseif (Auth::attempt(['email'=> $request->user_name, 'password' => $request->password],$remember)) {

            return redirect()->intended('admin');
    }

    else {
        return redirect('/login')->with(['error'=>'Invalid user name and password'])
                                 ->withInput();

    }
}

Now, whenever session expired simply typing url should redirect to admin/dashboard, But couldnot do so... By default it redirects to login page.

I put Auth::viaRemember() in constructor of AuthContoller class before checking for middleware like below-

public function __construct()
{
    // login with  remember me before checking whether its logged in or not
    Auth::viaRemember();
    $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}

What i follow in stack overflow -

Via Remember me always return false -this link is similar to mine

viaRemember not work - laravel

Laravel 5 viaRemember() always false

Laravel: Implement Auth::viaRemember() across the website

Body:
public function __construct()
{
    Auth::viaRemember()
    Auth::check();
    Auth::viaRemember();
    $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}

try this


来源: stackexchange

问:
Is this method of initialization recommended?
So when I was coding my own project, a problem came up with initializing an object. My class has so many attributes that needs to be initiated BUT not always all of them, which . That's when I came up with this idea (but I'm not sure if it's used before anywhere):

```<code>public class MyClass {
    public static final int DEFAULT1 = 1;
    public static final int DEFAULT2 = 2;
    public static final int DEFAULT3 = 3;
    private int attr1;
    private int attr2;
    private int attr3;
    private MyClass(){
        attr1 = DEFAULT1;
        attr2 = DEFAULT2;
        attr3 = DEFAULT3;
    }
    public static MyClass create(){
        return new MyClass();
    }
    public MyClass setAttr1(int attr1){
        this.attr1 = attr1;
        return this;
    }
    public MyClass setAttr2(int attr2){
        this.attr2 = attr2;
        return this;
    }
    public MyClass setAttr3(int attr3){
        this.attr3 = attr3;
        return this;
    }
}
</code>```

When I create a new MyClass instance I would do:

```<code>MyClass obj = MyClass.create().setAttr1(3).setAttr3(1);
</code>```

It worked for me (kind of because I tested it but I haven't decided to use it in my project). My question is, is this legit? Would it create any kinds of memory/execution problems?

答:
Your use case is a perfect example of Builder design pattern. Read more about here and oracle doc about builder. Also read why Builder pattern has an advantage over other creation pattern by Java legend Joshua which is discuss in his book, best practice of java
 here.

Your converted class using Builder design pattern will look like below. Note that i assumed attr1 optional and attr2 and attr3 as mandatory.

```<code>class MyClass {
    public static final int DEFAULT1 = 1;
    public static final int DEFAULT2 = 2;
    public static final int DEFAULT3 = 3;

    // assume attr1 is optional
    private int attr1;
    // assume attr2,3 is mandatory
    private int attr2;
    private int attr3;

    public MyClass(MyClassBuilder myClassBuilder) {
        this.attr1 = myClassBuilder.attr1;
        this.attr2 = myClassBuilder.attr2;
        this.attr3 = myClassBuilder.attr3;
    }

    //Builder Class
    public static class MyClassBuilder {

        // required parameters
        private int attr2;
        private int attr3;
        // optional parameters
        private int attr1;

        public MyClassBuilder(int attr2, int attr3){
            this.attr2 = attr2;
            this.attr3 = attr3;
        }

        public MyClassBuilder setAttr1(int attr1) {
            this.attr1 = attr1;
            return this;
        }

        public MyClass build(){
            return new MyClass(this);
        }

    }

}
</code>```

Now After that using below code, you can create the objects (with/without) optional param.

```<code>public class MyClassTest {

    public static void main(String[] args) {
        MyClass myClass = new MyClass.MyClassBuilder(10,20).build();
    // without optional param
    System.out.println("without optional param");
    System.out.println("attr1 "+ myClass.getAttr1());
    System.out.println("attr2 "+ myClass.getAttr2());
    System.out.println("attr3 "+ myClass.getAttr3());

    // with optional param
    System.out.println("with optional param");
    MyClass myClassWithAllParam = new MyClass.MyClassBuilder(10,20).setAttr1(5).build();
    System.out.println("attr1 "+ myClassWithAllParam.getAttr1());
    System.out.println("attr2 "+ myClassWithAllParam.getAttr2());
    System.out.println("attr3 "+ myClassWithAllParam.getAttr3());

    }
}
</code>```

Output of which is below :-

```<code>without optional param
attr1 0
attr2 10
attr3 20
with optional param
attr1 5
attr2 10
attr3 20
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So when I was coding my own project, a problem came up with initializing an object. My class has so many attributes that needs to be initiated BUT not always all of them, which . That's when I came up with this idea (but I'm not sure if it's used before anywhere):

public class MyClass {
    public static final int DEFAULT1 = 1;
    public static final int DEFAULT2 = 2;
    public static final int DEFAULT3 = 3;
    private int attr1;
    private int attr2;
    private int attr3;
    private MyClass(){
        attr1 = DEFAULT1;
        attr2 = DEFAULT2;
        attr3 = DEFAULT3;
    }
    public static MyClass create(){
        return new MyClass();
    }
    public MyClass setAttr1(int attr1){
        this.attr1 = attr1;
        return this;
    }
    public MyClass setAttr2(int attr2){
        this.attr2 = attr2;
        return this;
    }
    public MyClass setAttr3(int attr3){
        this.attr3 = attr3;
        return this;
    }
}

When I create a new MyClass instance I would do:

MyClass obj = MyClass.create().setAttr1(3).setAttr3(1);

It worked for me (kind of because I tested it but I haven't decided to use it in my project). My question is, is this legit? Would it create any kinds of memory/execution problems?

Body:
Your use case is a perfect example of Builder design pattern. Read more about here and oracle doc about builder. Also read why Builder pattern has an advantage over other creation pattern by Java legend Joshua which is discuss in his book, best practice of java
 here.

Your converted class using Builder design pattern will look like below. Note that i assumed attr1 optional and attr2 and attr3 as mandatory.

class MyClass {
    public static final int DEFAULT1 = 1;
    public static final int DEFAULT2 = 2;
    public static final int DEFAULT3 = 3;

    // assume attr1 is optional
    private int attr1;
    // assume attr2,3 is mandatory
    private int attr2;
    private int attr3;

    public MyClass(MyClassBuilder myClassBuilder) {
        this.attr1 = myClassBuilder.attr1;
        this.attr2 = myClassBuilder.attr2;
        this.attr3 = myClassBuilder.attr3;
    }

    //Builder Class
    public static class MyClassBuilder {

        // required parameters
        private int attr2;
        private int attr3;
        // optional parameters
        private int attr1;

        public MyClassBuilder(int attr2, int attr3){
            this.attr2 = attr2;
            this.attr3 = attr3;
        }

        public MyClassBuilder setAttr1(int attr1) {
            this.attr1 = attr1;
            return this;
        }

        public MyClass build(){
            return new MyClass(this);
        }

    }

}

Now After that using below code, you can create the objects (with/without) optional param.

public class MyClassTest {

    public static void main(String[] args) {
        MyClass myClass = new MyClass.MyClassBuilder(10,20).build();
    // without optional param
    System.out.println("without optional param");
    System.out.println("attr1 "+ myClass.getAttr1());
    System.out.println("attr2 "+ myClass.getAttr2());
    System.out.println("attr3 "+ myClass.getAttr3());

    // with optional param
    System.out.println("with optional param");
    MyClass myClassWithAllParam = new MyClass.MyClassBuilder(10,20).setAttr1(5).build();
    System.out.println("attr1 "+ myClassWithAllParam.getAttr1());
    System.out.println("attr2 "+ myClassWithAllParam.getAttr2());
    System.out.println("attr3 "+ myClassWithAllParam.getAttr3());

    }
}

Output of which is below :-

without optional param
attr1 0
attr2 10
attr3 20
with optional param
attr1 5
attr2 10
attr3 20


问:
Javascript re-load of page before sending data to PHP script
Background:
 I want to create a login form, the user input the "user ID" and "password".
 My JavaScript file checks certain parameters. If the data does not comply
 with them the my page is re-load.
 If the data is approved then after checking in JavaScript my PHP script
 kicks in and does other stuff.

Question: the problem I am having is that even though the data is not complaint with the JavaScript check up my page is not re-loading. It keeps sending the data to my PHP script.

Which is want I do not want.

I want to re-loed the same page and not send to PHP. I want to send the data to PHP when the data has passed the JavaScript check up.

CODE:

HTML SECTION

JavaScript SECTION

Thank you

If you guys can suggest a way to approach this situation it would be great.

Thank you.

答:
Your approach is incorrect , you don't need to reload the page in case of none valid entries , I would suggest doing something similar to the following :

function checkForm(){
  if(document.getElementById("whatever").value != 'xyz') {
    console.log("False !")
    return false;
  }
  return true
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="something.php" onsubmit="return checkForm()">
<input type="text" id="whatever">
<input type="submit">
</form></code>```

Body:
Your approach is incorrect , you don't need to reload the page in case of none valid entries , I would suggest doing something similar to the following :

function checkForm(){
  if(document.getElementById("whatever").value != 'xyz') {
    console.log("False !")
    return false;
  }
  return true
}

<form action="something.php" onsubmit="return checkForm()">
<input type="text" id="whatever">
<input type="submit">
</form>


问:
c++ error: no matching function for call to 'getline' from within function, but works in main
Update: Thanks for the advice! Removing const from my function paramaters and replacing #include  with #include , worked!

I'm new to C++ and I've looked up several posts, but can't seem to figure out why I am getting an "error: no matching function for call to 'getline'" from within my user defined function, when it is working fine from the main function.

I also don't understand why in some examples that I've seen online getline takes 2 paramaters (std::istream&, std::string&) and in others it takes 3 parameters (std::istream&, std::string&, char)

Have been racking my brain for a solution, would really appreciate if anyone can point out what I’m missing. sorry if this is a naive question!

condensed code:

```<code> #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>
 #include <fstream>
 #include <iostream>
 #include <cstdlib>

 using namespace std;

 char *myfunction (std::ifstream& infile, const std::string& strBuf){

        //compile error "no matching function for call to 'getline'"
        getline(infile, strBuf);

        char *ptr= NULL;
        return ptr;
    }

  int main() {
        ifstream infile;
        infile.open("myfile");
        std::string strBuf;

        getline(infile, strBuf);
        // prints the first line of the file as expected
        cout << strBuf << endl;

    }
</code>```

答:
You can't read to a const object.

Change the argument type from const std::string& to just std::string&.

```<code>char *myfunction (std::ifstream& infile, std::string& strBuf)
                                     // ^^ No const
{
    getline(infile, strBuf);
    ...
}
</code>```

Also, as mentioned in a comment, don't forget to add

```<code>#include <string>
</code>```

Body:
Update: Thanks for the advice! Removing const from my function paramaters and replacing #include  with #include , worked!

I'm new to C++ and I've looked up several posts, but can't seem to figure out why I am getting an "error: no matching function for call to 'getline'" from within my user defined function, when it is working fine from the main function.

I also don't understand why in some examples that I've seen online getline takes 2 paramaters (std::istream&, std::string&) and in others it takes 3 parameters (std::istream&, std::string&, char)

Have been racking my brain for a solution, would really appreciate if anyone can point out what I’m missing. sorry if this is a naive question!

condensed code:

 #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>
 #include <fstream>
 #include <iostream>
 #include <cstdlib>

 using namespace std;

 char *myfunction (std::ifstream& infile, const std::string& strBuf){

        //compile error "no matching function for call to 'getline'"
        getline(infile, strBuf);

        char *ptr= NULL;
        return ptr;
    }

  int main() {
        ifstream infile;
        infile.open("myfile");
        std::string strBuf;

        getline(infile, strBuf);
        // prints the first line of the file as expected
        cout << strBuf << endl;

    }

Body:
You can't read to a const object.

Change the argument type from const std::string& to just std::string&.

char *myfunction (std::ifstream& infile, std::string& strBuf)
                                     // ^^ No const
{
    getline(infile, strBuf);
    ...
}

Also, as mentioned in a comment, don't forget to add

#include <string>


问:
Refactoring advice: maps to POJOs
I currently am part of a project where there is an interface like this:

```<code>public interface RepositoryOperation {

    public OperationResult execute(Map<RepOpParam, Object> params);
}
</code>```

This interface has about ~100 implementers.

To call an implementer one needs to do the following:

```<code>final Map<RepOpParam, Object> opParams = new HashMap<RepOpParam, Object>();
opParams.put(ParamName.NAME1, val1);
opParams.put(ParamName.NAME2, val2);
</code>```

Now I think that there is obviously something wrong with anything with a<Something, Object> generic declaration.

Currently this causes a caller of a OperationImpl to have to actually read the code of the operation in order to know how to build the argument map. (and this is not even the worst of the problems, but I don't want to cite them all since they are fairly obvious)

After some discussion I managed to convince my colleagues to let me do some refactoring.

It seems to me that the simplest 'fix' would be to change the interface like so:

```<code>public interface RepositoryOperation {

    public OperationResult execute(OperationParam param);
}
</code>```

After all the concrete operations will define (extend) their own OperationParam and the needed arguments would be visible to everybody. (which is the 'normal way' to do things like that IMHO)

So as I see it since the interface implementers are quite numerous I have several choices:

Try to change the interface and rewrite all the Operation calls to use objects instead of maps. This seems the cleanest, but I think that since the operations are a lot it might be too much work in practice. (~2 weeks with tests probably)

Add an additional method to the interface like so:

```<code>public interface RepositoryOperation {
    public OperationResult execute(Map<String, Object> params);
    public OperationResult execute(OperationParam params);
}
</code>```

and fix the map calls whenever I come across them during functionality implementation.

Live with it (please no !).

So my question is.

Does anyone see a better approach for 'fixing' the maps and if you do would you fix them with method 1 or 2 or not fix them at all.

EDIT:
Thanks for the great answers. I would accept both Max's and Riduidel's answers if I could, but since I can't I'm leaning a bit more towards Riduidel's.

答:
It sounds like you have an unnecessary and  misguided abstraction.  Anytime I see an interface with one method in it, I think Strategy pattern or Action pattern, depending on whether you make the decision at runtime or not.

One way to cleanup the code is have each RepositoryOperation implementation have a constructor which takes the specific arguments it needs for the execute method to run correctly.  That way there is no messy casting of the Object values in the map.

If you want to keep the execute method signature, you might be able to use generics to putter tighter bounds on the values of the Map.

ContentLicense: CC BY-SA 2.5

Title: Refactoring advice: maps to POJOs

Body:
I currently am part of a project where there is an interface like this:

public interface RepositoryOperation {

    public OperationResult execute(Map<RepOpParam, Object> params);
}

This interface has about ~100 implementers.

To call an implementer one needs to do the following:

final Map<RepOpParam, Object> opParams = new HashMap<RepOpParam, Object>();
opParams.put(ParamName.NAME1, val1);
opParams.put(ParamName.NAME2, val2);

Now I think that there is obviously something wrong with anything with a<Something, Object> generic declaration.

Currently this causes a caller of a OperationImpl to have to actually read the code of the operation in order to know how to build the argument map. (and this is not even the worst of the problems, but I don't want to cite them all since they are fairly obvious)

After some discussion I managed to convince my colleagues to let me do some refactoring.

It seems to me that the simplest 'fix' would be to change the interface like so:

public interface RepositoryOperation {

    public OperationResult execute(OperationParam param);
}

After all the concrete operations will define (extend) their own OperationParam and the needed arguments would be visible to everybody. (which is the 'normal way' to do things like that IMHO)

So as I see it since the interface implementers are quite numerous I have several choices:

Try to change the interface and rewrite all the Operation calls to use objects instead of maps. This seems the cleanest, but I think that since the operations are a lot it might be too much work in practice. (~2 weeks with tests probably)

Add an additional method to the interface like so:

public interface RepositoryOperation {
    public OperationResult execute(Map<String, Object> params);
    public OperationResult execute(OperationParam params);
}

and fix the map calls whenever I come across them during functionality implementation.

Live with it (please no !).

So my question is.

Does anyone see a better approach for 'fixing' the maps and if you do would you fix them with method 1 or 2 or not fix them at all.

EDIT:
Thanks for the great answers. I would accept both Max's and Riduidel's answers if I could, but since I can't I'm leaning a bit more towards Riduidel's.


问:
printing session variables in php
How do I print these sessions using the print_r function.

I'm new to php.

Theses are the sessions.

```<code>$studentID = $_SESSION['StudentID'];
$offeringID=$_SESSION['OfferingID'];
$email=$_SESSION['email'];
</code>```

Any help would be very much appreciated.

答:
If you want to print whole session then

```<code>print_r($_SESSION);
</code>```

IF you want single session then

```<code>print_r($_SESSION['StudentID']);
</code>```

Title: printing session variables in php

Body:
How do I print these sessions using the print_r function.

I'm new to php.

Theses are the sessions.

$studentID = $_SESSION['StudentID'];
$offeringID=$_SESSION['OfferingID'];
$email=$_SESSION['email'];

Any help would be very much appreciated.

Body:
If you want to print whole session then

print_r($_SESSION);

IF you want single session then

print_r($_SESSION['StudentID']);


问:
How can I check for a response cookie in Asp.net Core MVC (aka Asp.Net 5 RC1)?
I'm converting a web forms application to asp.net core mvc.  In my web forms application sometimes after I set some response cookies other code needs to see if they were set, and if so, access the cookie's properties (i.e. value, Expires, Secure, http).  In webforms and MVC 5 it's possible to iterate over the cookies and return any particular cookies like so (old school I know)

```<code>       for(int i = 0; i < cookies.Count; i++) {
            if(cookies[i].Name == cookieName) {
                return cookies[i];
            }
        }
</code>```

But the interface for accessing response cookies in asp.net core mvc looks like this:

Based on this interface I don't see a way to check to see if a response cookie exists and obtain it's properties.  But there has gotta be some way to do it?

In an action method I tried setting two cookies on the response object and then immediately trying to access them.  But intellisense doesn't show any methods, properties or indexers that would allow me to access them:

For a moment, I thought that perhaps I could use Response.Cookies.ToString(); and just parse the information to find my cookie info, but alas, the ToString() call returns "Microsoft.AspNet.Http.Internal.ResponseCookies" because the object doesn't override the default implementation.

Just for fun I also checked the current dev branch of GitHub to see if the interface has changed since RC1 but it has not.  So given this interface, how do I check for the existence of a response cookie and get it's properties?  I've thought about trying to hack in via the response headers collection but that seems pretty lame.

答:
Here's how I get the value of a cookie from a Response. Something like this could be used to get the whole cookie if required:

```<code>string GetCookieValueFromResponse(HttpResponse response, string cookieName)
{
  foreach (var headers in response.Headers.Values)
    foreach (var header in headers)
      if (header.StartsWith($"{cookieName}="))
      {
        var p1 = header.IndexOf('=');
        var p2 = header.IndexOf(';');
        return header.Substring(p1 + 1, p2 - p1 - 1);
      }
  return null;
}
</code>```

Body:
I'm converting a web forms application to asp.net core mvc.  In my web forms application sometimes after I set some response cookies other code needs to see if they were set, and if so, access the cookie's properties (i.e. value, Expires, Secure, http).  In webforms and MVC 5 it's possible to iterate over the cookies and return any particular cookies like so (old school I know)

       for(int i = 0; i < cookies.Count; i++) {
            if(cookies[i].Name == cookieName) {
                return cookies[i];
            }
        }

But the interface for accessing response cookies in asp.net core mvc looks like this:

Based on this interface I don't see a way to check to see if a response cookie exists and obtain it's properties.  But there has gotta be some way to do it?

In an action method I tried setting two cookies on the response object and then immediately trying to access them.  But intellisense doesn't show any methods, properties or indexers that would allow me to access them:

For a moment, I thought that perhaps I could use Response.Cookies.ToString(); and just parse the information to find my cookie info, but alas, the ToString() call returns "Microsoft.AspNet.Http.Internal.ResponseCookies" because the object doesn't override the default implementation.

Just for fun I also checked the current dev branch of GitHub to see if the interface has changed since RC1 but it has not.  So given this interface, how do I check for the existence of a response cookie and get it's properties?  I've thought about trying to hack in via the response headers collection but that seems pretty lame.

Body:
Here's how I get the value of a cookie from a Response. Something like this could be used to get the whole cookie if required:

string GetCookieValueFromResponse(HttpResponse response, string cookieName)
{
  foreach (var headers in response.Headers.Values)
    foreach (var header in headers)
      if (header.StartsWith($"{cookieName}="))
      {
        var p1 = header.IndexOf('=');
        var p2 = header.IndexOf(';');
        return header.Substring(p1 + 1, p2 - p1 - 1);
      }
  return null;
}

ContentLicense: CC BY-SA 4.0


问:
How to print log in to contentType="image/jpeg jsp files?
I'm going to use Img tag to show charts from load jsp file.
I put <% System.out.println("log") %> in jsp file which was linked to img tag.
but <% System.out.println("log") %> is not working in contentType="image/jpeg jsp files.

How should i print log in that type of files?

答:
The out in jsp is a JspWriter object which is created by Jsp automatically, it is used to write something to webpage while System.out.print() is used to output/write something to the console. Use
out.println()


问:
How to organize state with redux and react-router?
Redux advocates the use of a single store with a single state. However, with react-router you get multiple pages each having their own top-level root component. </p>

<p>How should one go about wiring up redux with a react-router app that has multiple pages? React-router 1.0 no longer lets you pass props to the routes so making the router the top level component that contains the state for all the pages is no longer possible nor is it feasible. </p>

答:
Redux-router is no longer compatible with react-router v4, and the above solution will not work.

As such, I suggest utilzing redux-little-router. Unlike redux-router it is not dependent on react-router, but instead a replacement for it.

With it you can do things like:

Push to new routes from your async actions:

```<code>export function navigateAbout() {
  return (dispatch) => {
    dispatch(push('/about'))
  }
}
</code>```

See your router details (current path, querystring and params) inside redux-dev-tools, and access those details from you store like you would for any other prop:

```<code>function mapStateToProps(state) {
  return {
    string: state.router.query.string
  }
}
</code>```

PS. You can refer to or use this react boilerplate with redux-little-redux already implemented

Body:
Redux advocates the use of a single store with a single state. However, with react-router you get multiple pages each having their own top-level root component.

How should one go about wiring up redux with a react-router app that has multiple pages? React-router 1.0 no longer lets you pass props to the routes so making the router the top level component that contains the state for all the pages is no longer possible nor is it feasible.

Body:
Redux-router is no longer compatible with react-router v4, and the above solution will not work.

As such, I suggest utilzing redux-little-router. Unlike redux-router it is not dependent on react-router, but instead a replacement for it.

With it you can do things like:

Push to new routes from your async actions:

export function navigateAbout() {
  return (dispatch) => {
    dispatch(push('/about'))
  }
}

See your router details (current path, querystring and params) inside redux-dev-tools, and access those details from you store like you would for any other prop:

function mapStateToProps(state) {
  return {
    string: state.router.query.string
  }
}

PS. You can refer to or use this react boilerplate with redux-little-redux already implemented


问:
Android Studio 2.3.2 and Kotlin 1.1.2-4 + Data Binding
I have issue in Android Studio 2.3.2 when trying to use Kotlin 1.1.2-4 and Data Binding.

Here is my gradle files:

```<code>buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "my.app.kotlin.databinding"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    dataBinding {
        enabled = true
    }
}

dependencies {

    // Data binding compiler for kotlin
    kapt 'com.android.databinding:compiler:2.3.2'

    //support libraries
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'

    // std lib for Kotlin
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

    testCompile 'junit:junit:4.12'
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
}
repositories {
    mavenCentral()
}
</code>```

When I try to compile the project it gives me this error:

```<code>* Exception is:
org.gradle.api.CircularReferenceException: Circular dependency between the following tasks:
:app:compileReleaseKotlin
\--- :app:kaptReleaseKotlin
     \--- :app:compileReleaseKotlin (*)

(*) - details omitted (listed previously)

        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.onOrderingCycle(DefaultTaskExecutionPlan.java:445)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.determineExecutionPlan(DefaultTaskExecutionPlan.java:287)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.ensurePopulated(DefaultTaskGraphExecuter.java:202)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:109)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
        at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
        at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
        at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
        at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)

BUILD FAILED
</code>```

If I switch back to version 1.1.2-3 everything works well and compiling without any issue.

What I missed? Why it doesn't work with version 1.1.2-4?

答: It is a bug, but you can download Android Studio 3.0 Canary 3 and update your Android Gradle Plugin to 3.0.0-alpha3 and it's fixed.

Body:
I have issue in Android Studio 2.3.2 when trying to use Kotlin 1.1.2-4 and Data Binding.

Here is my gradle files:

buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "my.app.kotlin.databinding"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    dataBinding {
        enabled = true
    }
}

dependencies {

    // Data binding compiler for kotlin
    kapt 'com.android.databinding:compiler:2.3.2'

    //support libraries
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'

    // std lib for Kotlin
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

    testCompile 'junit:junit:4.12'
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
}
repositories {
    mavenCentral()
}

When I try to compile the project it gives me this error:

* Exception is:
org.gradle.api.CircularReferenceException: Circular dependency between the following tasks:
:app:compileReleaseKotlin
\--- :app:kaptReleaseKotlin
     \--- :app:compileReleaseKotlin (*)

(*) - details omitted (listed previously)

        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.onOrderingCycle(DefaultTaskExecutionPlan.java:445)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.determineExecutionPlan(DefaultTaskExecutionPlan.java:287)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.ensurePopulated(DefaultTaskGraphExecuter.java:202)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:109)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
        at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
        at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
        at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
        at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)

BUILD FAILED

If I switch back to version 1.1.2-3 everything works well and compiling without any issue.

What I missed? Why it doesn't work with version 1.1.2-4?


问:
Programmatically trigger a select event in open layers 4
Is there any chance to trigger a manual selection for an ol.feature in ol4? I saw the post here, but i have the same issue : the custom selection style is not applied. Any workarounds to get programmatically selection working as normal selection(within map)? </p>

答:
The problem I had to solve was - if an user clicked on a record in an external table, I had to display a popup for that feature. This is how I solved the problem.

When drawing the map, I saved the layer source, the list of features in a global variable.

When user clicks on the record in the table, I get the ID of the record.

Get the feature - layerSource.getFeatureById (id)

Draw the popup. (don't think you are interested in this step)

If you have to set the style, I think you will need to remove the old Vector layer from the map, and redraw the layer again. For the style, you will need to use a function that will return a different style for the selected feature.


问:
Global variables to local variables
My program to find the roots of a function using the quadratic formula is below. It works perfectly. However I was unable to get it to work without defining three of the variables globally; which, according to my project description, I am not supposed to do.

Any suggestions or alterations on how to define them locally and have the calculations not get lost before the print results function is able to do so?

```<code>#include <stdio.h>
#include <math.h>

double discriminant;
double root_one = 0, root_two = 0;
double a = 0, b = 0, c = 0;

int checkComplex(double a, double b, double c)
{
    discriminant = (b * b) - 4 * (a * c);

    if (discriminant == 0)
        return 2;

    else if (discriminant > 0)
        return 1;

    else
        return 0;
}// end checkComplex

void calculateRoots(double a, double b, double c)
{
    root_one = (-b + sqrt(discriminant)) / (2 * a);
    root_two = (-b - sqrt(discriminant)) / (2 * a);
} // end calculateRoots

void getData()
{
    printf("Enter a: ");
    scanf("%lf", &a);

    printf("\nEnter b: ");
    scanf("%lf", &b);

    printf("\nEnter c: ");
    scanf("%lf", &c);
}// end getData

void printResults()
{
    if (checkComplex(a, b, c) == 1)
    {
        calculateRoots(a, b, c);
        printf("\n\n-----------------------------------------\n");
        printf("\nThe quantity (b^2-4ac) is %.2lf", discriminant);
        printf("\n\nfirst root = %.2lf\nsecond root = %.2lf\n\n", root_one,
               root_two);
    }// if discriminant is 1

    else if (checkComplex(a, b, c) == 0)
    {
        printf("\n\n-----------------------------------------\n");
        printf("The discriminant (b^2-4ac) is negative (imaginary)");
        printf("\nTherefore, the roots are complex\n");
    } // if discriminant is 0

    else if (checkComplex(a == 2, b == 2, c == 2))
    {
        calculateRoots(a, b, c);
        printf("\n\n-----------------------------------------\n");
        printf("\nThe quantity (b^2-4ac) is %.2lf", discriminant);
        printf("\n\nfirst root = %.2lf\nsecond root = %.2lf\n\n", root_one,
               root_two);
    }// if discriminant is greater than 1
} // end printResults

int main()
{
    getData();
    printResults();
    return 0;
} // End program
</code>```

答:
If you need to return multiple values, you can return a struct, or you can accept pointers to where the result should be stored. I've used both approaches in the following solution:</p>

```<code>#include <stdio.h>
#include <math.h>

typedef struct {
   double discriminant;
   char num_roots;
   double roots[2];
} roots_t;

void getData(double* ap, double* bp, double* cp) {
   printf("Enter a: ");   scanf("%lf", ap);
   printf("Enter b: ");   scanf("%lf", bp);
   printf("Enter c: ");   scanf("%lf", cp);
}

roots_t calculateRoots(double a, double b, double c) {
   roots_t roots;
   roots.discriminant = (b*b) - 4 * (a*c);
   roots.num_roots = 0;
   if (roots.discriminant >= 0) {
      roots.roots[roots.num_roots++] = (-b + sqrt(roots.discriminant)) / (2 * a);
      if (roots.discriminant > 0)
         roots.roots[roots.num_roots++] = (-b - sqrt(roots.discriminant)) / (2 * a);
      }
   }

   return roots;
}

void printResults(double a, double b, double c, roots_t roots) {
   if (roots.num_roots == 2) {
      printf("The quantity (b^2-4ac) is %.2lf\n", roots.discriminant);
      printf("roots = %.2lf, %.2lf\n", roots.roots[0], roots.roots[1]);
   }
   else if (roots.num_roots == 1) {
      printf("The quantity (b^2-4ac) is %.2lf\n", roots.discriminant);
      printf("roots = %.2lf\n", roots.roots[0]);
   }
   else {
      printf("The discriminant (b^2-4ac) is negative\n");
      printf("roots = <complex>\n");
   }
}

int main(void) {
   double a, b, c;
   getData(&a, &b, &c);
   printResults(a, b, c, calculateRoots(a, b, c));
   return 0;
}
</code>```

Title: Global variables to local variables

Body:
My program to find the roots of a function using the quadratic formula is below. It works perfectly. However I was unable to get it to work without defining three of the variables globally; which, according to my project description, I am not supposed to do.

Any suggestions or alterations on how to define them locally and have the calculations not get lost before the print results function is able to do so?

#include <stdio.h>
#include <math.h>

double discriminant;
double root_one = 0, root_two = 0;
double a = 0, b = 0, c = 0;

int checkComplex(double a, double b, double c)
{
    discriminant = (b * b) - 4 * (a * c);

    if (discriminant == 0)
        return 2;

    else if (discriminant > 0)
        return 1;

    else
        return 0;
}// end checkComplex

void calculateRoots(double a, double b, double c)
{
    root_one = (-b + sqrt(discriminant)) / (2 * a);
    root_two = (-b - sqrt(discriminant)) / (2 * a);
} // end calculateRoots

void getData()
{
    printf("Enter a: ");
    scanf("%lf", &a);

    printf("\nEnter b: ");
    scanf("%lf", &b);

    printf("\nEnter c: ");
    scanf("%lf", &c);
}// end getData

void printResults()
{
    if (checkComplex(a, b, c) == 1)
    {
        calculateRoots(a, b, c);
        printf("\n\n-----------------------------------------\n");
        printf("\nThe quantity (b^2-4ac) is %.2lf", discriminant);
        printf("\n\nfirst root = %.2lf\nsecond root = %.2lf\n\n", root_one,
               root_two);
    }// if discriminant is 1

    else if (checkComplex(a, b, c) == 0)
    {
        printf("\n\n-----------------------------------------\n");
        printf("The discriminant (b^2-4ac) is negative (imaginary)");
        printf("\nTherefore, the roots are complex\n");
    } // if discriminant is 0

    else if (checkComplex(a == 2, b == 2, c == 2))
    {
        calculateRoots(a, b, c);
        printf("\n\n-----------------------------------------\n");
        printf("\nThe quantity (b^2-4ac) is %.2lf", discriminant);
        printf("\n\nfirst root = %.2lf\nsecond root = %.2lf\n\n", root_one,
               root_two);
    }// if discriminant is greater than 1
} // end printResults

int main()
{
    getData();
    printResults();
    return 0;
} // End program

Body:
If you need to return multiple values, you can return a struct, or you can accept pointers to where the result should be stored. I've used both approaches in the following solution:

#include <stdio.h>
#include <math.h>

typedef struct {
   double discriminant;
   char num_roots;
   double roots[2];
} roots_t;

void getData(double* ap, double* bp, double* cp) {
   printf("Enter a: ");   scanf("%lf", ap);
   printf("Enter b: ");   scanf("%lf", bp);
   printf("Enter c: ");   scanf("%lf", cp);
}

roots_t calculateRoots(double a, double b, double c) {
   roots_t roots;
   roots.discriminant = (b*b) - 4 * (a*c);
   roots.num_roots = 0;
   if (roots.discriminant >= 0) {
      roots.roots[roots.num_roots++] = (-b + sqrt(roots.discriminant)) / (2 * a);
      if (roots.discriminant > 0)
         roots.roots[roots.num_roots++] = (-b - sqrt(roots.discriminant)) / (2 * a);
      }
   }

   return roots;
}

void printResults(double a, double b, double c, roots_t roots) {
   if (roots.num_roots == 2) {
      printf("The quantity (b^2-4ac) is %.2lf\n", roots.discriminant);
      printf("roots = %.2lf, %.2lf\n", roots.roots[0], roots.roots[1]);
   }
   else if (roots.num_roots == 1) {
      printf("The quantity (b^2-4ac) is %.2lf\n", roots.discriminant);
      printf("roots = %.2lf\n", roots.roots[0]);
   }
   else {
      printf("The discriminant (b^2-4ac) is negative\n");
      printf("roots = <complex>\n");
   }
}

int main(void) {
   double a, b, c;
   getData(&a, &b, &c);
   printResults(a, b, c, calculateRoots(a, b, c));
   return 0;
}


问:
Adding items from one list to another list in another form in c#
I have a Form1 which displays a list of students in a ListBox.

I use Form2 to populate this list of students, well I want to.

Form2 is meant to update the studentList_Form1 in Form1 every time a button is clicked in Form2.

what I'm trying to figure out is how to actually do this? Because I have tried this

Form1:

```<code>public List<Student> studentList_Form1;

public List<Student> StudentList_Form1
{
    get
    {
        return studentList_Form1;
    }
}
</code>```

Form2:

```<code>public List<Student> studentList = new List<Student>();

private void update_main_student_list()
{
    using (Form1 newForm = new Form1())
    {
        foreach(Student s in studentList)
        {
            newForm.StudentList_Form1.Add(s);
        }
    }
    //As well as the code to populate studentList
}
</code>```

But I keep getting an error saying I need to check if s if null before I use it.

Student is a class which is made up of a string name, string address, int id

答:
The code you showed cannot have an error about s being null.

The error tells you that studentList_Form1 in Form1 is null.

But the code is still pointless. You need to use studentList_Form1 from an existing Form1 (that list at some point still has to be instantiated) to add items to.

Body:
I have a Form1 which displays a list of students in a ListBox.

I use Form2 to populate this list of students, well I want to.

Form2 is meant to update the studentList_Form1 in Form1 every time a button is clicked in Form2.

what I'm trying to figure out is how to actually do this? Because I have tried this

Form1:

public List<Student> studentList_Form1;

public List<Student> StudentList_Form1
{
    get
    {
        return studentList_Form1;
    }
}

Form2:

public List<Student> studentList = new List<Student>();

private void update_main_student_list()
{
    using (Form1 newForm = new Form1())
    {
        foreach(Student s in studentList)
        {
            newForm.StudentList_Form1.Add(s);
        }
    }
    //As well as the code to populate studentList
}

But I keep getting an error saying I need to check if s if null before I use it.

Student is a class which is made up of a string name, string address, int id


问:
Cant Get a result form random.shuffle in python
I have never had this problem before but when i try and shuffle a list i get a return of 'None'

```<code>import random
c=[1,4,67,3]
c=random.shuffle(c)
print c
</code>```

The print statement returns 'None' and i dont know why, I have looked around for an answer to this problem but there doesent seem to be anything. I hope i am not making an obvious mistake.

答:
Try like this

import random
c=[1,4,67,3]
random.shuffle(c)
print c

Body:
I have never had this problem before but when i try and shuffle a list i get a return of 'None'

import random
c=[1,4,67,3]
c=random.shuffle(c)
print c

The print statement returns 'None' and i dont know why, I have looked around for an answer to this problem but there doesent seem to be anything. I hope i am not making an obvious mistake.


问:
How to make columns in table sortable in both ways using ReactJS
I am building a simple app in ReactJS that works with a JSON array by calling a certain API. I am then populating the results of the array in a table. I now wanted to make the columns of the table sortable. What I ideally want is to have both ascending and descending sorting. Once I click on the header when it is sorted ascending, it should sort descending and vice-versa. Here is my code.</p>

```<code>class ParentComponent extends Component {
constructor(props) {
 super(props);
 this.state = { data: [] };
}

componentDidMount() {
  fetch("http://hostname:xxxx/yyyy/zzzz")
  .then(function(response) {
    return response.json();
  })
  .then(items => this.setState({ data: items }));
 }

render() {
var newdata = this.state.data;

return (
  <table className="m-table">
    <thead>
      <tr>
        <th>AccountName</th>
        <th>ContractValue</th>
      </tr>
    </thead>
    <tbody>
      {newdata.map(function(account, index) {
        return (
          <tr key={index} data-item={account}>
            <td data-title="Account">{account.accountname}</td>
            <td data-title="Value">{account.negotiatedcontractvalue}</td>
          </tr>
        );
      })}
    </tbody>
  </table>
  );
 }
}

export default ParentComponent;
</code>```

答:
You can add a sort property to your state with column and direction properties:

```<code>state = {
  data: [],
  sort: {
    column: null,
    direction: 'desc',
  },
};
</code>```

Of course you should also have a sort handler like so:

```<code>onSort = (column) => (e) => {
  const direction = this.state.sort.column ? (this.state.sort.direction === 'asc' ? 'desc' : 'asc') : 'desc';
  const sortedData = this.state.data.sort((a, b) => {
    if (column === 'accountName') {
      const nameA = a.accountName.toUpperCase(); // ignore upper and lowercase
      const nameB = b.accountName.toUpperCase(); // ignore upper and lowercase
      if (nameA < nameB) {
        return -1;
      }
      if (nameA > nameB) {
        return 1;
      }

      // names must be equal
      return 0;
    } else {
      return a.contractValue - b.contractValue;
    }
  });

  if (direction === 'desc') {
    sortedData.reverse();
  }

  this.setState({
    data: sortedData,
    sort: {
      column,
      direction,
    }
  });
};
</code>```

I got the sorting from MDN.

Here's a sample pen: https://codepen.io/anon/pen/xrGJKv

Body:
I am building a simple app in ReactJS that works with a JSON array by calling a certain API. I am then populating the results of the array in a table. I now wanted to make the columns of the table sortable. What I ideally want is to have both ascending and descending sorting. Once I click on the header when it is sorted ascending, it should sort descending and vice-versa. Here is my code.

class ParentComponent extends Component {
constructor(props) {
 super(props);
 this.state = { data: [] };
}

componentDidMount() {
  fetch("http://hostname:xxxx/yyyy/zzzz")
  .then(function(response) {
    return response.json();
  })
  .then(items => this.setState({ data: items }));
 }

render() {
var newdata = this.state.data;

return (

        AccountName
        ContractValue

      {newdata.map(function(account, index) {
        return (

            {account.accountname}
            {account.negotiatedcontractvalue}

        );
      })}

  );
 }
}

export default ParentComponent;

Body:
You can add a sort property to your state with column and direction properties:

state = {
  data: [],
  sort: {
    column: null,
    direction: 'desc',
  },
};

Of course you should also have a sort handler like so:

onSort = (column) => (e) => {
  const direction = this.state.sort.column ? (this.state.sort.direction === 'asc' ? 'desc' : 'asc') : 'desc';
  const sortedData = this.state.data.sort((a, b) => {
    if (column === 'accountName') {
      const nameA = a.accountName.toUpperCase(); // ignore upper and lowercase
      const nameB = b.accountName.toUpperCase(); // ignore upper and lowercase
      if (nameA < nameB) {
        return -1;
      }
      if (nameA > nameB) {
        return 1;
      }

      // names must be equal
      return 0;
    } else {
      return a.contractValue - b.contractValue;
    }
  });

  if (direction === 'desc') {
    sortedData.reverse();
  }

  this.setState({
    data: sortedData,
    sort: {
      column,
      direction,
    }
  });
};

I got the sorting from MDN.

Here's a sample pen: https://codepen.io/anon/pen/xrGJKv


问:
Superscript in Crystal reports formula
I am trying to make part of array text into superscript inside my formula field. I tried rendering the field as HTML with a  tag but it seems it is not supported. Following did not work

```<code>numberVar array arr:=["1<sup>st</sup>"];
</code>```

Is there a way round this problem ?

答:
As far as I'm aware, Crystal Reports doesn't support superscript at all, not for HTML (see here for supported tags if interested), or for RTF.

Off the top of my head, you would need two separate textboxes to achieve this effect, with the "st" text at a higher Y-position than the "1" to get "1st".

Title: Superscript in Crystal reports formula

Body:
I am trying to make part of array text into superscript inside my formula field. I tried rendering the field as HTML with a  tag but it seems it is not supported. Following did not work

numberVar array arr:=["1st"];

Is there a way round this problem ?


问:
How to do multiple replaces on the same line in vi?
In vi, I will typically do a "confirm" find and replace just by using this: :%s/find/replace/c.

Well, the problem with that is when I have some code like this:

```<code>#this will find this and won't find the next one.
</code>```

Then it asks me to confirm if I want to replace the first instance of find, but it skips over the second one for some reason.

How do I make it prompt me for every occurrence of the word find rather than only the first one in each line?

答:
Use the global parameter g

:%s/find/replace/gc

Body:
In vi, I will typically do a "confirm" find and replace just by using this: :%s/find/replace/c.

Well, the problem with that is when I have some code like this:

#this will find this and won't find the next one.

Then it asks me to confirm if I want to replace the first instance of find, but it skips over the second one for some reason.

How do I make it prompt me for every occurrence of the word find rather than only the first one in each line?


问:
Can't send JSON String to server in API 25
Hey I want to send JSON string to server and get the response in JSON array ,

Please help me figure out what to use to send the json array and get the response back in json format my code is

```<code>public class Welcome extends AppCompatActivity {
    private static final String LOGIN_REQUEST_URL = "http://demo4u.org/leaveapp/ws/login.php";
    JSONObject request = new JSONObject();

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

        final EditText user_email = (EditText) findViewById(R.id.username);
        final EditText user_password = (EditText) findViewById(R.id.password);
        final Button signin = (Button) findViewById(R.id.signin);
        signin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String uname = user_email.getText().toString();
                final String pass = user_password.getText().toString();
                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            try {
                                JSONObject jsonresponse = new JSONObject(response);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            try {
                                request.put("user_email", uname);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            try {
                                request.put("user_password", pass);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            final TextView show = (TextView) findViewById(R.id.res);
                            String jsonstring = request.toString();
                            JsonObjectRequest jsonobjreq = new JsonObjectRequest(
                                    Method.POST, LOGIN_REQUEST_URL, jsonstring,
                                    new Response.Listener<JSONObject>() {
                                        @Override
                                        public void onResponse(JSONObject response) {
                                            //Log.d(Tag, toString());
                                            Toast.makeText(Welcome.this,"Volley Error",Toast.LENGTH_LONG).show();
                                            show.setText(response.toString());
                                        }
                                    }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    //Toast.makeText(Welcome.this,"Volley Error",Toast.LENGTH_LONG).show();
                                    VolleyLog.d(Tag, "Error : " + error.getMessage());
                                }
                            }) {
                                @Override
                                public Map<String, String> getHeaders() throws AuthFailureError {
                                    HashMap<String, String> headers = new HashMap<String, String>();
                                    headers.put("Content-Type", "application/json; charset=utf-8");
                                    return headers;
                                }

                            };

                        } catch (JSONException e) {
                        }
</code>```

Please write the code that I have to replace with the above code.

答:
You can pass your uname and pass to this method and get the jsonString back.</p>

```<code>private String test(String uname, String pass) {
    try {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("user_email", uname);
        jsonObject.put("user_password", pass);
        jsonArray.put(jsonObject);
        return jsonArray.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return "";
    }
}
</code>```

Body:
Hey I want to send JSON string to server and get the response in JSON array ,

Please help me figure out what to use to send the json array and get the response back in json format my code is

public class Welcome extends AppCompatActivity {
    private static final String LOGIN_REQUEST_URL = "http://demo4u.org/leaveapp/ws/login.php";
    JSONObject request = new JSONObject();

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

        final EditText user_email = (EditText) findViewById(R.id.username);
        final EditText user_password = (EditText) findViewById(R.id.password);
        final Button signin = (Button) findViewById(R.id.signin);
        signin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String uname = user_email.getText().toString();
                final String pass = user_password.getText().toString();
                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            try {
                                JSONObject jsonresponse = new JSONObject(response);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            try {
                                request.put("user_email", uname);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            try {
                                request.put("user_password", pass);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            final TextView show = (TextView) findViewById(R.id.res);
                            String jsonstring = request.toString();
                            JsonObjectRequest jsonobjreq = new JsonObjectRequest(
                                    Method.POST, LOGIN_REQUEST_URL, jsonstring,
                                    new Response.Listener<JSONObject>() {
                                        @Override
                                        public void onResponse(JSONObject response) {
                                            //Log.d(Tag, toString());
                                            Toast.makeText(Welcome.this,"Volley Error",Toast.LENGTH_LONG).show();
                                            show.setText(response.toString());
                                        }
                                    }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    //Toast.makeText(Welcome.this,"Volley Error",Toast.LENGTH_LONG).show();
                                    VolleyLog.d(Tag, "Error : " + error.getMessage());
                                }
                            }) {
                                @Override
                                public Map<String, String> getHeaders() throws AuthFailureError {
                                    HashMap<String, String> headers = new HashMap<String, String>();
                                    headers.put("Content-Type", "application/json; charset=utf-8");
                                    return headers;
                                }

                            };

                        } catch (JSONException e) {
                        }

Please write the code that I have to replace with the above code.

Body:
You can pass your uname and pass to this method and get the jsonString back.

private String test(String uname, String pass) {
    try {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("user_email", uname);
        jsonObject.put("user_password", pass);
        jsonArray.put(jsonObject);
        return jsonArray.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return "";
    }
}


问:
Find a key in array of object
The input is JSON array of object.

```<code>[
    {
        "name": "JOHN",
        "age": "90",
        "ID": "123",
        "country": "UK",
        "email": "john@test.com"
    }, {
        "name": "PETER",
        "age": "10",
        "ID": "456",
        "country": "",
    }
]
</code>```

What is the best way in Javascript to find a key in all of the arrays and return ok if it exists. For example, does "name" exist? Yes, JOHN and PETER. Does "email" exist? Yes, john@test.com. Does "city" exist? No.

Thank you for giving tips!

答:
```<code>var arr=[
          {
              "name": "JOHN",
              "age": "90",
              "ID": "123",
              "country": "UK",
              "email": "john@test.com"
          }, {
              "name": "PETER",
              "age": "10",
              "ID": "456",
              "country": "",
          }
        ];
var fu=function(arr,prop){
   return $.map(arr,(v,k)=>{if(v.hasOwnProperty(prop)){return arr[k][prop]}});
}
console.log(fu(arr,"ID"));
console.log(fu(arr,"name"));
console.log(fu(arr,"email"));
</code>```

Title: Find a key in array of object

Body:
The input is JSON array of object.

[
    {
        "name": "JOHN",
        "age": "90",
        "ID": "123",
        "country": "UK",
        "email": "john@test.com"
    }, {
        "name": "PETER",
        "age": "10",
        "ID": "456",
        "country": "",
    }
]

What is the best way in Javascript to find a key in all of the arrays and return ok if it exists. For example, does "name" exist? Yes, JOHN and PETER. Does "email" exist? Yes, john@test.com. Does "city" exist? No.

Thank you for giving tips!


答:
you have to clear first that session is started on top.

```<code>session_start();
</code>```

then assign a value to the session. i assuming that your variables have some values. then,

```<code>$_SESSION['StudentID']= $studentID ;
$_SESSION['OfferingID']= $offeringID;
$_SESSION['email']=$email;
</code>```

Now if you wants to print that session values using print_r, i am printing studentid here,

```<code>print_r($_SESSION['StudentID']);
</code>```

if you wants to print full session,

```<code>print_r($_SESSION);
</code>```

Title: printing session variables in php

Body:
How do I print these sessions using the print_r function.

I'm new to php.

Theses are the sessions.

$studentID = $_SESSION['StudentID'];
$offeringID=$_SESSION['OfferingID'];
$email=$_SESSION['email'];

Any help would be very much appreciated.

Body:
you have to clear first that session is started on top.

session_start();

then assign a value to the session. i assuming that your variables have some values. then,

$_SESSION['StudentID']= $studentID ;
$_SESSION['OfferingID']= $offeringID;
$_SESSION['email']=$email;

Now if you wants to print that session values using print_r, i am printing studentid here,

print_r($_SESSION['StudentID']);

if you wants to print full session,

print_r($_SESSION);


答:
in Form1

you should add new List < Student >(); when define studentList_Form1

```<code>public List<Student> studentList_Form1 = new List<Student>();

public List<Student> StudentList_Form1
{
    get
    {
       return studentList_Form1;
    }
}
</code>```

Title: Adding items from one list to another list in another form in c#

Body:
in Form1

you should add new List < Student >(); when define studentList_Form1

public List<Student> studentList_Form1 = new List<Student>();

public List<Student> StudentList_Form1
{
    get
    {
       return studentList_Form1;
    }
}


问:
In what order are projects returned using ActiveSolutionProjects?
Im using this code, inside a project template wizard.

```<code>DTE dte = project.DTE;
VSProject vsProj = (VSProject)project.Object;

Array projects = (Array)dte.ActiveSolutionProjects;
Project activeProject = (Project)projects.GetValue(0);
</code>```

But im curious in what order the projects are returned?
The code above is running just after the project is created, in the

```<code>public void ProjectFinishedGenerating(Project project)
</code>```

In what order does the projects get returned?
My goal is to get the newest project, will GetValue(0) do that?

答:
I looked at this a while back and the order seems to be non-determinstic.

GetValue(0) is the active project which might not be newest project.

To find the newested, you will need to traverse the projects using either the file stamp
on the project file (if saved) plus ranking non-saved ones higher as higher.

Body:
Im using this code, inside a project template wizard.

DTE dte = project.DTE;
VSProject vsProj = (VSProject)project.Object;

Array projects = (Array)dte.ActiveSolutionProjects;
Project activeProject = (Project)projects.GetValue(0);

But im curious in what order the projects are returned?
The code above is running just after the project is created, in the

public void ProjectFinishedGenerating(Project project)

In what order does the projects get returned?
My goal is to get the newest project, will GetValue(0) do that?


问:
how to create captcha in identityServer3 login pages
I want to use captcha in my login Pages in identityServer3, How do i that?
Is there a sample source ?
I Try To Use Google reCaptcha but it dose not work.
Please Help Me</p>

答:
The better question is how to customize the login screen?
see the documentation on customizing views

The views in IdentityServer can be customized in one of two ways: 1)
  Customize the HTML templates provided by the DefaultViewService, or if
  more control is needed 2) define a custom IViewService

Implement a custom IViewService to change the full layout.
Also if you want to change only the login page, add your custom html that implements the same angular logic as the existing login page and adding it to a folder named templates with a file name of _login.html.
If you want to modify the layout (the headers) then you need to do the same this time naming the file _Layout.html.
This is all expalined in the documentation, with the above listed as "Replacing partial views".


问:
How to calculate days to months, years, days in Swift?
I need to find months, years, days from given days. For example, 370 days, I need to convert to 1 year 0 month & 5 days. Days can be rounded off to the nearest month. For example, if days are less than 15, that should go to 0 month. If its more than 15 days, now that should go to 1 month</p>

答:
```<code>func numberOfDaysInCurrentYear() -> Int {
    let calendar = Calendar.init(identifier: .gregorian)
    let interval = calendar.dateInterval(of: .year, for: Date.init())!
    let days = calendar.dateComponents([.day], from: interval.start, to: interval.end).day!
    return days
}
</code>```


问:
How call a function in node js?
I'm having a problem with node JS.

Basically,I Have this function :

```<code>let getImageName = function(query,callback){
  Images.getImageById(query,function(err,image){
    return image.filename;
  });
}
</code>```

But when i called this,the console.log() print undefined,and I know that the function getImageName is working.

```<code>app.get('/api/books/:_id', function(req, res){
Book.getBookById(req.params._id, function(err,book){
    if(err){
        throw err;
    }
    console.log(getImageName(book.cover));
});
});
</code>```

答:
You are trying to return a value from a callback to an asynchronous function. They don't work that way. You are treating getImageById() like it is synchronous but getImageById() is asynchronous (which is possible to infer from the way it takes a callback).

```<code>Images.getImageById(query,function(err,image){
    return image.filename;
  });
</code>```

There are many solutions depending on your use case. The easiest could be to move the console.log() to inside that callback. (But if you then change the console.log() to a return statement, you will have the same problem all over again.)

If this is all confusing, there's a short explanation at https://docs.nodejitsu.com/articles/getting-started/control-flow/what-are-callbacks/.

Title: How call a function in node js?

Body:
I'm having a problem with node JS.

Basically,I Have this function :

let getImageName = function(query,callback){
  Images.getImageById(query,function(err,image){
    return image.filename;
  });
}

But when i called this,the console.log() print undefined,and I know that the function getImageName is working.

app.get('/api/books/:_id', function(req, res){
Book.getBookById(req.params._id, function(err,book){
    if(err){
        throw err;
    }
    console.log(getImageName(book.cover));
});
});

Body:
You are trying to return a value from a callback to an asynchronous function. They don't work that way. You are treating getImageById() like it is synchronous but getImageById() is asynchronous (which is possible to infer from the way it takes a callback).

Images.getImageById(query,function(err,image){
    return image.filename;
  });

There are many solutions depending on your use case. The easiest could be to move the console.log() to inside that callback. (But if you then change the console.log() to a return statement, you will have the same problem all over again.)

If this is all confusing, there's a short explanation at https://docs.nodejitsu.com/articles/getting-started/control-flow/what-are-callbacks/.


问:
In .net, is there an opposite function to Server.HTMLEncode()?
.Net's Server.HTMLEncode() is the very helpful function that takes an HTML string and replaces special characters with their entity equivalents - "<" becomes &lt ; and so forth.

Is there a (built-in) function that does the reverse?  There doesn't seem to be, and I am incredulous.  While I could certainly write my own (and have in the past) Server.HTMLEncode has all kinds of cool handling for different string encodings and high-level unicode characters that I would really not have crash my hand-rolled decoder in a year's time.

What do other people do when they need the plain HTML back?

Update:
To answer the first batch of questions, I present the MSDN article on the
Server object, which has Encode but no Decode...  I'm as amazed as anyone.

Update2: as several alert readers have pointed out, the docs I was looking at were for classic ASP, not ASP.Net.  Thanks guys, that's an important MSDN safety tip.

LastEditorDisplayName: Eddie

Body: HttpServerUtility.HtmlDecode

OwnerDisplayName: jlewicki


问:
How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found
So I'm now desperate in finding a fix for this. I'm compiling a shared library .so in Ubuntu 32 bit (Have tried doing it under Debian and Ubuntu 64 bit, but none worked either)

I keep getting: /usr/lib/libstdc++.so.6: version ``GLIBCXX_3.4.15' not found every time I try to load my plugin.

Here's how I'm getting this error:

Install latest Ubuntu 32 bit

sudo apt-get install build-essential

Compile & load my plugin (.so)

Here are some links which I found and tried, but none worked for me:

(My old question: I somehow got it fixed a few days after posting this question, but I can't remember how exactly I did it)

My Question

Another user with the same problem

And another

I see some people fixed it by moving libstdc++(i think) to some directory and then pointing or linking idk what to that directory, but that just puzzled me.

Anyone know a fix?

(Edit:)
- Running: strings /usr/lib/libstdc++.so.6 | grep GLIBC in terminal gives me: strings '/usr/lib/libstdc++.so.6': No such file. Could that be the problem? And if so, how do I install this library?

(Edit2:) Anyone else know of a solution?

(Edit3) Still in need of a solution. is there a way to see on which distro a shared library was compiled on? I know I once compiled this same library a while ago, but can't remember!!

(Edit4) ldd my_lib_.so gives me:

```<code>    linux-gate.so.1 =>  (0xb77d7000)
    libstdc++.so.6 => /usr/lib/i386-linux-gnu/libstdc++.so.6 (0xb76c1000)
    libgcc_s.so.1 => /lib/i386-linux-gnu/libgcc_s.so.1 (0xb76a4000)
    libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xb74fa000)
    libm.so.6 => /lib/i386-linux-gnu/libm.so.6 (0xb74ce000)
    /lib/ld-linux.so.2 (0xb77d8000)
</code>```

ldd program_im_loading_so_into gives me:

```<code>    linux-gate.so.1 =>  (0xb77d8000)
    libdl.so.2 => /lib/i386-linux-gnu/libdl.so.2 (0xb77c0000)
    libpthread.so.0 => /lib/i386-linux-gnu/libpthread.so.0 (0xb77a5000)
    libstdc++.so.6 => /usr/lib/i386-linux-gnu/libstdc++.so.6 (0xb76bb000)
    libm.so.6 => /lib/i386-linux-gnu/libm.so.6 (0xb768f000)
    libgcc_s.so.1 => /lib/i386-linux-gnu/libgcc_s.so.1 (0xb7672000)
    libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xb74c9000)
    /lib/ld-linux.so.2 (0xb77d9000)
</code>```

running strings /usr/lib/i386-linux-gnu/libstdc++.so.6 | grep GLIBCXX gives me:

```<code>GLIBCXX_3.4
GLIBCXX_3.4.1
GLIBCXX_3.4.2
GLIBCXX_3.4.3
GLIBCXX_3.4.4
GLIBCXX_3.4.5
GLIBCXX_3.4.6
GLIBCXX_3.4.7
GLIBCXX_3.4.8
GLIBCXX_3.4.9
GLIBCXX_3.4.10
GLIBCXX_3.4.11
GLIBCXX_3.4.12
GLIBCXX_3.4.13
GLIBCXX_3.4.14
GLIBCXX_3.4.15
GLIBCXX_3.4.16
GLIBCXX_3.4.17
GLIBCXX_3.4.18
GLIBCXX_3.4.19
GLIBCXX_DEBUG_MESSAGE_LENGTH
</code>```

and finally here's my gcc version:

```<code>`gcc version 4.6.4 (Ubuntu/Linaro 4.6.4-1ubuntu1~12.04)`
</code>```

答:
this problem can be solved by installing the latest libstdc++.</p>

```<code>$ sudo add-apt-repository ppa:ubuntu-toolchain-r/test
$ sudo apt-get update
$ sudo apt-get install libstdc++6-7-dbg
</code>```

Body:
So I'm now desperate in finding a fix for this. I'm compiling a shared library .so in Ubuntu 32 bit (Have tried doing it under Debian and Ubuntu 64 bit, but none worked either)

I keep getting: /usr/lib/libstdc++.so.6: version ``GLIBCXX_3.4.15' not found every time I try to load my plugin.

Here's how I'm getting this error:

Install latest Ubuntu 32 bit

sudo apt-get install build-essential

Compile & load my plugin (.so)

Here are some links which I found and tried, but none worked for me:

(My old question: I somehow got it fixed a few days after posting this question, but I can't remember how exactly I did it)

My Question

Another user with the same problem

And another

I see some people fixed it by moving libstdc++(i think) to some directory and then pointing or linking idk what to that directory, but that just puzzled me.

Anyone know a fix?

(Edit:)
- Running: strings /usr/lib/libstdc++.so.6 | grep GLIBC in terminal gives me: strings '/usr/lib/libstdc++.so.6': No such file. Could that be the problem? And if so, how do I install this library?

(Edit2:) Anyone else know of a solution?

(Edit3) Still in need of a solution. is there a way to see on which distro a shared library was compiled on? I know I once compiled this same library a while ago, but can't remember!!

(Edit4) ldd my_lib_.so gives me:

    linux-gate.so.1 =>  (0xb77d7000)
    libstdc++.so.6 => /usr/lib/i386-linux-gnu/libstdc++.so.6 (0xb76c1000)
    libgcc_s.so.1 => /lib/i386-linux-gnu/libgcc_s.so.1 (0xb76a4000)
    libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xb74fa000)
    libm.so.6 => /lib/i386-linux-gnu/libm.so.6 (0xb74ce000)
    /lib/ld-linux.so.2 (0xb77d8000)

ldd program_im_loading_so_into gives me:

    linux-gate.so.1 =>  (0xb77d8000)
    libdl.so.2 => /lib/i386-linux-gnu/libdl.so.2 (0xb77c0000)
    libpthread.so.0 => /lib/i386-linux-gnu/libpthread.so.0 (0xb77a5000)
    libstdc++.so.6 => /usr/lib/i386-linux-gnu/libstdc++.so.6 (0xb76bb000)
    libm.so.6 => /lib/i386-linux-gnu/libm.so.6 (0xb768f000)
    libgcc_s.so.1 => /lib/i386-linux-gnu/libgcc_s.so.1 (0xb7672000)
    libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xb74c9000)
    /lib/ld-linux.so.2 (0xb77d9000)

running strings /usr/lib/i386-linux-gnu/libstdc++.so.6 | grep GLIBCXX gives me:

GLIBCXX_3.4
GLIBCXX_3.4.1
GLIBCXX_3.4.2
GLIBCXX_3.4.3
GLIBCXX_3.4.4
GLIBCXX_3.4.5
GLIBCXX_3.4.6
GLIBCXX_3.4.7
GLIBCXX_3.4.8
GLIBCXX_3.4.9
GLIBCXX_3.4.10
GLIBCXX_3.4.11
GLIBCXX_3.4.12
GLIBCXX_3.4.13
GLIBCXX_3.4.14
GLIBCXX_3.4.15
GLIBCXX_3.4.16
GLIBCXX_3.4.17
GLIBCXX_3.4.18
GLIBCXX_3.4.19
GLIBCXX_DEBUG_MESSAGE_LENGTH

and finally here's my gcc version:

`gcc version 4.6.4 (Ubuntu/Linaro 4.6.4-1ubuntu1~12.04)`

Body:
this problem can be solved by installing the latest libstdc++.

$ sudo add-apt-repository ppa:ubuntu-toolchain-r/test
$ sudo apt-get update
$ sudo apt-get install libstdc++6-7-dbg


问:
Format issue while uploading Jpg file with NodeJS Multer module
I'm using Multer to upload jpg file from Postman to a node.js back-end.

I assume the "upload" goes well because the image is located at the right place with the right name and the right size after the POST request

Unfortunately, when I try to open the image file it doesn't open as a jpg image even though the extension is .jpg
I used checkFileType website and apparently, the file type becomes application/octet-stream after the upload.

I didn't specify any headers in the request.

Here is my Postman setup

Here is the response

Here is the code in the Node API side

```<code>var localWorkLocation = '/Users/noste/CarFixer/Pictures/';

exports.createBinary = function (req, res) {
        var location = localWorkLocation + req.params.platenumber;
        var storageOptions = multer.diskStorage({
                        destination: function (req, file, callback) {
                            mkdirp(location, err => callback(err, location));
                            callback(null, location);
                        },
                        filename: function (req, file, callback) {
                            //if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
                            //        return callback(new Error('Only image files are allowed!'), false);
                            //}
                            callback(null, file.originalname);
                        },
        });
        var upload = multer({storage : storageOptions}).single('picture');

        upload(req, res, function(err){
            console.log(req.file);
            if(err) {
                return res.end(err.message);
            }

            res.send(req.file);
        });
};
</code>```

I've tried to upload a .txt file and it's still readable after upload.
Is there a place where I need to specify that I want to keep the jpg format ?

答:
here's the storage configuration u need .. change the naming according to your code

```<code> var path = require('path');
 var storage = multer.diskStorage({
            destination: function(req, file, callback) {
                callback(null, './uploads');
            },

            filename: function(req, file, callback) {
                var fname = file.fieldname + '-' + Date.now() + path.extname(file.originalname);

                callback(null, fname);

            }
        });
</code>```

And here's another answer for multiple files upload

Body:
I'm using Multer to upload jpg file from Postman to a node.js back-end.

I assume the "upload" goes well because the image is located at the right place with the right name and the right size after the POST request

Unfortunately, when I try to open the image file it doesn't open as a jpg image even though the extension is .jpg
I used checkFileType website and apparently, the file type becomes application/octet-stream after the upload.

I didn't specify any headers in the request.

Here is my Postman setup

Here is the response

Here is the code in the Node API side

var localWorkLocation = '/Users/noste/CarFixer/Pictures/';

exports.createBinary = function (req, res) {
        var location = localWorkLocation + req.params.platenumber;
        var storageOptions = multer.diskStorage({
                        destination: function (req, file, callback) {
                            mkdirp(location, err => callback(err, location));
                            callback(null, location);
                        },
                        filename: function (req, file, callback) {
                            //if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
                            //        return callback(new Error('Only image files are allowed!'), false);
                            //}
                            callback(null, file.originalname);
                        },
        });
        var upload = multer({storage : storageOptions}).single('picture');

        upload(req, res, function(err){
            console.log(req.file);
            if(err) {
                return res.end(err.message);
            }

            res.send(req.file);
        });
};

I've tried to upload a .txt file and it's still readable after upload.
Is there a place where I need to specify that I want to keep the jpg format ?

Body:
here's the storage configuration u need .. change the naming according to your code

 var path = require('path');
 var storage = multer.diskStorage({
            destination: function(req, file, callback) {
                callback(null, './uploads');
            },

            filename: function(req, file, callback) {
                var fname = file.fieldname + '-' + Date.now() + path.extname(file.originalname);

                callback(null, fname);

            }
        });

And here's another answer for multiple files upload


问:
Creating a mother/child program in python
My original concept is that i would have a mother program controlling the child programs installed on some (possible up to 5) computers. The child programs job would be to take commands from the mother program and execute those commands on their host computers. I know for this project my program would need to deal with ip addresses. I also know it will have to interact with the windows command promt/powershell. If anyone can give me advice on where to start it would be very much appreciated! Google doesnt return much on this topic for some reason. Thanks people!</p>

答:
Well the easiest thing would be when the host of your mother program has a fixed IP or DNS.

Then your clients could simply connect back to your mother program.

It sounds a bit like a reverse shell you want to program here and I want to mention that according to German Law already the programming of this is illegal. Probably this is the reason why you don't find much about the topic.


问:
Fastest Way for Comparing Strings Python
Situation: Comparing strings in fileA with pre-defined strings in fileB. Example of said function in my code:

```<code>string = open('fileA', 'r')
stringlist = open('fileB', 'r')

//compare the strings
for i in string:
    for j in stringlist:
        if i == j:
            print("Same String found!" + i + " " + j)
</code>```

Problem: In my actual program, string contains more than 200 strings, while stringlist is a file with more than 50,000 strings. The nested for loop, as I have read, is slow as a comparison function.

Question: What is the fastest way to compare the two files' content?

Additional information 1: Both files are CSV files, and are opened in my program as CSV-delimited.

Additional information 2: Strings are md5 hashes (32 characters).

Additional information 3: I am open to other ways to store the strings, i.e. Compare the strings on-the-fly instead of saving it to fileA.

Additional information 4: I am also open to other methods or modules that I can use (i.e.: Threading/parallel processing) -- speed is the key here.

答:
If you are okay with not printing duplicates, using set.intersection should be really fast:</p>

```<code>list1 = ["hello", "world", "foo"]
list2 = ["foo", "bar", "baz"]

set(list1).intersection(list2)
# {'foo'}
</code>```

Body:
Situation: Comparing strings in fileA with pre-defined strings in fileB. Example of said function in my code:

string = open('fileA', 'r')
stringlist = open('fileB', 'r')

//compare the strings
for i in string:
    for j in stringlist:
        if i == j:
            print("Same String found!" + i + " " + j)

Problem: In my actual program, string contains more than 200 strings, while stringlist is a file with more than 50,000 strings. The nested for loop, as I have read, is slow as a comparison function.

Question: What is the fastest way to compare the two files' content?

Additional information 1: Both files are CSV files, and are opened in my program as CSV-delimited.

Additional information 2: Strings are md5 hashes (32 characters).

Additional information 3: I am open to other ways to store the strings, i.e. Compare the strings on-the-fly instead of saving it to fileA.

Additional information 4: I am also open to other methods or modules that I can use (i.e.: Threading/parallel processing) -- speed is the key here.

Body:
If you are okay with not printing duplicates, using set.intersection should be really fast:

list1 = ["hello", "world", "foo"]
list2 = ["foo", "bar", "baz"]

set(list1).intersection(list2)
# {'foo'}