问:
Input validation in do-while
I'm having a problem with the input error.My input is validated but my error message "Invalid Range. Please Enter Range 0-100:" is not showing if there's invalid input.

Here's an example:

```<code>Please Enter Grade 1: 101 (It does not accept input)
Please Enter Grade 1: 321 (It does not accept input)
</code>```

Instead of showing:

```<code>Please Enter Grade 1: 101 (It does not accept input)

Invalid Rage. Please Enter Range 0-100.
Please Enter Grade 1:
</code>```

Here's My Code:

```<code>for(vector<double>::size_type i = 0; i < 15; i++)
  {
    do
    {
         cout << "Please Enter Grade "<< i + 1 <<": " << flush;
            cin >> gradesVector[i];
        }
        while(gradesVector[i] < 0.0 || gradesVector[i] > 100.0);
        {
            cout << "Invalid Rage. Please Enter Range 0-100:\n";
                cout << "Please Enter Grade "<< i + 1 <<": " << flush;
                    cin >> gradesVector[i];
         }
}
</code>```

答:
Your while() condition should be

while(gradesVector[i] < 0.0 || gradesVector[i] > 100.0) and use this code

```<code>for(vector<double>::size_type i = 0; i < 15; i++)
  {
   int c=0;
    do
    {
        if(c!=0)   //checking that we didnt entered loop for first time
          cout << "Invalid Rage. Please Enter Range 0-100:\n";

           cout << "Please Enter Grade "<< i + 1 <<": " << flush;
           cin >> gradesVector[i];
           c++;
     }
        while(gradesVector[i] < 0.0 || gradesVector[i] > 100.0);

}
</code>```

Title: Input validation in do-while

Body:
I'm having a problem with the input error.My input is validated but my error message "Invalid Range. Please Enter Range 0-100:" is not showing if there's invalid input.

Here's an example:

Please Enter Grade 1: 101 (It does not accept input)
Please Enter Grade 1: 321 (It does not accept input)

Instead of showing:

Please Enter Grade 1: 101 (It does not accept input)

Invalid Rage. Please Enter Range 0-100.
Please Enter Grade 1:

Here's My Code:

for(vector<double>::size_type i = 0; i < 15; i++)
  {
    do
    {
         cout << "Please Enter Grade "<< i + 1 <<": " << flush;
            cin >> gradesVector[i];
        }
        while(gradesVector[i] < 0.0 || gradesVector[i] > 100.0);
        {
            cout << "Invalid Rage. Please Enter Range 0-100:\n";
                cout << "Please Enter Grade "<< i + 1 <<": " << flush;
                    cin >> gradesVector[i];
         }
}

Body:
Your while() condition should be

while(gradesVector[i] < 0.0 || gradesVector[i] > 100.0) and use this code

for(vector<double>::size_type i = 0; i < 15; i++)
  {
   int c=0;
    do
    {
        if(c!=0)   //checking that we didnt entered loop for first time
          cout << "Invalid Rage. Please Enter Range 0-100:\n";

           cout << "Please Enter Grade "<< i + 1 <<": " << flush;
           cin >> gradesVector[i];
           c++;
     }
        while(gradesVector[i] < 0.0 || gradesVector[i] > 100.0);

}


来源: stackexchange

问:
How to run the same test-case for different classes?
I have several classes that share some invariants and have a common interface, and I would like to run automatically the same test for each of them.

As an example, suppose I have several classes that implement different approaches for partitioning a data-set. The common invariant here would be, that for all of these classes the union over all partitions should equal the original data-set.

What I currently have looks something like this:

```<code>class PartitionerInvariantsTests(unittest.TestCase):
    def setUp(self):
        self.testDataSet = range(100) # create test-data-set

    def impl(self, partitioner):
        self.assertEqual(self.testDataSet,
                         chain.from_iterable(partitioner(self.testDataSet))
</code>```

Then I add a different function that calls impl for each of the classes I want to test with an instance of that class. The problem with this becomes apparent when doing this for more than one test-function. Suppose I have 5 test-functions and 5 classes I want to test. This would make 25 functions that look almost identical for invoking all the tests.

Another approach I was thinking about was to implement the template as a super-class, and then create a sub-class for each of the classes I want to test. The sub-classes could provide a function for instantiating the class. The problem with that is that the default test-loader would consider the (unusable) base-class a valid test-case and try to run it, which would fail.

So, what are your suggestions?

P.S.: I am using Python 2.6

答:
You could use multiple inheritance.</p>

```<code>class PartitionerInvariantsFixture(object):
    def setUp(self):
        self.testDataSet = range(100) # create test-data-set
        super(PartitionInvariantsFixture, self).setUp()

    def test_partitioner(self):
        TestCase.assertEqual(self.testDataSet,
                     chain.from_iterable(self.partitioner(self.testDataSet))

class MyClassTests(TestCase, PartitionerInvariantsFixture):
    partitioner = Partitioner
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have several classes that share some invariants and have a common interface, and I would like to run automatically the same test for each of them.

As an example, suppose I have several classes that implement different approaches for partitioning a data-set. The common invariant here would be, that for all of these classes the union over all partitions should equal the original data-set.

What I currently have looks something like this:

class PartitionerInvariantsTests(unittest.TestCase):
    def setUp(self):
        self.testDataSet = range(100) # create test-data-set

    def impl(self, partitioner):
        self.assertEqual(self.testDataSet,
                         chain.from_iterable(partitioner(self.testDataSet))

Then I add a different function that calls impl for each of the classes I want to test with an instance of that class. The problem with this becomes apparent when doing this for more than one test-function. Suppose I have 5 test-functions and 5 classes I want to test. This would make 25 functions that look almost identical for invoking all the tests.

Another approach I was thinking about was to implement the template as a super-class, and then create a sub-class for each of the classes I want to test. The sub-classes could provide a function for instantiating the class. The problem with that is that the default test-loader would consider the (unusable) base-class a valid test-case and try to run it, which would fail.

So, what are your suggestions?

P.S.: I am using Python 2.6

Body:
You could use multiple inheritance.

class PartitionerInvariantsFixture(object):
    def setUp(self):
        self.testDataSet = range(100) # create test-data-set
        super(PartitionInvariantsFixture, self).setUp()

    def test_partitioner(self):
        TestCase.assertEqual(self.testDataSet,
                     chain.from_iterable(self.partitioner(self.testDataSet))

class MyClassTests(TestCase, PartitionerInvariantsFixture):
    partitioner = Partitioner

ContentLicense: CC BY-SA 2.5


问:
How to handle UITextField position while typing in Xamarin iOS?
Its very common problem in iOS mobile development and that is while you are done with your UI and It contains too many UITextFields, If you try to input value in UITextFields those are added center bottom of the screen; these fields hides behind the keyboard. How can we get rid of this general problem?</p>

答:
I have used a nuget package to get rid of this problem. I have overrides two methods and initialized code inside these methods.

Download KeyboardHandler and use as following:

```<code>using KeyboardHandler;

public override void ViewWillAppear(bool animated)
{
  base.ViewWillAppear(animated);
  this.yourScrollView.SubscribeKeyboardManaqger();
}

public override void ViewWillDisappear(bool animated)
{
  base.ViewWillDisappear(animated);
  this.yourScrollView.UnsubscribeKeyboardManaqger();
}
</code>```

Body:
I have used a nuget package to get rid of this problem. I have overrides two methods and initialized code inside these methods.

Download KeyboardHandler and use as following:

using KeyboardHandler;

public override void ViewWillAppear(bool animated)
{
  base.ViewWillAppear(animated);
  this.yourScrollView.SubscribeKeyboardManaqger();
}

public override void ViewWillDisappear(bool animated)
{
  base.ViewWillDisappear(animated);
  this.yourScrollView.UnsubscribeKeyboardManaqger();
}


问:
How to get subimage with FreeImage
As stated in the title, I am using FreeImage to load textures in my OpenGL game, but how do I get subimages?

My current code looks like this:

```<code>    FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
    FIBITMAP* dib = nullptr;
    fif = FreeImage_GetFileType(filename, 0);
    if (fif == FIF_UNKNOWN)
        fif = FreeImage_GetFIFFromFilename(filename);
    if (fif == FIF_UNKNOWN)
        return nullptr;

    if (FreeImage_FIFSupportsReading(fif))
        dib = FreeImage_Load(fif, filename);
    if (!dib)
        return nullptr;

    BYTE* pixels = FreeImage_GetBits(dib);
    *width = FreeImage_GetWidth(dib);
    *height = FreeImage_GetHeight(dib);
    *bits = FreeImage_GetBPP(dib);

    int size = *width * *height * (*bits / 8);
    BYTE* result = new BYTE[size];
    memcpy(result, pixels, size);
    FreeImage_Unload(dib);
    return result;
</code>```

What would I need to change to get the subimage (for example a 32x32 area of pixels in the top left corner)?

答:
You can use FreeImage_Copy() to get a subimage of a specified region. Note that FreeImage_Copy() takes left, top, right, bottom and not  x, y, width, height.

```<code>FIBITMAP *image = ...;

int x = 0;
int y = 0;
int width = 32;
int height = 32;

FIBITMAP *subimage = FreeImage_Copy(image, x, y, x + width, y + height);
</code>```

Remember to FreeImage_Unload(subimage) as it is a literal copy of the given image.

If needed you could then save it to a PNG by doing:

```<code>if (FreeImage_Save(FIF_PNG, subimage, "subimage.png"))
    printf("Subimage successfully saved!\n");
else
    printf("Failed saving subimage!\n");
</code>```

Title: How to get subimage with FreeImage

Body:
As stated in the title, I am using FreeImage to load textures in my OpenGL game, but how do I get subimages?

My current code looks like this:

    FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
    FIBITMAP* dib = nullptr;
    fif = FreeImage_GetFileType(filename, 0);
    if (fif == FIF_UNKNOWN)
        fif = FreeImage_GetFIFFromFilename(filename);
    if (fif == FIF_UNKNOWN)
        return nullptr;

    if (FreeImage_FIFSupportsReading(fif))
        dib = FreeImage_Load(fif, filename);
    if (!dib)
        return nullptr;

    BYTE* pixels = FreeImage_GetBits(dib);
    *width = FreeImage_GetWidth(dib);
    *height = FreeImage_GetHeight(dib);
    *bits = FreeImage_GetBPP(dib);

    int size = *width * *height * (*bits / 8);
    BYTE* result = new BYTE[size];
    memcpy(result, pixels, size);
    FreeImage_Unload(dib);
    return result;

What would I need to change to get the subimage (for example a 32x32 area of pixels in the top left corner)?

Body:
You can use FreeImage_Copy() to get a subimage of a specified region. Note that FreeImage_Copy() takes left, top, right, bottom and not  x, y, width, height.

FIBITMAP *image = ...;

int x = 0;
int y = 0;
int width = 32;
int height = 32;

FIBITMAP *subimage = FreeImage_Copy(image, x, y, x + width, y + height);

Remember to FreeImage_Unload(subimage) as it is a literal copy of the given image.

If needed you could then save it to a PNG by doing:

if (FreeImage_Save(FIF_PNG, subimage, "subimage.png"))
    printf("Subimage successfully saved!\n");
else
    printf("Failed saving subimage!\n");


问:
Spring MVC ajax DELETE method 404 error
Help me please with understanding. All done is well, but one method isn't work and I have a 404 error
I have a few requests

```<code>function deleteFunc(id) {
            $.ajax({
                dataType: "json",
                type: "DELETE",
                url: "/BookList.vw/" + id,
                async: true,
                success: function (response) {
                },
                error: function (e) {
                    alert("Book doesn't found");
                }
            });
        }

        function modifyFunc(id) {
            alert(id);
            $.ajax({
                dataType: "json",
                type: "PUT",
                url: "/EditBook.vw",
                data: id,
                success: function (response) {
                },
                error: function (e) {
                    alert('Server problems. You cannot modify this book.');
                }
            });
        }
</code>```

Controller:

```<code>@Controller
@RequestMapping("/BookList.vw")
public class BookListController {

    @Autowired
    private IBookService bookService;

    public String getModelName() {
        return "BookList";
    }

    public BookListController() {
    }

    @RequestMapping(method = RequestMethod.GET)
    protected ModelAndView openMain(Model m) throws Exception {
        m.addAttribute("book", new Book());

        Map<String, Object> model = new HashMap<String, Object>();
        List<Book> books = bookService.listBooks();
        model.put("books", books);

        return new ModelAndView(getModelName(), "model", model);
    }

    @RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
    public ModelAndView delete(@PathVariable int id) throws Exception {
        bookService.removeBook(id);
        return new ModelAndView(getModelName());
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView search(@ModelAttribute Book b) throws Exception {
        List<Book> books = bookService.searchBook(b.getName().trim());
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("books", books);

        return new ModelAndView("BookList", "model", model);
    }
}
</code>```

Search and main method work is good, but I can't understand why I have a Error in DELETE method like this:

```<code>"NetworkError: 404 Not Found - http://localhost:8080/BookList.vw/2"
</code>```

答:
I have same problem with you.I used Spring Boot with Spring Security.By defualt , Spring Security will enable the CSRF Protection, all requests using PATCH, POST, PUT, and/or DELETE will be under protection. So ,the simple way is diseable the  CSRF Protection, like:

```<code>public class SecurityConfig extends WebSecurityConfigurerAdapter {
    ...
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...
        http.csrf().disable();
        ...
    }
    ...
}
</code>```

on the other way, if you want keep CSRF Protection, you should sumbit the CSRF Token is every request.
If you are using JSON, then it is not possible to submit the CSRF token within an HTTP parameter. Instead you can submit the token within a HTTP header. A typical pattern would be to include the CSRF token within your meta tags. An example with a JSP is shown below:

```<code><html>
<head>
    <meta name="_csrf" content="${_csrf.token}"/>
    <!-- default header name is X-CSRF-TOKEN -->
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
    <!-- ... -->
</head>
<!-- ... -->
</code>```

You can then include the token within all your Ajax requests. If you were using jQuery, this could be done with the following:

```<code>$(function () {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
    xhr.setRequestHeader(header, token);
});
});
</code>```

Title: Spring MVC ajax DELETE method 404 error

Body:
Help me please with understanding. All done is well, but one method isn't work and I have a 404 error
I have a few requests

function deleteFunc(id) {
            $.ajax({
                dataType: "json",
                type: "DELETE",
                url: "/BookList.vw/" + id,
                async: true,
                success: function (response) {
                },
                error: function (e) {
                    alert("Book doesn't found");
                }
            });
        }

        function modifyFunc(id) {
            alert(id);
            $.ajax({
                dataType: "json",
                type: "PUT",
                url: "/EditBook.vw",
                data: id,
                success: function (response) {
                },
                error: function (e) {
                    alert('Server problems. You cannot modify this book.');
                }
            });
        }

Controller:

@Controller
@RequestMapping("/BookList.vw")
public class BookListController {

    @Autowired
    private IBookService bookService;

    public String getModelName() {
        return "BookList";
    }

    public BookListController() {
    }

    @RequestMapping(method = RequestMethod.GET)
    protected ModelAndView openMain(Model m) throws Exception {
        m.addAttribute("book", new Book());

        Map<String, Object> model = new HashMap<String, Object>();
        List<Book> books = bookService.listBooks();
        model.put("books", books);

        return new ModelAndView(getModelName(), "model", model);
    }

    @RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
    public ModelAndView delete(@PathVariable int id) throws Exception {
        bookService.removeBook(id);
        return new ModelAndView(getModelName());
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView search(@ModelAttribute Book b) throws Exception {
        List<Book> books = bookService.searchBook(b.getName().trim());
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("books", books);

        return new ModelAndView("BookList", "model", model);
    }
}

Search and main method work is good, but I can't understand why I have a Error in DELETE method like this:

"NetworkError: 404 Not Found - http://localhost:8080/BookList.vw/2"

Body:
I have same problem with you.I used Spring Boot with Spring Security.By defualt , Spring Security will enable the CSRF Protection, all requests using PATCH, POST, PUT, and/or DELETE will be under protection. So ,the simple way is diseable the  CSRF Protection, like:

public class SecurityConfig extends WebSecurityConfigurerAdapter {
    ...
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...
        http.csrf().disable();
        ...
    }
    ...
}

on the other way, if you want keep CSRF Protection, you should sumbit the CSRF Token is every request.
If you are using JSON, then it is not possible to submit the CSRF token within an HTTP parameter. Instead you can submit the token within a HTTP header. A typical pattern would be to include the CSRF token within your meta tags. An example with a JSP is shown below:

<html>
<head>
    <meta name="_csrf" content="${_csrf.token}"/>
    <!-- default header name is X-CSRF-TOKEN -->
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
    <!-- ... -->
</head>
<!-- ... -->

You can then include the token within all your Ajax requests. If you were using jQuery, this could be done with the following:

$(function () {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
    xhr.setRequestHeader(header, token);
});
});


问:
Handling special entities like & nbsp; , & pound; in HtmlCleaner
I am using HtmlCleaner library for html content extraction. It works fairly but with few limitations.

It is not able to handle special characters like &pound or quotes etc. For e.x.
for url : http://www.basicelegancefurnishings.co.uk/alaska-3-and-2-seater-sofa-setspan-classukmadespan-p-280.html, On giving xpath to price, It gives me "& pound;" inplace of £

Is there any property which we can set in htmlcleaner for handling this or any other solution.

Thanks

Jitendra

答:
No, I don't believe HtmlCleaner can do this. However, you can use Apache Commons StringEscapeUtils to "unescape" the html, like this:

```<code>StringEscapeUtils.unescapeHtml("£679.00");
</code>```

will produce £679.00.

Instead of HtmlCleaner, I would recommend you try JSoup.

Body:
No, I don't believe HtmlCleaner can do this. However, you can use Apache Commons StringEscapeUtils to "unescape" the html, like this:

StringEscapeUtils.unescapeHtml("&pound;679.00");

will produce £679.00.

Instead of HtmlCleaner, I would recommend you try JSoup.


问:
ExpressJS - How to change the value of key in the url of a get request
So I am developing custom pagination functionality with express and mongoose. I have a get parameter called page and I need to change the value for every different page. The problem is that the way I do it it keeps appending "page" key-value pairs to the url like this "&page=1&page=1&page=1". That is because I don't simply change the value of "page" but I append the key-value pair each time like so:

```<code>currentPageUrl: req.originalUrl + '&page=' + currentPage
</code>```

I need just to change the value of the "page" key. How can I accomplish this? Any advice, express helper function or custom solution would help a lot. Thanks in advance!

答:
I wrote a function that takes a url, a parameter and the new value you want it to be. I think this does exactly what you want

```<code>const url = require('url')

uri = 'http://example.com/cat?page=1&rand=18347109823'

function change_parameter(uri, parameter_name, new_value){
  parsed_uri = url.parse(uri, true)
  parameters = []
  for ( key in parsed_uri.query ) {
    if ( key == parameter_name ) {
      parameters.push( key + "=" + new_value )
    } else {
      parameters.push( key + "=" + parsed_uri.query[key] )
    }
  }
  return parsed_uri.protocol + "//" + parsed_uri.hostname + "?" + parameters.join("&")
}

console.log(change_parameter(uri, 'page', '3'))
</code>```

OUTPUT

```<code>$ node so.js
http://example.com?page=3&rand=18347109823
</code>```

Body:
So I am developing custom pagination functionality with express and mongoose. I have a get parameter called page and I need to change the value for every different page. The problem is that the way I do it it keeps appending "page" key-value pairs to the url like this "&page=1&page=1&page=1". That is because I don't simply change the value of "page" but I append the key-value pair each time like so:

currentPageUrl: req.originalUrl + '&page=' + currentPage

I need just to change the value of the "page" key. How can I accomplish this? Any advice, express helper function or custom solution would help a lot. Thanks in advance!

Body:
I wrote a function that takes a url, a parameter and the new value you want it to be. I think this does exactly what you want

const url = require('url')

uri = 'http://example.com/cat?page=1&rand=18347109823'

function change_parameter(uri, parameter_name, new_value){
  parsed_uri = url.parse(uri, true)
  parameters = []
  for ( key in parsed_uri.query ) {
    if ( key == parameter_name ) {
      parameters.push( key + "=" + new_value )
    } else {
      parameters.push( key + "=" + parsed_uri.query[key] )
    }
  }
  return parsed_uri.protocol + "//" + parsed_uri.hostname + "?" + parameters.join("&")
}

console.log(change_parameter(uri, 'page', '3'))

OUTPUT

$ node so.js
http://example.com?page=3&rand=18347109823


问:
Java Complex Object Replace
I never faced a requirement like that and I am pretty confused how can I implement that.

Lets consider the following Beans:

```<code>Company{
String companyName;
String companyId;
Person person;
//getter and setters
}

Person{
String id;
String name;
String lastName;
List<Address> address;
//getter and setters
}

Address{
String id;
String name;
String description;
//getter and setters
}
</code>```

So the hierarchy would be like this:

Company has  Person has Address

What I have to do is, replace all String fields with other String, for instance

Company.companyName = "Hi there #xyz"

```<code>Address.name = "St. Example #xyz"
</code>```

I need to replace the char #xyx with #abcd, for instance.

The object is much more complex than that and has a huge hierarchy.

I tried to find some API that would help me to do that, however I couldn't find anyone (I don't know if look correctly).

A solution that I have is in each getter method replace the char, however I don't think that is the best way to solve that.

I appreciate your help.

Thanks in advance.

答: I could solve that using reflection. I did not find any API.</p>

Title: Java Complex Object Replace

Body:
I never faced a requirement like that and I am pretty confused how can I implement that.

Lets consider the following Beans:

Company{
String companyName;
String companyId;
Person person;
//getter and setters
}

Person{
String id;
String name;
String lastName;
List<Address> address;
//getter and setters
}

Address{
String id;
String name;
String description;
//getter and setters
}

So the hierarchy would be like this:

Company has  Person has Address

What I have to do is, replace all String fields with other String, for instance

Company.companyName = "Hi there #xyz"

Address.name = "St. Example #xyz"

I need to replace the char #xyx with #abcd, for instance.

The object is much more complex than that and has a huge hierarchy.

I tried to find some API that would help me to do that, however I couldn't find anyone (I don't know if look correctly).

A solution that I have is in each getter method replace the char, however I don't think that is the best way to solve that.

I appreciate your help.

Thanks in advance.


问:
Mapbox GL - how to change the width of geojson line on hover?
I have a mapbox map, where I add various geojson lines. I add them like this

```<code>map.addSource('diklodartlo', diklodartlo);
        map.addLayer({
            'id': 'diklodartlo',
            'type': 'line',
            'source': 'diklodartlo',
            'layout': {
                'line-cap': 'round',
                'line-join': 'round'
            },
            'paint': {
                'line-opacity': 0.75,
                'line-color': '#747474',
                'line-width': 2
            }
        });
</code>```

Each line has also a corresponding marker, which on hover displays popup with additional information about the trail. Now I want also to "highlight" corresponding line - increase its "line-width" so the user knows which line is selected.
My idea is to take id property from the marker, pair it with id property of the line and then change the line "line-width". But its easier said than done - I know how to get property of the selected marker, but dont know how to access the layer and change the width of the line at the runtime. Could someone advise me how to do it?

Thanks a lot...

答:
So it was quite simple after all, mapbox has a property for it.

https://docs.mapbox.com/mapbox-gl-js/api/#map#setpaintproperty

Looks like this:

```<code>map.setPaintProperty(//hovered trail//, 'line-width', //desired width//);
</code>```

Body:
I have a mapbox map, where I add various geojson lines. I add them like this

map.addSource('diklodartlo', diklodartlo);
        map.addLayer({
            'id': 'diklodartlo',
            'type': 'line',
            'source': 'diklodartlo',
            'layout': {
                'line-cap': 'round',
                'line-join': 'round'
            },
            'paint': {
                'line-opacity': 0.75,
                'line-color': '#747474',
                'line-width': 2
            }
        });

Each line has also a corresponding marker, which on hover displays popup with additional information about the trail. Now I want also to "highlight" corresponding line - increase its "line-width" so the user knows which line is selected.
My idea is to take id property from the marker, pair it with id property of the line and then change the line "line-width". But its easier said than done - I know how to get property of the selected marker, but dont know how to access the layer and change the width of the line at the runtime. Could someone advise me how to do it?

Thanks a lot...

Body:
So it was quite simple after all, mapbox has a property for it.

https://docs.mapbox.com/mapbox-gl-js/api/#map#setpaintproperty

Looks like this:

map.setPaintProperty(//hovered trail//, 'line-width', //desired width//);

ContentLicense: CC BY-SA 4.0


问:
How to fetch course price from moodle web service APIs
I am building mobile app that uses moodle web service APIs to fetch data, issue is i am not getting data for course price as well as start and end date for a particular enrolled course from the api response. Any help regarding this would be appriciated.</p>

答: Since there is web serivce functions to retrieve course price, start date and end date you have to create a custom web service to retrieve these values. Please note Moodle is not storing the course end date. Hope this helps. </p>


问:
HTML connection to MySQL
I want to create a login script on HTML page. I read that I need to use an intermediate script so that I can let my HTML use the database. So, I`ve written a PHP page that checks the username/password regarding the database.

I also read that I should use AJAX to connect to the database.

I would like to know how to write the AJAX code to return the value of the login either true or false.

答:
You should really at-least try Google before posting here.

Google Search: ajax login code

This is a very simple implementation but can be a starting point.
http://woork.blogspot.com/2007/10/login-using-ajax-and-php.html

You may need to read up on ajax a little if this doesn't make sence:
http://code.google.com/edu/ajax/tutorials/ajax-tutorial.html

Title: HTML connection to MySQL


问:
Garbage collection too slow
I have a function foo() that creates a BIG list (and then converts it to a pandas dataframe)

When I time it, it runs a bit slow, but reasonable:

```<code>timeit.Timer('foo()', setup="from __main__ import foo").timeit(number=1)
6.69
</code>```

However, that's not the time I get during execution, because the garbage collection is disabled.  It runs 2x slower, if the garbage collector is enabled:

```<code>timeit.Timer('foo()', setup="from __main__ import foo \ngc.enable()").timeit(number=1)
20.31
</code>```

When is it ok to disable the garbage collector? Should I do so from within foo()?

答:
According to python documentation you can disable the collector if you are sure your program does not create reference cycles. If don't want automatic GC to happen during execution of foo. It makes sense to do something like this

```<code>def foo():
   gc.disable()
   // Your logic
   gc.enable()
</code>```

Link: https://docs.python.org/2/library/gc.html

Title: Garbage collection too slow

Body:
I have a function foo() that creates a BIG list (and then converts it to a pandas dataframe)

When I time it, it runs a bit slow, but reasonable:

timeit.Timer('foo()', setup="from __main__ import foo").timeit(number=1)
6.69

However, that's not the time I get during execution, because the garbage collection is disabled.  It runs 2x slower, if the garbage collector is enabled:

timeit.Timer('foo()', setup="from __main__ import foo \ngc.enable()").timeit(number=1)
20.31

When is it ok to disable the garbage collector? Should I do so from within foo()?

Body:
According to python documentation you can disable the collector if you are sure your program does not create reference cycles. If don't want automatic GC to happen during execution of foo. It makes sense to do something like this

def foo():
   gc.disable()
   // Your logic
   gc.enable()

Link: https://docs.python.org/2/library/gc.html


问:
How to remove dark black background from the loading spinner?
I have made a plnkr and I want to remove the black background from the ionicLoading loading spinner. How could I achieve this?

```<code>var app = angular.module('newsapp', ['ionic']);

app.controller('newscontroller',function($scope, $http, $ionicLoading, $timeout){

   $scope.show = function() {
        $ionicLoading.show({
            template: '<img width="32" height="32" src="data:image/gif;base64,[encoded data, 8452 characters]">'
        }).then(function(){
            console.log("The loading indicator is now displayed");
        });
    };
    $scope.hide = function(){
        $ionicLoading.hide().then(function(){
            console.log("The loading indicator is now hidden");
        });
    };

  $scope.news =[];

   $scope.show();

   $timeout(function () {
      $http({
        method: "GET",
        url: "https://newsapi.org/v1/articles?source=techcrunch&sortBy=latest&apiKey=90b77760d33d4c76af4c6c53862c9e72"
      }).then(function(newsdata){
        angular.forEach(newsdata.data.articles, function(newsarticle) {
          $scope.news.push(newsarticle);
        });
         $scope.lastarticleID= newsdata.data.lastID;
         $scope.hide();
      })
   },
    2500);
});
</code>```

答:
```<code>.loading{
  background-color:transparent !important;
}
</code>```

Add this to your css... that will remove the dark black background from the loading spinner

Body:
I have made a plnkr and I want to remove the black background from the ionicLoading loading spinner. How could I achieve this?

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

app.controller('newscontroller',function($scope, $http, $ionicLoading, $timeout){

   $scope.show = function() {
        $ionicLoading.show({
            template: '<img width="32" height="32" src="data:image/gif;base64,[encoded data, 8452 characters]">'
        }).then(function(){
            console.log("The loading indicator is now displayed");
        });
    };
    $scope.hide = function(){
        $ionicLoading.hide().then(function(){
            console.log("The loading indicator is now hidden");
        });
    };

  $scope.news =[];

   $scope.show();

   $timeout(function () {
      $http({
        method: "GET",
        url: "https://newsapi.org/v1/articles?source=techcrunch&sortBy=latest&apiKey=90b77760d33d4c76af4c6c53862c9e72"
      }).then(function(newsdata){
        angular.forEach(newsdata.data.articles, function(newsarticle) {
          $scope.news.push(newsarticle);
        });
         $scope.lastarticleID= newsdata.data.lastID;
         $scope.hide();
      })
   },
    2500);
});

Body:
.loading{
  background-color:transparent !important;
}

Add this to your css... that will remove the dark black background from the loading spinner


问:
HtmlUnit 400 Bad Request when additional Host header is set
I need to use a browser that can be run from Java program and allows to send a custom HTTP request directly and modify any part of the HTTP request. Therefore I chose HtmlUnit.

I tried to make a simple GET request to http://localhost and added an additional header Host:localhost. The page on my localhost home is XAMPP home. Inside the page, there is a request to other site (facebook.com). If the Host header is added, I got 400 Bad Request error. The error doesn't happen if I don't add Host header.

```<code>com.gargoylesoftware.htmlunit.ScriptException: Wrapped com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException: 400 Bad Request for http://connect.facebook.net/en_US/all.js#xfbml=1&appId=277385395761685
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:894)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:628)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:515)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:775)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:751)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:739)
at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptIfPossible(HtmlPage.java:910)
at com.gargoylesoftware.htmlunit.html.HtmlScript.executeInlineScriptIfNeeded(HtmlScript.java:307)
at com.gargoylesoftware.htmlunit.html.HtmlScript.executeScriptIfNeeded(HtmlScript.java:368)
at com.gargoylesoftware.htmlunit.html.HtmlScript$2.execute(HtmlScript.java:239)
at com.gargoylesoftware.htmlunit.html.HtmlScript.onAllChildrenAddedToPage(HtmlScript.java:258)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.endElement(HTMLParser.java:781)
at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.endElement(HTMLParser.java:738)
at net.sourceforge.htmlunit.cyberneko.HTMLTagBalancer.callEndElement(HTMLTagBalancer.java:1243)
at net.sourceforge.htmlunit.cyberneko.HTMLTagBalancer.endElement(HTMLTagBalancer.java:1143)
at net.sourceforge.htmlunit.cyberneko.filters.DefaultFilter.endElement(DefaultFilter.java:226)
at net.sourceforge.htmlunit.cyberneko.filters.NamespaceBinder.endElement(NamespaceBinder.java:345)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner$ContentScanner.scanEndElement(HTMLScanner.java:3154)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner$ContentScanner.scan(HTMLScanner.java:2117)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner.scanDocument(HTMLScanner.java:945)
at net.sourceforge.htmlunit.cyberneko.HTMLConfiguration.parse(HTMLConfiguration.java:521)
at net.sourceforge.htmlunit.cyberneko.HTMLConfiguration.parse(HTMLConfiguration.java:472)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.parse(HTMLParser.java:988)
at com.gargoylesoftware.htmlunit.html.HTMLParser.parse(HTMLParser.java:246)
at com.gargoylesoftware.htmlunit.html.HTMLParser.parseHtml(HTMLParser.java:188)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createHtmlPage(DefaultPageCreator.java:267)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createPage(DefaultPageCreator.java:155)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:517)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:391)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:309)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:473)
</code>```

In HtmlUnit, is all additional headers are applied on all request on the page (not only the first URL)?
How to fix it?

答:
No, additional requests are not applied to other requests.

Below is a complete case, compare it with yours:

index.html:

```<code>First
<a href="index2.html">test</a>
</code>```

index2.html

```<code>Second
</code>```

Test case:

```<code>LogManager.getLogger("org.apache.http.wire").setLevel(Level.ALL);
final CollectingAlertHandler handler = new CollectingAlertHandler();
try (final WebClient webClient = new WebClient(BrowserVersion.CHROME)) {
    WebRequest request = new WebRequest(new URL("http://localhost:8080"));
    request.setAdditionalHeader("Host", "abc.com");
    HtmlPage page = webClient.getPage(request);
    page.getAnchors().get(0).click();
}
</code>```

Output:

```<code>DEBUG 08:07:31,868 org.apache.http.wire: http-outgoing-0 >> "GET / HTTP/1.1[\r][\n]"
DEBUG 08:07:31,869 org.apache.http.wire: http-outgoing-0 >> "Host: abc.com[\r][\n]"
DEBUG 08:07:31,869 org.apache.http.wire: http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
DEBUG 08:07:31,869 org.apache.http.wire: http-outgoing-0 >> "Accept: */*[\r][\n]"
DEBUG 08:07:31,869 org.apache.http.wire: http-outgoing-0 >> "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36[\r][\n]"
DEBUG 08:07:31,869 org.apache.http.wire: http-outgoing-0 >> "Accept-Encoding: gzip, deflate[\r][\n]"
DEBUG 08:07:31,869 org.apache.http.wire: http-outgoing-0 >> "Accept-Language: en-US[\r][\n]"
DEBUG 08:07:31,870 org.apache.http.wire: http-outgoing-0 >> "[\r][\n]"
DEBUG 08:07:31,873 org.apache.http.wire: http-outgoing-0 << "HTTP/1.1 200 [\r][\n]"
DEBUG 08:07:31,873 org.apache.http.wire: http-outgoing-0 << "Accept-Ranges: bytes[\r][\n]"
DEBUG 08:07:31,873 org.apache.http.wire: http-outgoing-0 << "ETag: W/"37-1491113233075"[\r][\n]"
DEBUG 08:07:31,873 org.apache.http.wire: http-outgoing-0 << "Last-Modified: Sun, 02 Apr 2017 06:07:13 GMT[\r][\n]"
DEBUG 08:07:31,873 org.apache.http.wire: http-outgoing-0 << "Content-Type: text/html[\r][\n]"
DEBUG 08:07:31,873 org.apache.http.wire: http-outgoing-0 << "Content-Length: 37[\r][\n]"
DEBUG 08:07:31,875 org.apache.http.wire: http-outgoing-0 << "Date: Sun, 02 Apr 2017 06:07:31 GMT[\r][\n]"
DEBUG 08:07:31,875 org.apache.http.wire: http-outgoing-0 << "[\r][\n]"
DEBUG 08:07:31,875 org.apache.http.wire: http-outgoing-0 << "First[\r][\n]"
DEBUG 08:07:31,875 org.apache.http.wire: http-outgoing-0 << "<a href="index2.html">test</a>"
DEBUG 08:07:32,172 org.apache.http.wire: http-outgoing-0 >> "GET /index2.html HTTP/1.1[\r][\n]"
DEBUG 08:07:32,172 org.apache.http.wire: http-outgoing-0 >> "Host: localhost:8080[\r][\n]"
DEBUG 08:07:32,172 org.apache.http.wire: http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
DEBUG 08:07:32,172 org.apache.http.wire: http-outgoing-0 >> "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8[\r][\n]"
DEBUG 08:07:32,172 org.apache.http.wire: http-outgoing-0 >> "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36[\r][\n]"
DEBUG 08:07:32,173 org.apache.http.wire: http-outgoing-0 >> "Referer: http://localhost:8080/[\r][\n]"
DEBUG 08:07:32,173 org.apache.http.wire: http-outgoing-0 >> "Accept-Encoding: gzip, deflate[\r][\n]"
DEBUG 08:07:32,173 org.apache.http.wire: http-outgoing-0 >> "Accept-Language: en-US[\r][\n]"
DEBUG 08:07:32,173 org.apache.http.wire: http-outgoing-0 >> "[\r][\n]"
DEBUG 08:07:32,174 org.apache.http.wire: http-outgoing-0 << "HTTP/1.1 200 [\r][\n]"
DEBUG 08:07:32,174 org.apache.http.wire: http-outgoing-0 << "Accept-Ranges: bytes[\r][\n]"
DEBUG 08:07:32,174 org.apache.http.wire: http-outgoing-0 << "ETag: W/"6-1491113144011"[\r][\n]"
DEBUG 08:07:32,174 org.apache.http.wire: http-outgoing-0 << "Last-Modified: Sun, 02 Apr 2017 06:05:44 GMT[\r][\n]"
DEBUG 08:07:32,174 org.apache.http.wire: http-outgoing-0 << "Content-Type: text/html[\r][\n]"
DEBUG 08:07:32,175 org.apache.http.wire: http-outgoing-0 << "Content-Length: 6[\r][\n]"
DEBUG 08:07:32,175 org.apache.http.wire: http-outgoing-0 << "Date: Sun, 02 Apr 2017 06:07:31 GMT[\r][\n]"
DEBUG 08:07:32,175 org.apache.http.wire: http-outgoing-0 << "[\r][\n]"
DEBUG 08:07:32,175 org.apache.http.wire: http-outgoing-0 << "Second"
</code>```

Body:
I need to use a browser that can be run from Java program and allows to send a custom HTTP request directly and modify any part of the HTTP request. Therefore I chose HtmlUnit.

I tried to make a simple GET request to http://localhost and added an additional header Host:localhost. The page on my localhost home is XAMPP home. Inside the page, there is a request to other site (facebook.com). If the Host header is added, I got 400 Bad Request error. The error doesn't happen if I don't add Host header.

com.gargoylesoftware.htmlunit.ScriptException: Wrapped com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException: 400 Bad Request for http://connect.facebook.net/en_US/all.js#xfbml=1&appId=277385395761685
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:894)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:628)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:515)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:775)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:751)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:739)
at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptIfPossible(HtmlPage.java:910)
at com.gargoylesoftware.htmlunit.html.HtmlScript.executeInlineScriptIfNeeded(HtmlScript.java:307)
at com.gargoylesoftware.htmlunit.html.HtmlScript.executeScriptIfNeeded(HtmlScript.java:368)
at com.gargoylesoftware.htmlunit.html.HtmlScript$2.execute(HtmlScript.java:239)
at com.gargoylesoftware.htmlunit.html.HtmlScript.onAllChildrenAddedToPage(HtmlScript.java:258)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.endElement(HTMLParser.java:781)
at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.endElement(HTMLParser.java:738)
at net.sourceforge.htmlunit.cyberneko.HTMLTagBalancer.callEndElement(HTMLTagBalancer.java:1243)
at net.sourceforge.htmlunit.cyberneko.HTMLTagBalancer.endElement(HTMLTagBalancer.java:1143)
at net.sourceforge.htmlunit.cyberneko.filters.DefaultFilter.endElement(DefaultFilter.java:226)
at net.sourceforge.htmlunit.cyberneko.filters.NamespaceBinder.endElement(NamespaceBinder.java:345)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner$ContentScanner.scanEndElement(HTMLScanner.java:3154)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner$ContentScanner.scan(HTMLScanner.java:2117)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner.scanDocument(HTMLScanner.java:945)
at net.sourceforge.htmlunit.cyberneko.HTMLConfiguration.parse(HTMLConfiguration.java:521)
at net.sourceforge.htmlunit.cyberneko.HTMLConfiguration.parse(HTMLConfiguration.java:472)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.parse(HTMLParser.java:988)
at com.gargoylesoftware.htmlunit.html.HTMLParser.parse(HTMLParser.java:246)
at com.gargoylesoftware.htmlunit.html.HTMLParser.parseHtml(HTMLParser.java:188)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createHtmlPage(DefaultPageCreator.java:267)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createPage(DefaultPageCreator.java:155)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:517)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:391)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:309)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:473)

In HtmlUnit, is all additional headers are applied on all request on the page (not only the first URL)?
How to fix it?

Body:
No, additional requests are not applied to other requests.

Below is a complete case, compare it with yours:

index.html:

First
<a href="index2.html">test</a>

index2.html

Second

Test case:

LogManager.getLogger("org.apache.http.wire").setLevel(Level.ALL);
final CollectingAlertHandler handler = new CollectingAlertHandler();
try (final WebClient webClient = new WebClient(BrowserVersion.CHROME)) {
    WebRequest request = new WebRequest(new URL("http://localhost:8080"));
    request.setAdditionalHeader("Host", "abc.com");
    HtmlPage page = webClient.getPage(request);
    page.getAnchors().get(0).click();
}

Output:

DEBUG 08:07:31,868 org.apache.http.wire: http-outgoing-0 >> "GET / HTTP/1.1[\r][\n]"
DEBUG 08:07:31,869 org.apache.http.wire: http-outgoing-0 >> "Host: abc.com[\r][\n]"
DEBUG 08:07:31,869 org.apache.http.wire: http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
DEBUG 08:07:31,869 org.apache.http.wire: http-outgoing-0 >> "Accept: */*[\r][\n]"
DEBUG 08:07:31,869 org.apache.http.wire: http-outgoing-0 >> "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36[\r][\n]"
DEBUG 08:07:31,869 org.apache.http.wire: http-outgoing-0 >> "Accept-Encoding: gzip, deflate[\r][\n]"
DEBUG 08:07:31,869 org.apache.http.wire: http-outgoing-0 >> "Accept-Language: en-US[\r][\n]"
DEBUG 08:07:31,870 org.apache.http.wire: http-outgoing-0 >> "[\r][\n]"
DEBUG 08:07:31,873 org.apache.http.wire: http-outgoing-0 << "HTTP/1.1 200 [\r][\n]"
DEBUG 08:07:31,873 org.apache.http.wire: http-outgoing-0 << "Accept-Ranges: bytes[\r][\n]"
DEBUG 08:07:31,873 org.apache.http.wire: http-outgoing-0 << "ETag: W/"37-1491113233075"[\r][\n]"
DEBUG 08:07:31,873 org.apache.http.wire: http-outgoing-0 << "Last-Modified: Sun, 02 Apr 2017 06:07:13 GMT[\r][\n]"
DEBUG 08:07:31,873 org.apache.http.wire: http-outgoing-0 << "Content-Type: text/html[\r][\n]"
DEBUG 08:07:31,873 org.apache.http.wire: http-outgoing-0 << "Content-Length: 37[\r][\n]"
DEBUG 08:07:31,875 org.apache.http.wire: http-outgoing-0 << "Date: Sun, 02 Apr 2017 06:07:31 GMT[\r][\n]"
DEBUG 08:07:31,875 org.apache.http.wire: http-outgoing-0 << "[\r][\n]"
DEBUG 08:07:31,875 org.apache.http.wire: http-outgoing-0 << "First[\r][\n]"
DEBUG 08:07:31,875 org.apache.http.wire: http-outgoing-0 << "<a href="index2.html">test</a>"
DEBUG 08:07:32,172 org.apache.http.wire: http-outgoing-0 >> "GET /index2.html HTTP/1.1[\r][\n]"
DEBUG 08:07:32,172 org.apache.http.wire: http-outgoing-0 >> "Host: localhost:8080[\r][\n]"
DEBUG 08:07:32,172 org.apache.http.wire: http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
DEBUG 08:07:32,172 org.apache.http.wire: http-outgoing-0 >> "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8[\r][\n]"
DEBUG 08:07:32,172 org.apache.http.wire: http-outgoing-0 >> "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36[\r][\n]"
DEBUG 08:07:32,173 org.apache.http.wire: http-outgoing-0 >> "Referer: http://localhost:8080/[\r][\n]"
DEBUG 08:07:32,173 org.apache.http.wire: http-outgoing-0 >> "Accept-Encoding: gzip, deflate[\r][\n]"
DEBUG 08:07:32,173 org.apache.http.wire: http-outgoing-0 >> "Accept-Language: en-US[\r][\n]"
DEBUG 08:07:32,173 org.apache.http.wire: http-outgoing-0 >> "[\r][\n]"
DEBUG 08:07:32,174 org.apache.http.wire: http-outgoing-0 << "HTTP/1.1 200 [\r][\n]"
DEBUG 08:07:32,174 org.apache.http.wire: http-outgoing-0 << "Accept-Ranges: bytes[\r][\n]"
DEBUG 08:07:32,174 org.apache.http.wire: http-outgoing-0 << "ETag: W/"6-1491113144011"[\r][\n]"
DEBUG 08:07:32,174 org.apache.http.wire: http-outgoing-0 << "Last-Modified: Sun, 02 Apr 2017 06:05:44 GMT[\r][\n]"
DEBUG 08:07:32,174 org.apache.http.wire: http-outgoing-0 << "Content-Type: text/html[\r][\n]"
DEBUG 08:07:32,175 org.apache.http.wire: http-outgoing-0 << "Content-Length: 6[\r][\n]"
DEBUG 08:07:32,175 org.apache.http.wire: http-outgoing-0 << "Date: Sun, 02 Apr 2017 06:07:31 GMT[\r][\n]"
DEBUG 08:07:32,175 org.apache.http.wire: http-outgoing-0 << "[\r][\n]"
DEBUG 08:07:32,175 org.apache.http.wire: http-outgoing-0 << "Second"


答:
Override the CSS:</p>

```<code>.loading {
   background-color: transparent !important;
}
</code>```

Title: How to remove dark black background from the loading spinner?

Body:
Override the CSS:

.loading {
   background-color: transparent !important;
}


问:
multi select folders and files
it is possible to select multiple files using OpenFileDialog. (setting multiselect as true)

the question is how to select multiple files and folders at the same time?

I know what is FolderBrowseDialog, I know I should Hold ctrl or shift! :D

assume a folder contain 5 folder and 2 files, the scenario is to select for example 1 of files and 2 folders.

I don't know why people down vote this question!!

----------------- Edit --------------------

assume an OpenFileDialog, you can select as many file as you want in a folder, ok?
I want something like this but with the ability to select folders too!
so as OpenFileDialog return selected file names in FileNames array that dialog return something Like SelectedPaths array that contains filenames and folderpaths.

答:
I've done this in an application I built, and I ended up using a TreeView control and just mapping the hard drive into this control - each folder had a TreeNode, nested to match the folder structure, and then the files at the deepest level.

While it's memory-hungry, a user can select/de-select individual files, and it's pretty easy to automatically select/de-select all the children when somebody checks a parent folder.

Title: multi select folders and files


问:
PHP: extract version number for string
I get each time different string.

From the string i need to extract the version number. when the version number can come in different types like:

```<code>v1.3
V1.3
v 2.4.1
V 2.4.1

version1.3
version 1.3
Version2.4.1
Version 2.4.1
</code>```

The output need to be: 1.3 or 2.4.1

one more problem is that string can contain numbers beside the version number.

what will be the fast way to do this task?

答:
I'd use regex for this:

Code:

```<code><?php

function getVersion($str) {
    preg_match("/(?:version|v)\s*((?:[0-9]+\.?)+)/i", $str, $matches);
    return $matches[1];
}

print_r(getVersion("Version 2.4.1"));

?>
</code>```

Regex101:

https://regex101.com/r/6WnQKt/3

Title: PHP: extract version number for string

Body:
I get each time different string.

From the string i need to extract the version number. when the version number can come in different types like:

v1.3
V1.3
v 2.4.1
V 2.4.1

version1.3
version 1.3
Version2.4.1
Version 2.4.1

The output need to be: 1.3 or 2.4.1

one more problem is that string can contain numbers beside the version number.

what will be the fast way to do this task?

Body:
I'd use regex for this:

Code:

<?php

function getVersion($str) {
    preg_match("/(?:version|v)\s*((?:[0-9]+\.?)+)/i", $str, $matches);
    return $matches[1];
}

print_r(getVersion("Version 2.4.1"));

?>

Regex101:

https://regex101.com/r/6WnQKt/3


问:
What can go wrong (what are the risks) if i don't escape the data and insert it to database?
I am using codeigniter and in security section it suggest that: Escape the data before submitting it into your database or outputting it to a browser.

What could really go wrong if I don't escape it, what are the risks?

Thank you.

答:
Major Threats

SQL Injection

Cross Side Request Forgery


问:
Django: How to order a query set for a foreign key by a field of referencing class
I've got two classes:

```<code>class Manufacturer(models.Model):
    name = models.CharField(max_length=50)

class Part(models.Model):

    name = models.CharField(max_length=255)
    manufacturer = models.ForeignKey(
        Manufacturer,
        verbose_name=_("Manufacturer"),
        null=True,
        blank=True,
        help_text=_("The manufacturer of the part.")
    )
</code>```

Now I ned to make a query that fetches all parts linking to a particual manufacturer. This I've done with parts = self.part_set.all(). But Now I need to sort the order. so I assumed the .order_by() could do the trick so in the end I have

```<code>def get_parts(self):
    return list(self.part_set.all().order_by('name'))
</code>```

Unfortunately this is not sorting correct. So my question is: What is the correct way on sort the list of objects referencing another object by some attribute?

答:
There is always the option of default ordering, via the Meta class on each model. So:

```<code>class Part(models.Model):
    name = models.CharField(max_length=255)
    manufacturer = ...

    class Meta:
        ordering = ['name']  # or ['-name'] for descending
</code>```

Now, everytime you get Part objects, they'll be sorted by name unless an order_by is used in the query.

To come to your question, you can use this:

```<code>self.part_set.order_by('part__name')
</code>```

but if you have already specified the ordering setting of Meta inside the Part class then you don't have to write it that way. Instead write:

```<code>self.part_set.order_by('part')
</code>```

and Django will order Part objects as per the Part Meta's ordering setting.

Body:
I've got two classes:

class Manufacturer(models.Model):
    name = models.CharField(max_length=50)

class Part(models.Model):

    name = models.CharField(max_length=255)
    manufacturer = models.ForeignKey(
        Manufacturer,
        verbose_name=_("Manufacturer"),
        null=True,
        blank=True,
        help_text=_("The manufacturer of the part.")
    )

Now I ned to make a query that fetches all parts linking to a particual manufacturer. This I've done with parts = self.part_set.all(). But Now I need to sort the order. so I assumed the .order_by() could do the trick so in the end I have

def get_parts(self):
    return list(self.part_set.all().order_by('name'))

Unfortunately this is not sorting correct. So my question is: What is the correct way on sort the list of objects referencing another object by some attribute?

Body:
There is always the option of default ordering, via the Meta class on each model. So:

class Part(models.Model):
    name = models.CharField(max_length=255)
    manufacturer = ...

    class Meta:
        ordering = ['name']  # or ['-name'] for descending

Now, everytime you get Part objects, they'll be sorted by name unless an order_by is used in the query.

To come to your question, you can use this:

self.part_set.order_by('part__name')

but if you have already specified the ordering setting of Meta inside the Part class then you don't have to write it that way. Instead write:

self.part_set.order_by('part')

and Django will order Part objects as per the Part Meta's ordering setting.


问:
Fetching comments of a post through ajax from database in laravel 5.3
```<code><script>
    var token = '{{ Session::token() }}';
    var commentUrl = '{{ route('comments.store')  }}';
    var fetchComments = '{{ route('commentT')  }}';

</script>
</code>```

A 'post' route to fetch comment

```<code>Route::post('comm', [
                'uses' => 'CommentController@comment',
                'as'   => 'commentT'
            ]);
</code>```

function which has ajax

```<code>function getCommentsFromDb(postid){

    console.log("Post"+postid);
    $.ajax({

        type : 'POST',
        url  : fetchComments,
        data : { postid: postid,_token: token },
        success : function(result){
            console.log(result);
        }

    });

}
</code>```

I am trying to fetch comments of a single post and i am passing id of post

```<code> public function comment(Request $request)
    {
        //

            $answer_id = $request['answerid'];

            // echo "controller side ".$test;

            $comments = DB::table('posts')
                        ->join('posts', 'posts.id' , '=', 'comments.answer_id')
                        ->join('users' , 'users.id' , '=', 'comments.user_id')
                        ->where('posts.id', '=' , $post_id)
                        ->select('comments.comment as comment',
                                'comments.created_at as created_at',
                                'users.first_name as first_name',
                                'users.last_name as last_name',
                                'posts.post as post')
                        ->orderBy('created_at', 'desc')
                        ->get();

                   $comm = json_decode($comments);

                   print_r($comm);

        *// I though here i have to write html content which i want to render on the view*

    }
</code>```

I am getting expected result in console but how can i render this result to my view , it is simple if i do in core php but here in laravel i am stuck

In future i would be making delete,edit functionality for comments using ajax

Here is what i am getting in mys console

```<code>Array
(
    [0] => stdClass Object
        (
            [comment] => sdfasdf shameem
            [created_at] => 2017-03-31 21:44:22
            [first_name] => Shameem
            [last_name] => Ansari
            [post]  => fist post content fist post content fist post content fist post content fist post content fist post content fist post content fist post content
        )

    [1] => stdClass Object
        (
            [comment] => game on
            [created_at] => 2017-03-31 21:22:44
            [first_name] => Waqaar
            [last_name] => Aslam
            [post]    => fist post content fist post content fist post content fist post content fist post content fist post content fist post content fist post content
        )

)
</code>```

i assume first i have to put these values that i got in console in html structure as i want comment section format to be and then i can do this #div_to_show

答:
I think you want to show comments in the page.

You can use the GET method instead of the POST method. (While you are getting data, You don't submit any POST data.)

Instead of console.log(result); or below of console.log(result); add $('#div_to_show').html(result); where div_to_show is the id of the div tag.

You can return JSON data and append them with jQuery. (Good idea if you want to use Ajax.)

Code:

```<code>function getCommentsFromDb(postid){
    console.log("Post"+postid);
    $.ajax({

        type : 'POST',
        url  : fetchComments,
        data : { postid: postid,_token: token },
        success : function(result){
            console.log(result);
            $('#div_to_show').html(result); // If it is json try      $.each(result, function(i, field){$("#div_to_show").append(field + " ");});
        }
    });
}
</code>```

php code:

```<code> public function comment(Request $request)
    {
        //

            $answer_id = $request['answerid'];

            // echo "controller side ".$test;

            $comments = DB::table('posts')
                        ->join('posts', 'posts.id' , '=', 'comments.answer_id')
                        ->join('users' , 'users.id' , '=', 'comments.user_id')
                        ->where('posts.id', '=' , $post_id)
                        ->select('comments.comment as comment',
                                'comments.created_at as created_at',
                                'users.first_name as first_name',
                                'users.last_name as last_name',
                                'posts.post as post')
                        ->orderBy('created_at', 'desc')
                        ->get();

                   $comms = json_decode($comments);

                   //Instead of print_r()
                   foreach($comments as $comment) {
                       echo "<div>";
                       echo $comment->first_name;
                       echo $comment->last_name;
                       echo $comment->comment;
                       echo $comment->created_at;
                       echo "</div>";
                   }
    }
</code>```

Body:
A 'post' route to fetch comment

Route::post('comm', [
                'uses' => 'CommentController@comment',
                'as'   => 'commentT'
            ]);

function which has ajax

function getCommentsFromDb(postid){

    console.log("Post"+postid);
    $.ajax({

        type : 'POST',
        url  : fetchComments,
        data : { postid: postid,_token: token },
        success : function(result){
            console.log(result);
        }

    });

}

I am trying to fetch comments of a single post and i am passing id of post

 public function comment(Request $request)
    {
        //

            $answer_id = $request['answerid'];

            // echo "controller side ".$test;

            $comments = DB::table('posts')
                        ->join('posts', 'posts.id' , '=', 'comments.answer_id')
                        ->join('users' , 'users.id' , '=', 'comments.user_id')
                        ->where('posts.id', '=' , $post_id)
                        ->select('comments.comment as comment',
                                'comments.created_at as created_at',
                                'users.first_name as first_name',
                                'users.last_name as last_name',
                                'posts.post as post')
                        ->orderBy('created_at', 'desc')
                        ->get();

                   $comm = json_decode($comments);

                   print_r($comm);

        *// I though here i have to write html content which i want to render on the view*

    }

I am getting expected result in console but how can i render this result to my view , it is simple if i do in core php but here in laravel i am stuck

In future i would be making delete,edit functionality for comments using ajax

Here is what i am getting in mys console

Array
(
    [0] => stdClass Object
        (
            [comment] => sdfasdf shameem
            [created_at] => 2017-03-31 21:44:22
            [first_name] => Shameem
            [last_name] => Ansari
            [post]  => fist post content fist post content fist post content fist post content fist post content fist post content fist post content fist post content
        )

    [1] => stdClass Object
        (
            [comment] => game on
            [created_at] => 2017-03-31 21:22:44
            [first_name] => Waqaar
            [last_name] => Aslam
            [post]    => fist post content fist post content fist post content fist post content fist post content fist post content fist post content fist post content
        )

)

i assume first i have to put these values that i got in console in html structure as i want comment section format to be and then i can do this #div_to_show

Body:
I think you want to show comments in the page.

You can use the GET method instead of the POST method. (While you are getting data, You don't submit any POST data.)

Instead of console.log(result); or below of console.log(result); add $('#div_to_show').html(result); where div_to_show is the id of the div tag.

You can return JSON data and append them with jQuery. (Good idea if you want to use Ajax.)

Code:

function getCommentsFromDb(postid){
    console.log("Post"+postid);
    $.ajax({

        type : 'POST',
        url  : fetchComments,
        data : { postid: postid,_token: token },
        success : function(result){
            console.log(result);
            $('#div_to_show').html(result); // If it is json try      $.each(result, function(i, field){$("#div_to_show").append(field + " ");});
        }
    });
}

php code:

 public function comment(Request $request)
    {
        //

            $answer_id = $request['answerid'];

            // echo "controller side ".$test;

            $comments = DB::table('posts')
                        ->join('posts', 'posts.id' , '=', 'comments.answer_id')
                        ->join('users' , 'users.id' , '=', 'comments.user_id')
                        ->where('posts.id', '=' , $post_id)
                        ->select('comments.comment as comment',
                                'comments.created_at as created_at',
                                'users.first_name as first_name',
                                'users.last_name as last_name',
                                'posts.post as post')
                        ->orderBy('created_at', 'desc')
                        ->get();

                   $comms = json_decode($comments);

                   //Instead of print_r()
                   foreach($comments as $comment) {
                       echo "<div>";
                       echo $comment->first_name;
                       echo $comment->last_name;
                       echo $comment->comment;
                       echo $comment->created_at;
                       echo "</div>";
                   }
    }


问:
Refreshing Dagger 2 instance from Android Application class
I have a set of @Singleton and @Provides method in my module class for the purpose of creating Singleton instance throughout the application. Everything works fine except few bottle neck scenarios like as follows:

STEP 1. I am creating a Retrofit instance from OKHttpClient with Auth token in it to make a authenticated api calls each time (Auth token retrieval and insertion is handled through SharedPreferences). But the problem starts at the time of relaunching the activity after when i logout the application by clearing databases and shared preferences values.

STEP 2. After logout, am making an another request to fetch auth tokens and inserting into SharedPreferences again for future use.

STEP 3: Now if i proceed with the rest of api calls, the previous instance of the Dagger @Singleton and @Provides method remains same unless and until if i relaunch the app by clearing it from the recent task. (New auth token is not updated)

Fixes Needed:

How to trigger the Dagger provider methods forcibly to trigger or revoke it again?

Is there any method to refresh the application class data as similar behaviour like when the app relaunches.?

Please find my Dagger 2 architecture used in my project:

NetworkModule.java (Dagger Module class)

```<code>@Module
public class NetworkModule {

  private Context context;

    public NetworkModule(Application app) {
        this.context = app;
    }

    @Provides
    @Named("network.context")
    Context providesContext() {
        return context;
    }

 @Singleton
    @Provides
    OkHttpClient providesOkHttpClient(@Named("network.context")final Context context) {

        final UserProfile userProfile = GsonUtils.createPojo(SharedPrefsUtils.getString(Constants.SHARED_PREFS.USERS_PROFILE, "",context), UserProfile.class);

        Logger.i(userProfile != null && !TextUtils.isEmpty(userProfile.getAuth_token()) ? userProfile.getAuth_token() : "----OAuth token empty---");

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();

                Request request = original.newBuilder()
                        .header("Accept", "application/json")
                        .header("Content-Type", "application/json")
                        .header("Api-Version", "application/vnd.addo-v1+json")
                        .header("Access-Token", userProfile != null && !TextUtils.isEmpty(userProfile.getAuth_token()) ? userProfile.getAuth_token() : "")
                        .header("App-Version", Utils.getVersionName(context))
                        .header("Device-Platform","android")
                        .method(original.method(), original.body())
                        .build();

                return chain.proceed(request);
            }

        });

        return httpClient.build();
    }

    @Provides
    @Named(Constants.INJECTION.BASE_URL)
    String providebaseURL() {
        return Constants.URL.BASE_URL;
    }

    @Singleton
    @Provides

    Retrofit providesRetrofit(@Named("network.context")Context context, @Named(Constants.INJECTION.BASE_URL) String baseURL, OkHttpClient okHttpClient) {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseURL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(okHttpClient)
                .build();
        return retrofit;
    }

@Singleton
    @Provides
     NetworkApiService providesNetworkApiService(Retrofit retrofit){
        return retrofit.create(NetworkApiService.class);
    }

 @Singleton
    @Provides
    ProjectPresenter providesProjectPresenter(NetworkApiService networkApiService){
        return new ProjectPresenterImpl(networkApiService);
    }

}
</code>```

AppComponent.java (Dagger component class)

```<code>@Singleton
@Component(modules =  {NetworkModule.class})
public interface AppComponent {

    //ACtivity
    void inject(AuthenticationActivity authenticationActivity);

    void inject(MainActivity mainActivity);

    //Fragments

    void inject(ProjectsListFragment projectsListFragment);

}
</code>```

Application.java (Class used to create Dagger component)

```<code>   public class Application extends Application {

        private AppComponent appComponent ;

        @Override
        public void onCreate() {
            super.onCreate();

            Realm.init(this);

            ButterKnife.setDebug(BuildConfig.DEBUG);

            appComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).networkModule(new NetworkModule(this)).build();

        }

        public AppComponent getAppComponent() {
            return appComponent;
        }

    }
</code>```

Kindly help me with your suggestions or tips to resolve this weird behaviour of Dagger 2. Any kind of solutions will be much helpful to me since I am completely stuck up with this for the past 6 days. I am clueless and perplexed because my complete architecture is built on top of this. Please forgive me for typos and corrections. Ping me if there are any clarifications required regarding the same. Thanks in advance.

答:
As per the azizbekian solution I modified the code a bit and it worked like a charm. Thanks a lot!

If the use clicks logout button, I am clearing SharedPreference and assigning dagger component as null through custom created method in application clearComponent() and then navigating the user to the another Authentication screen. Please find the complete code as below. Hope it will help some one!

```<code>@OnClick(R.id.img_logout)
    void logout() {

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());

        alertDialog
                .setMessage("Do you really want to logout?")
                .setCancelable(false)
                .setPositiveButton("Logout", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogBox, int id) {
                        // ToDo get user input here

                        SharedPrefsUtils.remove(KEY_USERPROFILE, getActivity());

                        ((Application) getActivity().getApplication()).clearComponent();

                        ActivityUtils.launchActivity(getActivity(), AuthenticationActivity.class, true);

                    }
                })

                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialogBox, int id) {
                                dialogBox.cancel();
                            }
                        });

        AlertDialog alertDialogAndroid = alertDialog.create();
        alertDialogAndroid.show();

    }
</code>```

Application.java

```<code>    public class Application extends Application {

                private AppComponent appComponent ;

                @Override
                public void onCreate() {
                    super.onCreate();

                    Realm.init(this);

                    ButterKnife.setDebug(BuildConfig.DEBUG);

                    appComponent = createDaggerComponent();

                }

                  public AppComponent getAppComponent() {

                      return appComponent == null ? createDaggerComponent()   : appComponent;
    }

                public void clearComponent() {
                     appComponent = null;
                }

          private AppComponent createDaggerComponent() {
             return DaggerAppComponent.builder().appModule(new    AppModule(this)).networkModule(new NetworkModule(this)).build();
    }
            }
</code>```

Body:
I have a set of @Singleton and @Provides method in my module class for the purpose of creating Singleton instance throughout the application. Everything works fine except few bottle neck scenarios like as follows:

STEP 1. I am creating a Retrofit instance from OKHttpClient with Auth token in it to make a authenticated api calls each time (Auth token retrieval and insertion is handled through SharedPreferences). But the problem starts at the time of relaunching the activity after when i logout the application by clearing databases and shared preferences values.

STEP 2. After logout, am making an another request to fetch auth tokens and inserting into SharedPreferences again for future use.

STEP 3: Now if i proceed with the rest of api calls, the previous instance of the Dagger @Singleton and @Provides method remains same unless and until if i relaunch the app by clearing it from the recent task. (New auth token is not updated)

Fixes Needed:

How to trigger the Dagger provider methods forcibly to trigger or revoke it again?

Is there any method to refresh the application class data as similar behaviour like when the app relaunches.?

Please find my Dagger 2 architecture used in my project:

NetworkModule.java (Dagger Module class)

@Module
public class NetworkModule {

  private Context context;

    public NetworkModule(Application app) {
        this.context = app;
    }

    @Provides
    @Named("network.context")
    Context providesContext() {
        return context;
    }

 @Singleton
    @Provides
    OkHttpClient providesOkHttpClient(@Named("network.context")final Context context) {

        final UserProfile userProfile = GsonUtils.createPojo(SharedPrefsUtils.getString(Constants.SHARED_PREFS.USERS_PROFILE, "",context), UserProfile.class);

        Logger.i(userProfile != null && !TextUtils.isEmpty(userProfile.getAuth_token()) ? userProfile.getAuth_token() : "----OAuth token empty---");

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();

                Request request = original.newBuilder()
                        .header("Accept", "application/json")
                        .header("Content-Type", "application/json")
                        .header("Api-Version", "application/vnd.addo-v1+json")
                        .header("Access-Token", userProfile != null && !TextUtils.isEmpty(userProfile.getAuth_token()) ? userProfile.getAuth_token() : "")
                        .header("App-Version", Utils.getVersionName(context))
                        .header("Device-Platform","android")
                        .method(original.method(), original.body())
                        .build();

                return chain.proceed(request);
            }

        });

        return httpClient.build();
    }

    @Provides
    @Named(Constants.INJECTION.BASE_URL)
    String providebaseURL() {
        return Constants.URL.BASE_URL;
    }

    @Singleton
    @Provides

    Retrofit providesRetrofit(@Named("network.context")Context context, @Named(Constants.INJECTION.BASE_URL) String baseURL, OkHttpClient okHttpClient) {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseURL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(okHttpClient)
                .build();
        return retrofit;
    }

@Singleton
    @Provides
     NetworkApiService providesNetworkApiService(Retrofit retrofit){
        return retrofit.create(NetworkApiService.class);
    }

 @Singleton
    @Provides
    ProjectPresenter providesProjectPresenter(NetworkApiService networkApiService){
        return new ProjectPresenterImpl(networkApiService);
    }

}

AppComponent.java (Dagger component class)

@Singleton
@Component(modules =  {NetworkModule.class})
public interface AppComponent {

    //ACtivity
    void inject(AuthenticationActivity authenticationActivity);

    void inject(MainActivity mainActivity);

    //Fragments

    void inject(ProjectsListFragment projectsListFragment);

}

Application.java (Class used to create Dagger component)

   public class Application extends Application {

        private AppComponent appComponent ;

        @Override
        public void onCreate() {
            super.onCreate();

            Realm.init(this);

            ButterKnife.setDebug(BuildConfig.DEBUG);

            appComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).networkModule(new NetworkModule(this)).build();

        }

        public AppComponent getAppComponent() {
            return appComponent;
        }

    }

Kindly help me with your suggestions or tips to resolve this weird behaviour of Dagger 2. Any kind of solutions will be much helpful to me since I am completely stuck up with this for the past 6 days. I am clueless and perplexed because my complete architecture is built on top of this. Please forgive me for typos and corrections. Ping me if there are any clarifications required regarding the same. Thanks in advance.

Body:
As per the azizbekian solution I modified the code a bit and it worked like a charm. Thanks a lot!

If the use clicks logout button, I am clearing SharedPreference and assigning dagger component as null through custom created method in application clearComponent() and then navigating the user to the another Authentication screen. Please find the complete code as below. Hope it will help some one!

@OnClick(R.id.img_logout)
    void logout() {

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());

        alertDialog
                .setMessage("Do you really want to logout?")
                .setCancelable(false)
                .setPositiveButton("Logout", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogBox, int id) {
                        // ToDo get user input here

                        SharedPrefsUtils.remove(KEY_USERPROFILE, getActivity());

                        ((Application) getActivity().getApplication()).clearComponent();

                        ActivityUtils.launchActivity(getActivity(), AuthenticationActivity.class, true);

                    }
                })

                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialogBox, int id) {
                                dialogBox.cancel();
                            }
                        });

        AlertDialog alertDialogAndroid = alertDialog.create();
        alertDialogAndroid.show();

    }

Application.java

    public class Application extends Application {

                private AppComponent appComponent ;

                @Override
                public void onCreate() {
                    super.onCreate();

                    Realm.init(this);

                    ButterKnife.setDebug(BuildConfig.DEBUG);

                    appComponent = createDaggerComponent();

                }

                  public AppComponent getAppComponent() {

                      return appComponent == null ? createDaggerComponent()   : appComponent;
    }

                public void clearComponent() {
                     appComponent = null;
                }

          private AppComponent createDaggerComponent() {
             return DaggerAppComponent.builder().appModule(new    AppModule(this)).networkModule(new NetworkModule(this)).build();
    }
            }


问:
Hyphens between buttons when commenting out white space
When I try to remove gaps between my buttons by commenting out the white space between them, these little black dashes appear instead, which are selectable using the tab button. I can make them non visable with text-decoration: false and I can remove the gap with margin-left: -4px but whatever it is is still there and is selected when using the tab button.

Why are these dashes there and how do I get rid of them?

HTML:

```<code><a target="_blank" a href= "https://Google.com">
<button class="button">
<strong>LinkedIn</strong><br>
</button></a><!--
--><a target="_blank" a href= "https://www.Google.com">
<button class="button">
<strong>GitHub</strong><br>
</button></a>
<br><!--
--><a target="_blank" a href= "https://www.Google.com">
<button class="button">
<strong>Stack Overflow</strong><br>
</button></a><!--
--><a target="_blank" a href= "https://www.Google.com">
<button class="button">
<strong>HackerRank</strong><br>
</button></a>
</code>```

CSS:

```<code>div{
    display: inline-block;
    white-space: normal;
    height: 623px;
    padding: 10px;
    padding-top: 0;
    padding-left: 0;
    vertical-align: top;
    border-bottom: 3px solid black;
    border: 1px solid black;
  width: 500px;
}

.button{
    background-color: rgb(224,184,219);
    border: 2px solid white;
    border-radius: 10px;
    color: white;
    display: inline-block;
    font-size: 16px;
    text-decoration: none;
    text-align: center;
    padding: 10px;
    width: 160px;
    height: 100px;
    transition-duration: 0.2s;
    -webkit-transition-duration:0.2s;
    cursor: pointer;
    outline: none;
}
.button:hover{
    background-color: white;
    color: rgb(224,184,219);
    outline: none;
}
:focus, :visited{
    border: 2px solid rgb(153,217,234);
    outline: none;
    outline: 0;
}
</code>```

JSFiddle: https://jsfiddle.net/mpbev9ay/1/

答:
You also need to comment out the white space between  and <button>, see below.

div{
display: inline-block;
white-space: normal;
height: 623px;
padding: 10px;
padding-top: 0;
padding-left: 0;
vertical-align: top;
border-bottom: 3px solid black;
border: 1px solid black;
width: 500px;
}

.button{
background-color: rgb(224,184,219);
border: 2px solid white;
border-radius: 10px;
color: white;
display: inline-block;
font-size: 16px;
text-decoration: none;
text-align: center;
padding: 10px;
width: 160px;
height: 100px;
transition-duration: 0.2s;
-webkit-transition-duration:0.2s;
cursor: pointer;
outline: none;
}
.button:hover{
background-color: white;
color: rgb(224,184,219);
outline: none;
}
:focus, :visited{
border: 2px solid rgb(153,217,234);
outline: none;
outline: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--
--><button class="button">
<strong>LinkedIn</strong><br>
</button><!--
--><!--
--><button class="button">
<strong>GitHub</strong><br>
</button>
<br><!--
--><!--
--><button class="button">
<strong>Stack Overflow</strong><br>
</button><!--
--><!--
--><button class="button">
<strong>HackerRank</strong><br>
</button></code>```

OR you can use onclick on <button>, as below

div{
display: inline-block;
white-space: normal;
height: 623px;
padding: 10px;
padding-top: 0;
padding-left: 0;
vertical-align: top;
border-bottom: 3px solid black;
border: 1px solid black;
width: 500px;
}

.button{
background-color: rgb(224,184,219);
border: 2px solid white;
border-radius: 10px;
color: white;
display: inline-block;
font-size: 16px;
text-decoration: none;
text-align: center;
padding: 10px;
width: 160px;
height: 100px;
transition-duration: 0.2s;
-webkit-transition-duration:0.2s;
cursor: pointer;
outline: none;
}
.button:hover{
background-color: white;
color: rgb(224,184,219);
outline: none;
}
:focus, :visited{
border: 2px solid rgb(153,217,234);
outline: none;
outline: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="button" onclick="window.open('https://Google.com','_blank')">
<strong>LinkedIn</strong><br></button><!--
--><button class="button" onclick="window.open('https://Google.com','_blank')">
<strong>GitHub</strong><br>
</button><br><!--
--><button class="button" onclick="window.open('https://Google.com','_blank')">
<strong>Stack Overflow</strong><br>
</button><!--
--><button class="button" onclick="window.open('https://Google.com','_blank')">
<strong>HackerRank</strong><br>
</button></code>```

Body:
When I try to remove gaps between my buttons by commenting out the white space between them, these little black dashes appear instead, which are selectable using the tab button. I can make them non visable with text-decoration: false and I can remove the gap with margin-left: -4px but whatever it is is still there and is selected when using the tab button.

Why are these dashes there and how do I get rid of them?

HTML:

<button class="button">
LinkedIn

</button>
<button class="button">
GitHub

</button>

<button class="button">
Stack Overflow

</button>
<button class="button">
HackerRank

</button>

CSS:

div{
    display: inline-block;
    white-space: normal;
    height: 623px;
    padding: 10px;
    padding-top: 0;
    padding-left: 0;
    vertical-align: top;
    border-bottom: 3px solid black;
    border: 1px solid black;
  width: 500px;
}

.button{
    background-color: rgb(224,184,219);
    border: 2px solid white;
    border-radius: 10px;
    color: white;
    display: inline-block;
    font-size: 16px;
    text-decoration: none;
    text-align: center;
    padding: 10px;
    width: 160px;
    height: 100px;
    transition-duration: 0.2s;
    -webkit-transition-duration:0.2s;
    cursor: pointer;
    outline: none;
}
.button:hover{
    background-color: white;
    color: rgb(224,184,219);
    outline: none;
}
:focus, :visited{
    border: 2px solid rgb(153,217,234);
    outline: none;
    outline: 0;
}

JSFiddle: https://jsfiddle.net/mpbev9ay/1/

Body:
You also need to comment out the white space between <a> and <button>, see below.

div{
display: inline-block;
white-space: normal;
height: 623px;
padding: 10px;
padding-top: 0;
padding-left: 0;
vertical-align: top;
border-bottom: 3px solid black;
border: 1px solid black;
width: 500px;
}

.button{
background-color: rgb(224,184,219);
border: 2px solid white;
border-radius: 10px;
color: white;
display: inline-block;
font-size: 16px;
text-decoration: none;
text-align: center;
padding: 10px;
width: 160px;
height: 100px;
transition-duration: 0.2s;
-webkit-transition-duration:0.2s;
cursor: pointer;
outline: none;
}
.button:hover{
background-color: white;
color: rgb(224,184,219);
outline: none;
}
:focus, :visited{
border: 2px solid rgb(153,217,234);
outline: none;
outline: 0;
}

<a target="_blank" href= "https://Google.com"><!--
--><button class="button">
<strong>LinkedIn</strong><br>
</button></a><!--
--><a target="_blank"  href= "https://www.Google.com"><!--
--><button class="button">
<strong>GitHub</strong><br>
</button></a>
<br><!--
--><a target="_blank"  href= "https://www.Google.com"><!--
--><button class="button">
<strong>Stack Overflow</strong><br>
</button></a><!--
--><a target="_blank"  href= "https://www.Google.com"><!--
--><button class="button">
<strong>HackerRank</strong><br>
</button></a>

OR you can use onclick on <button>, as below

div{
display: inline-block;
white-space: normal;
height: 623px;
padding: 10px;
padding-top: 0;
padding-left: 0;
vertical-align: top;
border-bottom: 3px solid black;
border: 1px solid black;
width: 500px;
}

.button{
background-color: rgb(224,184,219);
border: 2px solid white;
border-radius: 10px;
color: white;
display: inline-block;
font-size: 16px;
text-decoration: none;
text-align: center;
padding: 10px;
width: 160px;
height: 100px;
transition-duration: 0.2s;
-webkit-transition-duration:0.2s;
cursor: pointer;
outline: none;
}
.button:hover{
background-color: white;
color: rgb(224,184,219);
outline: none;
}
:focus, :visited{
border: 2px solid rgb(153,217,234);
outline: none;
outline: 0;
}

<button class="button" onclick="window.open('https://Google.com','_blank')">
<strong>LinkedIn</strong><br></button><!--
--><button class="button" onclick="window.open('https://Google.com','_blank')">
<strong>GitHub</strong><br>
</button><br><!--
--><button class="button" onclick="window.open('https://Google.com','_blank')">
<strong>Stack Overflow</strong><br>
</button><!--
--><button class="button" onclick="window.open('https://Google.com','_blank')">
<strong>HackerRank</strong><br>
</button>


问:
while(multiple array lengths > 0)
I've found similar questions about my problem though the answers contain suggestions which do half of what I need - none of them do it all.

I need to develop a function which will cope with both:

an unknown number of arrays, AND...

of differing lengths AND...

alternately merge the arrays (added as edit)

I'm trying to write a function based on two I've found and believe I just need to figure the while() out, but I'm totally stumped. I can't seem to track down any examples of while loops that use an array in their conditions... if you follow.

```<code>function alternately_merge_arrays() {
  $arrays = func_get_args();
  $new_array = array();
  //

  while( count($array) in $arrays is > 0  ) {

  //
    foreach($arrays as $array) {
      if ( count($array) > 0 )
         $new_array[] = array_shift($array);
     }
  }
 return $new_array;
}

var_dump(alternately_merge_arrays(array(1,4), array(2,5,7), array(3,6,8,9));
</code>```

Of course I may be completely wrong and it needs to be something other than a while() loop. I'm cool using for() and foreach(), though if the first array is the shortest these would stop looping where while() should continue...

Edit: The output I need would be:

```<code>array(1,2,3,4,5,6,7,8,9)
</code>```

答:
You can build an array with keys that gives the position of each value according to this simple format: column#raw. Then all you have to do is to sort by keys and return the values:

```<code>function alternately_merge_arrays() {
    $result = [];
    foreach(func_get_args() as $n => &$array) {
        foreach ($array as $k => &$v) {
            $result["$k#$n"] = $v;
        }
    }
    ksort($result);
    return array_values($result);
}
</code>```

Title: while(multiple array lengths > 0)

Body:
I've found similar questions about my problem though the answers contain suggestions which do half of what I need - none of them do it all.

I need to develop a function which will cope with both:

an unknown number of arrays, AND...

of differing lengths AND...

alternately merge the arrays (added as edit)

I'm trying to write a function based on two I've found and believe I just need to figure the while() out, but I'm totally stumped. I can't seem to track down any examples of while loops that use an array in their conditions... if you follow.

function alternately_merge_arrays() {
  $arrays = func_get_args();
  $new_array = array();
  //

  while( count($array) in $arrays is > 0  ) {

  //
    foreach($arrays as $array) {
      if ( count($array) > 0 )
         $new_array[] = array_shift($array);
     }
  }
 return $new_array;
}

var_dump(alternately_merge_arrays(array(1,4), array(2,5,7), array(3,6,8,9));

Of course I may be completely wrong and it needs to be something other than a while() loop. I'm cool using for() and foreach(), though if the first array is the shortest these would stop looping where while() should continue...

Edit: The output I need would be:

array(1,2,3,4,5,6,7,8,9)

Body:
You can build an array with keys that gives the position of each value according to this simple format: column#raw. Then all you have to do is to sort by keys and return the values:

function alternately_merge_arrays() {
    $result = [];
    foreach(func_get_args() as $n => &$array) {
        foreach ($array as $k => &$v) {
            $result["$k#$n"] = $v;
        }
    }
    ksort($result);
    return array_values($result);
}


问:
How to make a button that has different parts?
I want to make a button that looks similar to the Club Penguin button you click when you want to join a server.

In this picture you see that the button has three main parts, the emoji, the name, and the amount of people playing.

How can I make a button that is similar to this with multiple parts? Or would a div be better for this? Either way, I want the user to be able to click on it.

This is what I tried but i'm having difficulties.

```<code><div id="container">
  <button id="button">
    <div id="first">
      Emoji
    </div>
    <div id="second">
      Name
    </div>
    <div id="third">
      Player count
    </div>
  </button>
</div>
</code>```

CSS:

```<code>#button {
  width:400px;
}
#first {
  float:left;
}
#second {
  float:center;
}
#third {
  float:right;
}
</code>```

https://jsfiddle.net/rmozk80x/

答:
If you need something similar to what you had, you might find this helpful.

inline-block display would give you more control over the flow.
Moreover, you can make it a div and use cursor: pointer; to make hovering at it look as if it was a button.

      #button {
        width:400px;
        height: 50px;
        border: 3px solid lightblue;
        border-radius: 25px;
        background: darkblue;
        cursor: pointer;
        color: white;
        font-wieght: 105%;
        font-family: Consolas;
      }

      #first {
        float:left;
        margin-left: 5px;
        margin-top: 3px;
        display: inline-block;
      }

      #second {
        display: inline-block;
        margin-left: 10px;
        margin-top: 15px;
      }
      #third {
        display: inline-block;
        float:right;
        margin-top: 15px;
        margin-right: 30px;
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div id="button" onclick="alert('you clicked me!')">
    <div id="first">
      <img src="http://cdn.hercampus.com/s3fs-public/styles/full_width_embed/public/2015/04/12/persons-0004_large.png" alt="Smiley face" height="42" width="42">
    </div>
    <div id="second">
      Name
    </div>
    <div id="third">
      Player count
    </div>
  </div>
</div></code>```

Body:
I want to make a button that looks similar to the Club Penguin button you click when you want to join a server.

In this picture you see that the button has three main parts, the emoji, the name, and the amount of people playing.

How can I make a button that is similar to this with multiple parts? Or would a div be better for this? Either way, I want the user to be able to click on it.

This is what I tried but i'm having difficulties.

  <button id="button">

      Emoji

      Name

      Player count

  </button>

CSS:

#button {
  width:400px;
}
#first {
  float:left;
}
#second {
  float:center;
}
#third {
  float:right;
}

https://jsfiddle.net/rmozk80x/

Body:
If you need something similar to what you had, you might find this helpful.

inline-block display would give you more control over the flow.
Moreover, you can make it a div and use cursor: pointer; to make hovering at it look as if it was a button.

      #button {
        width:400px;
        height: 50px;
        border: 3px solid lightblue;
        border-radius: 25px;
        background: darkblue;
        cursor: pointer;
        color: white;
        font-wieght: 105%;
        font-family: Consolas;
      }

      #first {
        float:left;
        margin-left: 5px;
        margin-top: 3px;
        display: inline-block;
      }

      #second {
        display: inline-block;
        margin-left: 10px;
        margin-top: 15px;
      }
      #third {
        display: inline-block;
        float:right;
        margin-top: 15px;
        margin-right: 30px;
      }

<div id="container">
  <div id="button" onclick="alert('you clicked me!')">
    <div id="first">
      <img src="http://cdn.hercampus.com/s3fs-public/styles/full_width_embed/public/2015/04/12/persons-0004_large.png" alt="Smiley face" height="42" width="42">
    </div>
    <div id="second">
      Name
    </div>
    <div id="third">
      Player count
    </div>
  </div>
</div>