问:
Lua Missing } unexpected
```<code>function love.load()
Tileset = love.graphics.newImage('countryside.png')

TileW, TileH = 32, 32
local tilesetW, tilesetH = Tileset:getWidth(), Tileset:getHeight()

Quads = {
    love.graphics.newQuad(0, 0, TileW, TileH, tilesetW, tilesetH) -- 1 = grass
    love.graphics.newQuad(32, 0, TileW, TileH, tilesetW, tilesetH) -- 2 = box
    love.graphics.newQuad(0, 32, TileW, TileH, tilesetW, tilesetH) -- 3 = flowers
    love.graphics.newQuad(32, 32, TileW, TileH, tilesetW, tilesetH) -- 4 = box
}

TileTable = {
    {1, 1, 1},
    {1, 2, 1},
    {1, 1, 1}
}

end
</code>```

This code gives this error:

Syntax error: main.lua:9: '}' expected (to close '{' at line 7) near 'love'

I don't understand it. Anyone got any help?

答:
In Lua, an array is initialized as below, hope it helps: </p>

```<code>Quads = {
    love.graphics.newQuad(0, 0, TileW, TileH, tilesetW, tilesetH), -- 1 = grass
    love.graphics.newQuad(32, 0, TileW, TileH, tilesetW, tilesetH), -- 2 = box
    love.graphics.newQuad(0, 32, TileW, TileH, tilesetW, tilesetH), -- 3 = flowers
    love.graphics.newQuad(32, 32, TileW, TileH, tilesetW, tilesetH), -- 4 = box
}
</code>```

Title: Lua Missing } unexpected

Body:
function love.load()
Tileset = love.graphics.newImage('countryside.png')

TileW, TileH = 32, 32
local tilesetW, tilesetH = Tileset:getWidth(), Tileset:getHeight()

Quads = {
    love.graphics.newQuad(0, 0, TileW, TileH, tilesetW, tilesetH) -- 1 = grass
    love.graphics.newQuad(32, 0, TileW, TileH, tilesetW, tilesetH) -- 2 = box
    love.graphics.newQuad(0, 32, TileW, TileH, tilesetW, tilesetH) -- 3 = flowers
    love.graphics.newQuad(32, 32, TileW, TileH, tilesetW, tilesetH) -- 4 = box
}

TileTable = {
    {1, 1, 1},
    {1, 2, 1},
    {1, 1, 1}
}

end

This code gives this error:

Syntax error: main.lua:9: '}' expected (to close '{' at line 7) near 'love'

I don't understand it. Anyone got any help?

Body:
In Lua, an array is initialized as below, hope it helps:

Quads = {
    love.graphics.newQuad(0, 0, TileW, TileH, tilesetW, tilesetH), -- 1 = grass
    love.graphics.newQuad(32, 0, TileW, TileH, tilesetW, tilesetH), -- 2 = box
    love.graphics.newQuad(0, 32, TileW, TileH, tilesetW, tilesetH), -- 3 = flowers
    love.graphics.newQuad(32, 32, TileW, TileH, tilesetW, tilesetH), -- 4 = box
}


来源: stackexchange

问:
Centralise div with minimum left margin
I am building a web site which has a navigation bar at the top. This bar consists of a logo in the top left corner, and a toolbar centralised in the window, as below. The logo is just an img tag with position:absolute to put it in the correct position, and the toolbar is a div with width:100% and the components centralised within it.

If the window is resized too small, or on tablet devices if the device is rotated to portrait, the toolbar overlaps the logo, like this:

I want the toolbar to stop moving when it reaches the logo, so if the window were resized it would like this:

I did find this solution:

css: how to build centered div with minimum spacing on the left

But the problem with this was that it relied on knowing the width of the centralised component (the toolbar), which cannot be guaranteed in this particular situation.

Thanks in advance for any help!

答:
You need to set both the logo and toolbar to {position: relative}. Then you need to set the toolbar to:

```<code>.toolbar {position: relative; float: right;}
</code>```

and the logo to:

```<code>img {position: relative; float: left}
</code>```

When the page is resized this should make them not overlap one another. You may also want to look into making a 'burger menu' for when the page is reduced past a certain point. I'd recommend doing this with media queries.

See the below Fiddle

https://jsfiddle.net/dbcv4yc7/

If you want your topbar to be central, then you'll need to put it into a div which takes up the rest of the right space.

Such as:

```<code>.logo {position: relative; float: left; width:30%; background-color: red}
.topbar {margin-left: auto; margin-right:auto; width:50%;background-color:red;}
.topbarContainer {float:right; width: 70%}
</code>```

Please see the below Fiddle:

https://jsfiddle.net/dbcv4yc7/1/

ContentLicense: CC BY-SA 3.0

Title: Centralise div with minimum left margin

Body:
You need to set both the logo and toolbar to {position: relative}. Then you need to set the toolbar to:

.toolbar {position: relative; float: right;}

and the logo to:

img {position: relative; float: left}

When the page is resized this should make them not overlap one another. You may also want to look into making a 'burger menu' for when the page is reduced past a certain point. I'd recommend doing this with media queries.

See the below Fiddle

https://jsfiddle.net/dbcv4yc7/

If you want your topbar to be central, then you'll need to put it into a div which takes up the rest of the right space.

Such as:

.logo {position: relative; float: left; width:30%; background-color: red}
.topbar {margin-left: auto; margin-right:auto; width:50%;background-color:red;}
.topbarContainer {float:right; width: 70%}

Please see the below Fiddle:

https://jsfiddle.net/dbcv4yc7/1/


问:
AJAX request from Cordova app returns 'status=0'
I have a question. I am developing a cordova application for ios, and I try to make an AJAX request using jQuery. The external server is whitelisted in the cordova.plist (in fact I whitelisted * just to be sure). I am sure the function is correct since I can manually call it in chrome, and it returns the correct data.

It however returns the following header data when run in the application:

{"readyState":0,"responseText":"","status":0,"statusText":"error"}

When crossDomain is changed to false it returns the following header data:
{"readyState":4,"responseText":"","status":404,"statusText":"error"}

```<code>$.ajax({
   type: "POST",
   url: url,
   data: request,
   crossDomain:true,
   success:
       function(data, textStatus, jqXHR){
           console.log('succes :S');
           console.log(data);
           console.log(textStatus);
           console.log(jqXHR);
       },
    error:
       function(data, textStatus, jqXHR){
           console.log('fail :(');
           console.log(data);
           console.log(textStatus);
           console.log(jqXHR);
       }
});
</code>```

I hope someone can tell me whats wrong, because I tried everything I can think of.

EDIT: Thank you guys, but I figured out what the problem was. The project used to have encryption and there where still some remnants of the code present in the native classes. So it en- or decrypted some URLs. This topic can be closed now.

答:
Remove below meta tag from your HTML file :

https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *">

Hope this works!!!

Body:
I have a question. I am developing a cordova application for ios, and I try to make an AJAX request using jQuery. The external server is whitelisted in the cordova.plist (in fact I whitelisted * just to be sure). I am sure the function is correct since I can manually call it in chrome, and it returns the correct data.

It however returns the following header data when run in the application:

{"readyState":0,"responseText":"","status":0,"statusText":"error"}

When crossDomain is changed to false it returns the following header data:
{"readyState":4,"responseText":"","status":404,"statusText":"error"}

$.ajax({
   type: "POST",
   url: url,
   data: request,
   crossDomain:true,
   success:
       function(data, textStatus, jqXHR){
           console.log('succes :S');
           console.log(data);
           console.log(textStatus);
           console.log(jqXHR);
       },
    error:
       function(data, textStatus, jqXHR){
           console.log('fail :(');
           console.log(data);
           console.log(textStatus);
           console.log(jqXHR);
       }
});

I hope someone can tell me whats wrong, because I tried everything I can think of.

EDIT: Thank you guys, but I figured out what the problem was. The project used to have encryption and there where still some remnants of the code present in the native classes. So it en- or decrypted some URLs. This topic can be closed now.


答:
If the number of branches is large, you might want to look at a binary search tree
This will reduce the maximum number of comparisons that any specific branch will need to be tested against (although the minimum number of tests will also increase).

e.g. The below case there is a minimum of 2 tests and a maximum of 3 tests. In your example above, there is a maximum of 4 tests.

```<code>if ($c< 202)
{
  if($c < 101){
    // action 101 here
  }
  else {
    // action 202 here
  }
}
else {
  if($c < 303){
    // action here
  }
  elseif($c < 404){
   // action here
}
</code>```

Edit : Depends on what you mean by 'shorten'. As per your title 'faster' am assuming performance.

Edit (you've updated the List) : Case in Point 'A' needs only one comparison test, whereas the 'AA' fall through will have failed ~25 tests. Assuming an even distribution of data across all bins, the average number of tests would be ~12 ('L') whereas in a binary tree formation, the most checks would be Log2(N) + 1 - i.e. 6 tests would cover 32 branches. Unfortunately in your case, there are gaps in the data on the even '100's. If you exclude these (i.e. if value MOD 100 == 0 then fall through to 'AA') then you can do just a one sided test for the rest of the permutations.

ContentLicense: CC BY-SA 2.5

Title: Faster way to check if integer is in any of ranges?

Body:
I wonder if there is another way to shorten this ? Here is the example im looking for to do same thing just shorter.

if($c <= 100){
    echo 'A';
}elseif($c <= 200 && $c > 100){
    echo 'B';
}elseif($c <= 300 && $c > 200){
    echo 'C';
}elseif($c <= 400 && $c > 300){
    echo 'D';
}elseif($c <= 500 && $c > 400){
    echo 'E';
}elseif($c <= 600 && $c > 500){
    echo 'F';
}elseif($c <= 700 && $c > 600){
    echo 'Z';
}elseif($c <= 800 && $c > 700){
    echo 'H';
}elseif($c <= 900 && $c > 800){
    echo 'I';
}elseif($c < 1000 && $c > 900){
    echo 'K';
}elseif($c <= 1100 && $c > 1000){
    echo 'L';
}elseif($c <= 1200 && $c > 1100){
    echo 'M';
}elseif($c < 1300 && $c > 1200){
    echo 'N';
}elseif($c <= 1400 && $c > 1300){
    echo 'O';
}elseif($c <= 1500 && $c > 1400){
    echo 'P';
}elseif($c <= 1600 && $c > 1500){
    echo 'Q';
}elseif($c <= 1700 && $c > 1600){
    echo 'R';
}elseif($c <= 1800 && $c > 1700){
    echo 'S';
}elseif($c <= 1900 && $c > 1800){
    echo 'T';
}elseif($c <= 2000 && $c > 1900){
    echo 'V';
}elseif($c <= 2100 && $c > 2000){
    echo 'X';
}else{
    echo 'AA';
}

Body:
If the number of branches is large, you might want to look at a binary search tree
This will reduce the maximum number of comparisons that any specific branch will need to be tested against (although the minimum number of tests will also increase).

e.g. The below case there is a minimum of 2 tests and a maximum of 3 tests. In your example above, there is a maximum of 4 tests.

if ($c< 202)
{
  if($c < 101){
    // action 101 here
  }
  else {
    // action 202 here
  }
}
else {
  if($c < 303){
    // action here
  }
  elseif($c < 404){
   // action here
}

Edit : Depends on what you mean by 'shorten'. As per your title 'faster' am assuming performance.

Edit (you've updated the List) : Case in Point 'A' needs only one comparison test, whereas the 'AA' fall through will have failed ~25 tests. Assuming an even distribution of data across all bins, the average number of tests would be ~12 ('L') whereas in a binary tree formation, the most checks would be Log2(N) + 1 - i.e. 6 tests would cover 32 branches. Unfortunately in your case, there are gaps in the data on the even '100's. If you exclude these (i.e. if value MOD 100 == 0 then fall through to 'AA') then you can do just a one sided test for the rest of the permutations.


问:
How to do "quick structure" in IntelliJ IDEA?
There is an awesome Quick Definition which shows overlay dialog with definition of an object currently under the cursor (so you don't have to jump in files).

Is there a way how to access similar functionality, but rather Quick Structure (like the dock on left ALT + 7), but on the object under cursor (when cursor is not on its definition, but on an instance/type)?

Example:

```<code>fileA:
class A { ... }

fileB:
class B extends A { ... }

file:
const a: X<B> = ...;
</code>```

In file when on B I could press shortcut and it would show me structure of the type B - so not only members defined in B (for which could be used Quick Definition), but also all inherited members (in this case defined in A).

答: Use the Navigate | File Structure menu item. Cmd+F12 by default on the Mac.

Body:
There is an awesome Quick Definition which shows overlay dialog with definition of an object currently under the cursor (so you don't have to jump in files).

Is there a way how to access similar functionality, but rather Quick Structure (like the dock on left ALT + 7), but on the object under cursor (when cursor is not on its definition, but on an instance/type)?

Example:

fileA:
class A { ... }

fileB:
class B extends A { ... }

file:
const a: X = ...;

In file when on B I could press shortcut and it would show me structure of the type B - so not only members defined in B (for which could be used Quick Definition), but also all inherited members (in this case defined in A).


问:
Joomla full article
I had a blog on the home page of my Joomla website. I decided to move it to the link "home/news"( on bosnian language "/pocetna/novosti"). Now I have a problem that I can not open the full article.
So, before the blog was on https://bascarsija.info, and now is on https://bascarsija.info/pocetna/novosti. I can open blog and intro articles, but  when I try to open the full article at the link missing menu and category name so I have empty page.
The link should be: bascarsija.info/pocetna/novosti/some-article
And now is without menu and category name: bascarsija.info/some-article

When I manually add: /pocetna/novosti everything is OK

My cash is turned off, I tried reinstalling Joomla, but the problem is not solved. I checked in the database menu path is correct (/pocetna/novosti)

Hoe can I solve this?

答:
How you publish your articles in Novosti page? Maybe the problem is there. Try to use Joomla native content component.

Try also to view the website using the default Joomla template (protostar) to avoid any overrides of the Joomla content component.

Title: Joomla full article


问:
C# correct and efficient conversion of double to decimal
What is the most efficient (and strictly correct) way to convert from a double to a decimal rounded to n places of precision?

I am using decimal.Round((decimal)d, n, MidpointRounding.AwayFromZero) but it occurs to me that I am rounding twice here- once duing the cast (decimal)d and once via Round().

Is there a way to directly round a double to a decimal to n places?  I suppose I can round trip it via strings but that seems ugly and expensive.

5/12/2017: i added an issue to corefx github here https://github.com/dotnet/corefx/issues/19706

答:
You want to do two steps:

Convert to decimal

Round to n places

You can't reduce these steps to one. Even if there were a function which gets a double number und int places as parameters, it has to do these two steps.


问:
how to cast up to super class when there is an override function in the sub class
A super-class Car and a sub-class Jaguar was created. The function info() -> Void in the sub-class overrided the super-class' function. A instance named theAuto of type Jaguar had been created.

Problem:

Seems I cannot up casts the theAuto to the type of Car, please see the code snippet and its comments

```<code>class Car {
        func info() {
                print("You've got a car")
        }
}

class Jaguar : Car {
       override func info() {
               print("You've got a Jaguar")
       }
}

let theAuto = Jaguar()
theAuto.info() // --> You've got a Jaguar
let auto = theAuto as Car // casting but seems not working
auto.info() // --> You've got a Jaguar
print(type(of: auto)) // fail to casting
</code>```

Question:

I think I didn't fully understand the concept of casting together with override scenario. Why I cannot make the up casting? Is the override action limited my upper casting?

many thanks for your help and time

答:
theAuto is always a Jaguar. It is also always a Car. However, calling info() will always return the implementation for the most specific type and so will always print

You've got a Jaguar

Regarding casting:

```<code>let car1 : Car = Jaguar()
let car2 : Car = BMW()

if let automobile = car1 as? Jaguar {
    print ("The automobile is a Jaguar")
    car1.info()
}

if let automobile = car2 as? Jaguar {
    print ("The automobile is a Jaguar")
    car2.info()
}
</code>```

prints

The automobile is a Jaguar

  You've got a Jaguar

Only the first section prints. The second car cannot be cast to a Jaguar, because it is a BMW.

Body:
A super-class Car and a sub-class Jaguar was created. The function info() -> Void in the sub-class overrided the super-class' function. A instance named theAuto of type Jaguar had been created.

Problem:

Seems I cannot up casts the theAuto to the type of Car, please see the code snippet and its comments

class Car {
        func info() {
                print("You've got a car")
        }
}

class Jaguar : Car {
       override func info() {
               print("You've got a Jaguar")
       }
}

let theAuto = Jaguar()
theAuto.info() // --> You've got a Jaguar
let auto = theAuto as Car // casting but seems not working
auto.info() // --> You've got a Jaguar
print(type(of: auto)) // fail to casting

Question:

I think I didn't fully understand the concept of casting together with override scenario. Why I cannot make the up casting? Is the override action limited my upper casting?

many thanks for your help and time

Body:
theAuto is always a Jaguar. It is also always a Car. However, calling info() will always return the implementation for the most specific type and so will always print

You've got a Jaguar

Regarding casting:

let car1 : Car = Jaguar()
let car2 : Car = BMW()

if let automobile = car1 as? Jaguar {
    print ("The automobile is a Jaguar")
    car1.info()
}

if let automobile = car2 as? Jaguar {
    print ("The automobile is a Jaguar")
    car2.info()
}

prints

The automobile is a Jaguar

  You've got a Jaguar

Only the first section prints. The second car cannot be cast to a Jaguar, because it is a BMW.


问:
R dplyr mutate on column index
Building on this question: dplyr: how to reference columns by column index rather than column name using mutate?

I want to mutate using column indexes for both the source and the destination of the mutate:

```<code>iris %>% head %>% mutate(.[[1]] = .[[1]] + .[[2]])
</code>```

gives:

```<code>Error: unexpected '=' in "iris %>% head %>% mutate(.[[1]] =".
</code>```

However, the following works:

```<code>iris %>% head %>% mutate(sum = .[[1]] + .[[2]])
</code>```

答:
We can do this in base R

```<code>iris[[1]] <- iris[[1]] + iris[[2]]
</code>```

Title: R dplyr mutate on column index

Body:
Building on this question: dplyr: how to reference columns by column index rather than column name using mutate?

I want to mutate using column indexes for both the source and the destination of the mutate:

iris %>% head %>% mutate(.[[1]] = .[[1]] + .[[2]])

gives:

Error: unexpected '=' in "iris %>% head %>% mutate(.[[1]] =".

However, the following works:

iris %>% head %>% mutate(sum = .[[1]] + .[[2]])

Body:
We can do this in base R

iris[[1]] <- iris[[1]] + iris[[2]]


问:
Using WCF Web Service to output database information on client side using c#
I have created a WCF Web Service using this walk through:

http://mikesknowledgebase.com/pages/Services/WebServices-Page2.htm

It returns data from a local SQL Server.  The WCF Web Service takes a string parameter, and returns it back, as a string in JSON format.

I have now created a client website where i want to use the WCF Services as my data source to output the information in the database through a grid view or something similar.  How do i do this?  I assume i have to use some c#.

Service.cs:

```<code>public class Service : IService
{
private object cds;
public List<cdInfo> GetCDinfo()
{
    try
    {
        CdDataClassesDataContext dc = new CdDataClassesDataContext();
        List<cdInfo> results = new List<cdInfo>();

        foreach (cd cD in dc.cds)
        {
            results.Add(new cdInfo()
            {
                Id = cD.Id.ToString(),
                artist = cD.artist,
                genre = cD.genre,
                title = cD.title,
                date = cD.date
            });}
        return results;
    }
    catch (Exception ex)
    {
        //  Return any exception messages back to the Response header
        OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
        response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
        response.StatusDescription = ex.Message.Replace("\r\n", "");
        return null;}}}
</code>```

答:
Hopefully this link will help you in consuming WCF service.

https://msdn.microsoft.com/en-us/library/bb412178(v=vs.110).aspx

Body:
I have created a WCF Web Service using this walk through:

http://mikesknowledgebase.com/pages/Services/WebServices-Page2.htm

It returns data from a local SQL Server.  The WCF Web Service takes a string parameter, and returns it back, as a string in JSON format.

I have now created a client website where i want to use the WCF Services as my data source to output the information in the database through a grid view or something similar.  How do i do this?  I assume i have to use some c#.

Service.cs:

public class Service : IService
{
private object cds;
public List<cdInfo> GetCDinfo()
{
    try
    {
        CdDataClassesDataContext dc = new CdDataClassesDataContext();
        List<cdInfo> results = new List<cdInfo>();

        foreach (cd cD in dc.cds)
        {
            results.Add(new cdInfo()
            {
                Id = cD.Id.ToString(),
                artist = cD.artist,
                genre = cD.genre,
                title = cD.title,
                date = cD.date
            });}
        return results;
    }
    catch (Exception ex)
    {
        //  Return any exception messages back to the Response header
        OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
        response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
        response.StatusDescription = ex.Message.Replace("\r\n", "");
        return null;}}}


问:
Select same table twice, in single query
My table:

```<code>id | views | date
1  | 100   | 2017-03-09
2  | 150   | 2017-03-10
3  | 300   | 2017-03-11
4  | 350   | 2017-03-12
</code>```

I need to calculate visit count difference between days something like this

```<code>2017-03-12-->Visitors:350
2017-03-11-->Visitors:300
Difference between days:50

2017-03-11-->Visitors:300
2017-03-10-->Visitors:150
Difference between days:150

2017-03-10-->Visitors:150
2017-03-09-->Visitors:100
Difference between days:50

and so on...
</code>```

I managed to get similar results, but not exatcly what i wanted

```<code>$sql = "SELECT * FROM `table` ORDER BY `table`.`id` DESC";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{

    $t = $row['views'];
    $dat = $row['date'];

    $sql1 = "SELECT * FROM `table` ORDER BY `table`.`id` DESC LIMIT 1, 99";
    $result1 = mysql_query($sql1) or die(mysql_error());
    while($row1 = mysql_fetch_array($result1))
    {

        $y = $row1['views'];
        $dat1 = $row1['date'];

        $d = $t-$y;

        echo "{$dat}-->Visitors:{$t}";
        echo "<br/>";
        echo "{$dat1}-->Visitors:{$y}";
        echo "<br/>";
        echo "Difference between days:{$d}";
        echo "<br/><br/><br/>";
    }
}
</code>```

So i guess i need to select same table twice with one query.

答:
Try this to handle it in MySQL.

http://rextester.com/XXJWR75843

```<code>set @views1=0;
select t.* ,views-lag_views from (
select t1.*,@views1 lag_views , @views1:=views curr_views
from Table1 t1
    ) t
</code>```

But you need to figure out a way to ignore first value, as it gives you same value as views.

Thanks for this answer to replicate lag function.

Body:
My table:

id | views | date
1  | 100   | 2017-03-09
2  | 150   | 2017-03-10
3  | 300   | 2017-03-11
4  | 350   | 2017-03-12

I need to calculate visit count difference between days something like this

2017-03-12-->Visitors:350
2017-03-11-->Visitors:300
Difference between days:50

2017-03-11-->Visitors:300
2017-03-10-->Visitors:150
Difference between days:150

2017-03-10-->Visitors:150
2017-03-09-->Visitors:100
Difference between days:50

and so on...

I managed to get similar results, but not exatcly what i wanted

$sql = "SELECT * FROM `table` ORDER BY `table`.`id` DESC";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{

    $t = $row['views'];
    $dat = $row['date'];

    $sql1 = "SELECT * FROM `table` ORDER BY `table`.`id` DESC LIMIT 1, 99";
    $result1 = mysql_query($sql1) or die(mysql_error());
    while($row1 = mysql_fetch_array($result1))
    {

        $y = $row1['views'];
        $dat1 = $row1['date'];

        $d = $t-$y;

        echo "{$dat}-->Visitors:{$t}";
        echo "
";
        echo "{$dat1}-->Visitors:{$y}";
        echo "
";
        echo "Difference between days:{$d}";
        echo "

";
    }
}

So i guess i need to select same table twice with one query.

Body:
Try this to handle it in MySQL.

http://rextester.com/XXJWR75843

set @views1=0;
select t.* ,views-lag_views from (
select t1.*,@views1 lag_views , @views1:=views curr_views
from Table1 t1
    ) t

But you need to figure out a way to ignore first value, as it gives you same value as views.

Thanks for this answer to replicate lag function.


问:
Selecting Folder Destination in Java?
I am a newbie to Java. I am trying to dynamically choose the file location to save the outcome of my project (to be initiated at the very start of my project). I worked around with a few FileDialog examples, but each one of them allows me to choose a file and not a folder.

Can anyone please help me with an example (or) link to one for the same?

答:
Along with JFileChooser is possible use this:

```<code>UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
</code>```

for have a Look and Feel like Windows.

for others settings, view here:
https://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html#available

Title: Selecting Folder Destination in Java?

Body:
Along with JFileChooser is possible use this:

UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

for have a Look and Feel like Windows.

for others settings, view here:
https://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html#available


问:
Memory keeps allocated after method ends
I'm developing a Windows Service with C# and .NET Framework 4.6.2 and Entity Framework 6.1.3.

I have a Web API interface on that service and in one Controller's method I create a Dictionary with more than one million strings:

```<code>Dictionary<string, List<string>> codes;
</code>```

This Dictionary is created inside another method:

```<code>codes = GetCodesAsDictionary(connectionString, productionId);
</code>```

I pass this variable to a static method from a static class.

One Visual Studio 2015's memory profiler I see how memory grows to 1,1Gb when I call this method, but when the method ends, the memory keep as 1,1Gb.

If I call the method again, memory grows again to 2Gb, and after method finishes, memory goes to 1,1Gb again.

I have tried to pass the codes variable as reference, but I get the same memory allocation. I have to stop the service and re-run it again to release that 1,1Gb. By the way, I pass it by reference because I don't want that the static method makes a copy of it.

Do you know why it doesn't release such amount of memory after method ends?

UPDATE:

I have changed the static class with an instance class (copying the method from static class) and I get the same result (1,1Gb memory allocated).

SECOND UPDATE:

I have also changed how the dictionary is created:

```<code>Dictionary<string, List<string>> codes = null;
GetCodesAsDictionary(connectionString, productionId, out codes);
</code>```

And I get the same result: 1,1Gb memory allocated.

THIRD UPDATE:

I have changed the Dictionary with a KeyValuePair<byte, string[]>[] and I get the same result, 1,1Gb allocated. Now, instead of using a string as key, I'm using byte.

答:
Do you know why it doesn't release such amount of memory after method ends?

If there aren't any references hanging around any more, it could just be that the garbage collector doesn't feel the urge to free that memory, even though it isn't in use any more.

You can try to force garbage collection and see if the memory is freed. If not, there is probably an issue with your code.

(Side note: if you have a high amount of repetition in the strings, you might benefit from interning them. It will minimize the memory pressure a lot. This will however keep those strings allocated at all time.)

Body:
I'm developing a Windows Service with C# and .NET Framework 4.6.2 and Entity Framework 6.1.3.

I have a Web API interface on that service and in one Controller's method I create a Dictionary with more than one million strings:

Dictionary<string, List<string>> codes;

This Dictionary is created inside another method:

codes = GetCodesAsDictionary(connectionString, productionId);

I pass this variable to a static method from a static class.

One Visual Studio 2015's memory profiler I see how memory grows to 1,1Gb when I call this method, but when the method ends, the memory keep as 1,1Gb.

If I call the method again, memory grows again to 2Gb, and after method finishes, memory goes to 1,1Gb again.

I have tried to pass the codes variable as reference, but I get the same memory allocation. I have to stop the service and re-run it again to release that 1,1Gb. By the way, I pass it by reference because I don't want that the static method makes a copy of it.

Do you know why it doesn't release such amount of memory after method ends?

UPDATE:

I have changed the static class with an instance class (copying the method from static class) and I get the same result (1,1Gb memory allocated).

SECOND UPDATE:

I have also changed how the dictionary is created:

Dictionary<string, List<string>> codes = null;
GetCodesAsDictionary(connectionString, productionId, out codes);

And I get the same result: 1,1Gb memory allocated.

THIRD UPDATE:

I have changed the Dictionary with a KeyValuePair<byte, string[]>[] and I get the same result, 1,1Gb allocated. Now, instead of using a string as key, I'm using byte.


问:
What is wrong with my logic my button only changes once and the onclick function stops?
I want a button to switch between F and C each time i do the click but when i click the button a third time it just doesn't work even though i set back the class to <code>.temp</code>. </p>

```<code>$(".temp").click(function() {
  $('#temperature').empty();
  $("#temperature").append(temp.main.temp + " <a class='temper' href='#'>C</a>");

  $(".temper").click(function() {
    $('#temperature').empty();
    $('#temperature').append(data.main.temp +" <a class='temp' href='#'>F</a>");
  });
});
</code>```

答:
I guess you are about to use live jquery event, this can help :</p>

```<code>$(document).on("click", ".temp", function() {});
$(document).on("click", ".temper", function() {});
</code>```

Body:
I want a button to switch between F and C each time i do the click but when i click the button a third time it just doesn't work even though i set back the class to .temp.

$(".temp").click(function() {
  $('#temperature').empty();
  $("#temperature").append(temp.main.temp + " C");

  $(".temper").click(function() {
    $('#temperature').empty();
    $('#temperature').append(data.main.temp +" F");
  });
});

Body:
I guess you are about to use live jquery event, this can help :

$(document).on("click", ".temp", function() {});
$(document).on("click", ".temper", function() {});


问:
Java getContentPane().setBackground() not working
Im trying to encapsulate the GUI calls to a single class. My window appears but the background remains the default color instead of red.

ChatProgram.java

```<code>package ChatPkg;

public class ChatProgram {

    /**
     * Launch the application.
     */
    public static void main(String[] args) {

        ChatWindow.initialize();
        ChatWindow.RunWindow();

    }

}
</code>```

ChatWindow.java

```<code>package ChatPkg;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.ListSelectionModel;

public final class ChatWindow {

    static JFrame frame;

    /**
     * Create the application.
     */
    private ChatWindow() { }

    public static void RunWindow() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Initialize the contents of the frame.
     */
    public static void initialize() {
        frame = new JFrame("Chat program");
        frame.setBounds(100, 100, 450, 450);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JCheckBox chckbxCvbc = new JCheckBox("cvbc");
        frame.getContentPane().add(chckbxCvbc);

        // Set background color
        frame.getContentPane().setBackground(Color.red);
    }

}
</code>```

Yes i am new to Java and none of the google results solved my problem.

答:
You should NOT add GUI components directly to the content pane of the JFrame. Also, you shouldn't modify its properties (like you tried changing the background).

You always need a JPanel that acts as a container on which the graphical elements are added. Here is how you could write your initialize function:

```<code>public static void initialize() {
    frame = new JFrame("Chat program");
    frame.setBounds(100, 100, 450, 450);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel();

    JCheckBox chckbxCvbc = new JCheckBox("cvbc");
    panel.add(chckbxCvbc);

    // Set background color and add panel to the Jframe
    panel.setBackground(Color.RED);
    frame.getContentPane().add(panel);
}
</code>```

Body:
Im trying to encapsulate the GUI calls to a single class. My window appears but the background remains the default color instead of red.

ChatProgram.java

package ChatPkg;

public class ChatProgram {

    /**
     * Launch the application.
     */
    public static void main(String[] args) {

        ChatWindow.initialize();
        ChatWindow.RunWindow();

    }

}

ChatWindow.java

package ChatPkg;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.ListSelectionModel;

public final class ChatWindow {

    static JFrame frame;

    /**
     * Create the application.
     */
    private ChatWindow() { }

    public static void RunWindow() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Initialize the contents of the frame.
     */
    public static void initialize() {
        frame = new JFrame("Chat program");
        frame.setBounds(100, 100, 450, 450);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JCheckBox chckbxCvbc = new JCheckBox("cvbc");
        frame.getContentPane().add(chckbxCvbc);

        // Set background color
        frame.getContentPane().setBackground(Color.red);
    }

}

Yes i am new to Java and none of the google results solved my problem.

Body:
You should NOT add GUI components directly to the content pane of the JFrame. Also, you shouldn't modify its properties (like you tried changing the background).

You always need a JPanel that acts as a container on which the graphical elements are added. Here is how you could write your initialize function:

public static void initialize() {
    frame = new JFrame("Chat program");
    frame.setBounds(100, 100, 450, 450);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel();

    JCheckBox chckbxCvbc = new JCheckBox("cvbc");
    panel.add(chckbxCvbc);

    // Set background color and add panel to the Jframe
    panel.setBackground(Color.RED);
    frame.getContentPane().add(panel);
}


问:
Android : First digit is not displaying when using decimal input filter with NumberFormat
In my android application I am using a decimal input filter to block the number of digits before decimal seperator(.) to 14 and after dot to 4, also using a NumberFormat with US locale to format the amount entered by user.I have noticed 2 problem when i try this as below.

Can't enter decimal digits when there is 14 integer digits.Can enter decimal when there is less than 14 Integer digits.

When change an amount greater than 999 then the first digit entered by user is not registering, I noticed that any number greater than 999 will formatted with a comma so when changing those amount with new amount the first digit typed will not come, why so.Suppose the Edittext contain the amount 4,000.00 and then changed to 9500 then only 500 is displayed.but when we change an amount like 450.00 there is no comma then no problem,all digit will come.Below is my code.

NumberFormat formatUsTwo = NumberFormat.getInstance(Locale.US);

```<code>edtAmount=(EditText) v.findViewById(R.id.edtAmount);
edtAmount.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(14,4)});
edtAmount.setText(formatUsTwo.format(9000));

edtAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if(!hasFocus){
Double  change=Double.parseDouble(edtAmount.getText().toString().trim().replace(",", ""));
                    edtAmount.setText(formatUsTwo.format(change));
                }else{
                    onFocus(view, holder);
                }
            }
        });

public class DecimalDigitsInputFilter implements InputFilter {
Pattern mPattern;
public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
                mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((\\.[0-9]{0," + (digitsAfterZero - 1) + "})?)||(\\.)?");
            }

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                Matcher matcher = mPattern.matcher(dest);
                if (!matcher.matches())
                    return "";
                return null;
            }
        }
</code>```

答:
Finally I solved the problem after spending half of the day.I changed my DecimalInputDegitsFilter class ass below which solved both the problem.</p>

```<code>        public class DecimalDigitsInputFilter implements InputFilter {

        Pattern mPattern;
        int digitsBeforeZero,digitsAfterZero;

        public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
            this.digitsBeforeZero = digitsBeforeZero;
            this.digitsAfterZero = digitsAfterZero;
            mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((\\.[0-9]{0," + (digitsAfterZero - 1) + "})?)||(\\.)?");
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            Matcher matcher = mPattern.matcher(dest.toString().replace(",", ""));
            if (!matcher.matches()) {
                if (dest.toString().contains(".")) {
                    if (dest.toString().substring(dest.toString().indexOf(".")).length() > digitsAfterZero) {
                        return "";
                    }
                    return null;
                } else if (!Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}").matcher(dest).matches()) {
                    if (!dest.toString().contains(".")) {
                        if (source.toString().equalsIgnoreCase(".")) {
                            return null;
                        }
                    }
                    return "";
                }
                return "";
            }
            return null;
        }
    }
</code>```

Body:
In my android application I am using a decimal input filter to block the number of digits before decimal seperator(.) to 14 and after dot to 4, also using a NumberFormat with US locale to format the amount entered by user.I have noticed 2 problem when i try this as below.

Can't enter decimal digits when there is 14 integer digits.Can enter decimal when there is less than 14 Integer digits.

When change an amount greater than 999 then the first digit entered by user is not registering, I noticed that any number greater than 999 will formatted with a comma so when changing those amount with new amount the first digit typed will not come, why so.Suppose the Edittext contain the amount 4,000.00 and then changed to 9500 then only 500 is displayed.but when we change an amount like 450.00 there is no comma then no problem,all digit will come.Below is my code.

NumberFormat formatUsTwo = NumberFormat.getInstance(Locale.US);

edtAmount=(EditText) v.findViewById(R.id.edtAmount);
edtAmount.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(14,4)});
edtAmount.setText(formatUsTwo.format(9000));

edtAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if(!hasFocus){
Double  change=Double.parseDouble(edtAmount.getText().toString().trim().replace(",", ""));
                    edtAmount.setText(formatUsTwo.format(change));
                }else{
                    onFocus(view, holder);
                }
            }
        });

public class DecimalDigitsInputFilter implements InputFilter {
Pattern mPattern;
public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
                mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((\\.[0-9]{0," + (digitsAfterZero - 1) + "})?)||(\\.)?");
            }

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                Matcher matcher = mPattern.matcher(dest);
                if (!matcher.matches())
                    return "";
                return null;
            }
        }

Body:
Finally I solved the problem after spending half of the day.I changed my DecimalInputDegitsFilter class ass below which solved both the problem.

        public class DecimalDigitsInputFilter implements InputFilter {

        Pattern mPattern;
        int digitsBeforeZero,digitsAfterZero;

        public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
            this.digitsBeforeZero = digitsBeforeZero;
            this.digitsAfterZero = digitsAfterZero;
            mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((\\.[0-9]{0," + (digitsAfterZero - 1) + "})?)||(\\.)?");
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            Matcher matcher = mPattern.matcher(dest.toString().replace(",", ""));
            if (!matcher.matches()) {
                if (dest.toString().contains(".")) {
                    if (dest.toString().substring(dest.toString().indexOf(".")).length() > digitsAfterZero) {
                        return "";
                    }
                    return null;
                } else if (!Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}").matcher(dest).matches()) {
                    if (!dest.toString().contains(".")) {
                        if (source.toString().equalsIgnoreCase(".")) {
                            return null;
                        }
                    }
                    return "";
                }
                return "";
            }
            return null;
        }
    }


问:
Multiple File Upload Contact Form 7
Having read the question here: Jquery function multiple upload fields add indivdually

There still hasn't been any answer as to how to get the multiple files to actually be delivered to the email client. Does anyone have any insight into avenues I could try to get this to actually work?

答: I managed to figure this out. You need to ensure there are spaces between the [file] shortcodes in the File Attachments section of CF7 Mail tab.

Title: Multiple File Upload Contact Form 7


问:
AuthorizeNET CIM Payments
I have moved Authorize.NET AIM to CIM. I have two questions to solve:

In Authorize.NET live account I can see two transaction for one transaction one is 0$ voided transaction and other one is real transaction, can I avoid 0$ transaction or it is for what?

```<code>$email_address = 'user' . time() . '@domain.com';
$description   = 'Monthly Membership No. ' . md5(uniqid(rand(), true));
$customer_id   = substr(md5(uniqid(rand(), true)), 16, 16);

// Create the profile
$cim->setParameter('email', $email_address);
$cim->setParameter('description', $description);
$cim->setParameter('merchantCustomerId', $customer_id);
$cim->createCustomerProfile();
</code>```

In the above code can we sent customer real email instead of generated email?
will it be a compliance issue?

答:
The $0 transaction is to verify the credit card is valid before creating the customer payment profile. No, you cannot stop it from happening and you want this to occur as it allows you to get immediate feedback if a payment profile is invalid. That way you can react to it immediately rather then waiting for their first payment to fail.

Yes, you can, and should, send the correct customer email. That random email is just an example to show you how it works. The same goes for  the $description and $customer_id fields as well.

Title: AuthorizeNET CIM Payments

Body:
I have moved Authorize.NET AIM to CIM. I have two questions to solve:

In Authorize.NET live account I can see two transaction for one transaction one is 0$ voided transaction and other one is real transaction, can I avoid 0$ transaction or it is for what?

$email_address = 'user' . time() . '@domain.com';
$description   = 'Monthly Membership No. ' . md5(uniqid(rand(), true));
$customer_id   = substr(md5(uniqid(rand(), true)), 16, 16);

// Create the profile
$cim->setParameter('email', $email_address);
$cim->setParameter('description', $description);
$cim->setParameter('merchantCustomerId', $customer_id);
$cim->createCustomerProfile();

In the above code can we sent customer real email instead of generated email?
will it be a compliance issue?


问:
How to make SharedPreferences from a PreferenceActivity be set to default in Android?
I have created a PreferenceActivity based on xml for PreferenceScreen. In the xml you can assign default values to the different preferences. But these are not stored in my SharedPreferences before the screen is opened and closed.

The problem is that I want to immediately use the Preferences stored in this screen (like server address), and the user will only need to open it if he wants to change the default values.

Is there a way to store all the preferences from the preferencescreen xml without forcing the user to open and close the preference activity?

I am aware that you can supply a default value when retrieving the Preference from SharedPreferences, but it is stupid to have to maintain default values both in xml and code.

答:
Just use this code in the Application class.

```<code>PreferenceManager.setDefaultValues(this, R.xml.preference, false);
</code>```

It will load your preferences from XML, and last parameter (readAgain) will guarantee that user preferences won't be overwritten. You need to maintain the default parameters in the R.xml.preference file.

Take a look into PreferenceManager.setDefaultValues in Android API for further investigation.

Body:
Just use this code in the Application class.

PreferenceManager.setDefaultValues(this, R.xml.preference, false);

It will load your preferences from XML, and last parameter (readAgain) will guarantee that user preferences won't be overwritten. You need to maintain the default parameters in the R.xml.preference file.

Take a look into PreferenceManager.setDefaultValues in Android API for further investigation.


问:
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.

答:
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?

Nope, there isn't such a trigger. Component is responsible for providing you a dependency. If you are done with one Component and you want to invalidate it (i.e. your dependencies to be created again) you have to dispose from it (null out) and create a new Component. Now all your dependencies will be created again.

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.


问:
SQL GROUP BY explanation
So I have been playing around with SQL for a while now, and i can't seem to get the group by function down. For example, I have been using the w3schools online database with SQL, and experimenting with it.
One problem I can't seem to crack is to update the prices of products from the same supplier, and that their sum is some number.

Here is the link to the database: https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all

So what I came up with was this:

```<code>    UPDATE Products
    SET Price=Price*100
    WHERE 47=(SELECT SUM(p.Price) FROM Products p GROUP BY p.SupplierID)
</code>```

It seems to update the whole database. I expected it only to update the prices of the products that belong to the first supplier, as the sum of their prices is 47. I guess I'm making some rookie mistake, but I just can't seem to get it right.

Edit:
My expected result would be that all rows from table Products who have supplierID=1 would update the price(Although it's not that I'm just aiming at the 1st supplier, but any supplier who's products prices sum up to 47), but what happens is that all the prices get updated, regardless of the supplier or the sum of their prices. But when I change the number from 47, nothing seems to happen.

答:
Please try this:</p>

```<code>UPDATE [Products]
SET  [Products].Price = [Products].Price*100
FROM    [Products]
        INNER JOIN (SELECT  p.SupplierID, SUM(p.Price) NewPrice
                    FROM Products p
                    GROUP BY p.SupplierID) B
        ON B.SupplierID = [Products].SupplierID
WHERE 47 = B.NewPrice
</code>```

Title: SQL GROUP BY explanation

Body:
So I have been playing around with SQL for a while now, and i can't seem to get the group by function down. For example, I have been using the w3schools online database with SQL, and experimenting with it.
One problem I can't seem to crack is to update the prices of products from the same supplier, and that their sum is some number.

Here is the link to the database: https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all

So what I came up with was this:

    UPDATE Products
    SET Price=Price*100
    WHERE 47=(SELECT SUM(p.Price) FROM Products p GROUP BY p.SupplierID)

It seems to update the whole database. I expected it only to update the prices of the products that belong to the first supplier, as the sum of their prices is 47. I guess I'm making some rookie mistake, but I just can't seem to get it right.

Edit:
My expected result would be that all rows from table Products who have supplierID=1 would update the price(Although it's not that I'm just aiming at the 1st supplier, but any supplier who's products prices sum up to 47), but what happens is that all the prices get updated, regardless of the supplier or the sum of their prices. But when I change the number from 47, nothing seems to happen.

Body:
Please try this:

UPDATE [Products]
SET  [Products].Price = [Products].Price*100
FROM    [Products]
        INNER JOIN (SELECT  p.SupplierID, SUM(p.Price) NewPrice
                    FROM Products p
                    GROUP BY p.SupplierID) B
        ON B.SupplierID = [Products].SupplierID
WHERE 47 = B.NewPrice


问:
How to avoid boot delay caused by signed libraries?
I have a startup service that uses some DLLs signed by myself.
In certain conditions (when the computer is connected to a network but it can't reach the internet) (Windows for) each signed library tries to validate its certificate somehow, increasing the boot time by a few seconds.

How to prevent this?

答: Google "disable crl checking" and take the first hit.  This isn't a real solution of course.  A real one takes different measures, ones that you cannot take care of yourself.  Somebody has to fix the Internet connection problem.  If your customer cannot take care of this, I'd recommend you suggest them to accept an unsigned version of your binaries.  Ask more questions about this at superuser.com</p>


答:
You want to update all prices where the supplier's product prices sum up to exactly 47. So make sure the subquery queries the products for the supplier of the product that you are about to update or not, i.e. have a correlated subquery.

```<code>UPDATE Products p1
SET Price = Price * 100
WHERE 47 = (SELECT SUM(p.Price) FROM Products p2 WHERE p2.SupplierID = p1.SupplierID);
</code>```

For every product (p1) we look up the sum of the supplier's products (p2) and update only if the sum is 47.

Title: SQL GROUP BY explanation

Body:
You want to update all prices where the supplier's product prices sum up to exactly 47. So make sure the subquery queries the products for the supplier of the product that you are about to update or not, i.e. have a correlated subquery.

UPDATE Products p1
SET Price = Price * 100
WHERE 47 = (SELECT SUM(p.Price) FROM Products p2 WHERE p2.SupplierID = p1.SupplierID);

For every product (p1) we look up the sum of the supplier's products (p2) and update only if the sum is 47.


问:
Unable to load data into logstash
I'm trying to follow the guide on the link below:

http://www.viaboxx.de/code/easily-generate-live-heatmaps-for-geolocations-with-elk/#codesyntax_1

It worked fine for me the first time but when I try it now, it gives me the following error at a step where I'm trying to load the csv data. The command I execute is:

cat test.csv | /opt/logstash/bin/logstash -f geostore.conf```
</div>
</div>
</p>

<p>and I get the following error:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Settings: Default pipeline workers: 2
Pipeline main started
Error parsing csv {:field=>"message", :source=>"", :exception=>#<NoMethodError: undefined method `each_index' for nil:NilClass>, :level=>:warn}
Pipeline main has been shutdown
stopping pipeline {:id=>"main"}</code>```

Can you please help !!! I've spent days on it trying to figure out.

Edit adding the geostore.conf:

 input { stdin {} }
    filter { # Step 1, drop the csv header line
       if [message] =~ /^#/ {
          drop {}
        } # Step 2, split latitude and longitude
        csv {
          separator => ','
          columns => [ 'lat', 'lon' ] }
           # Step 3 # move lat and lon into location object # for defined geo_point type in ES
        mutate {
             rename => [ "lat", "[location][lat]", "lon", "[location][lon]" ]
         }
       }
    output {
       elasticsearch {
         hosts => 'localhost'
         index => 'geostore'
         document_type => "locality"
         flush_size => 1000
      }
    }```
</div>
</div>
</p>

<p>I've changed my output section from this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>output {
  elasticsearch {
    hosts => 'localhost'
    index => 'geostore'
    document_type  => "locality"
    flush_size => 1000
  }</code>```

to this

output {
  elasticsearch {
    hosts => 'localhost'
    index => 'geostore'
    document_type  => "locality"
    flush_size => 1000
    stdout {}
  }```
</div>
</div>
</p>

<p>and now I'm getting a bit more verbose error message:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    fetched an invalid config {:config=>"input {\n    stdin {}\n}\nfilter {\n  #
 Step 1, drop the csv header line\n  if [message] =~ /^#/ {\n    drop {}\n  }\n
\n  # Step 2, split latitude and longitude\n  csv {\n    separator => ','\n
columns => [ 'lat', 'lon' ]\n  }\n \n  # Step 3\n  # move lat and lon into
location object \n  # for defined geo_point type in ES\n  mutate {  \n    rename
=> [ \"lat\", \"[location][lat]\", \"lon\", \"[location][lon]\" ]\n
}\n}\noutput {\n  elasticsearch {\n    hosts => 'localhost'\n    index =>
'geostore'\n    document_type  => \"locality\"\n    flush_size => 1000\n
stdout {}\n  }\n}\n\n", :reason=>"Expected one of #, => at line 29, column 12
(byte 543) after output {\n  elasticsearch {\n    hosts => 'localhost'\n
index => 'geostore'\n    document_type  => \"locality\"\n    flush_size =>
1000\n    stdout ", :level=>:error}</code>```

Can't understand why it worked for the first time.

Settings: Default pipeline workers: 2
Pipeline main started
Error parsing csv {:field=>"message", :source=>"", :exception=>#<NoMethodError: undefined method `each_index' for nil:NilClass>, :level=>:warn}
2017-03-30T13:46:31.171Z localhost.localdomain 53.97917361, -6.389038611
2017-03-30T13:46:31.171Z localhost.localdomain 54.00310028, -6.397707778
2017-03-30T13:46:31.172Z localhost.localdomain 53.99960056, -6.381966111
2017-03-30T13:46:31.172Z localhost.localdomain 54.00534917, -6.423718889
2017-03-30T13:46:31.172Z localhost.localdomain 51.92071667, -8.475726111
2017-03-30T13:46:31.172Z localhost.localdomain 51.82731222, -8.381912222
2017-03-30T13:46:31.173Z localhost.localdomain 51.81096639, -8.415731667
2017-03-30T13:46:31.173Z localhost.localdomain 54.28450222, -8.463775556
2017-03-30T13:46:31.173Z localhost.localdomain 54.27841, -8.495700278
2017-03-30T13:46:31.173Z localhost.localdomain 54.2681225, -8.462056944
2017-03-30T13:46:31.174Z localhost.localdomain 52.276167, -9.680497
2017-03-30T13:46:31.174Z localhost.localdomain 52.25660139, -9.703921389
2017-03-30T13:46:31.174Z localhost.localdomain 52.27031306, -9.723975556
2017-03-30T13:46:31.174Z localhost.localdomain 54.95663111, -7.714384167
2017-03-30T13:46:31.175Z localhost.localdomain 54.00133111, -7.352790833
2017-03-30T13:46:31.175Z localhost.localdomain 52.34264222, -6.4854175
2017-03-30T13:46:31.176Z localhost.localdomain 52.32439028, -6.464626111
2017-03-30T13:46:31.176Z localhost.localdomain 52.33008944, -6.487005
2017-03-30T13:46:31.176Z localhost.localdomain 53.70765861, -6.374657778
2017-03-30T13:46:31.177Z localhost.localdomain 53.72636306, -6.326768611
2017-03-30T13:46:31.177Z localhost.localdomain 53.71461361, -6.336066111
2017-03-30T13:46:31.177Z localhost.localdomain 51.55948417, -9.244535833
2017-03-30T13:46:31.177Z localhost.localdomain 53.52894667, -7.358543056
2017-03-30T13:46:31.177Z localhost.localdomain 53.51801167, -7.324215
2017-03-30T13:46:31.179Z localhost.localdomain 53.16202278, -6.795522222
2017-03-30T13:46:31.179Z localhost.localdomain 53.182702, -6.819299
2017-03-30T13:46:31.179Z localhost.localdomain 52.83053972, -8.991989444
2017-03-30T13:46:31.180Z localhost.localdomain 52.85651944, -8.965725833
2017-03-30T13:46:31.180Z localhost.localdomain 53.02885028, -7.300381667
2017-03-30T13:46:31.180Z localhost.localdomain
Pipeline main has been shutdown
stopping pipeline {:id=>"main"}```

答:
Hopefull, this would help other's as well.

I deleted the pattern from the command line:

curl -XDELETE 'localhost:9200/geostore?pretty'; ```
</div>
</div>
</p>

<p>and then went to to kibana to delete it from there as well. Reloaded the pattern back again as below and it worked. </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    curl -XPUT 'http://localhost:9200/geostore'</code>```

curl -XPUT 'http://localhost:9200/geostore/_mapping/locality' -d '
{
   "locality" : {
       "properties" : {
              "location" : {
                  "type" : "geo_point",
                  "geohash_prefix":     true,
                  "geohash_precision":  "1km"
              }
          }
       }
}'```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>cat test.csv | /opt/logstash/bin/logstash -f geostore.conf</code>```

This will take a few seconds to startup logstash, parse the input and store the result into Elasticsearch.

Now that we have the data in Elasticsearch, let's move to Kibana 4. After logged into Kibana, you need to add the index to Kibana.

Go to: Settings -> Indices -> Add New -> Write "geostore" in the index name field.

After you add the index, you'll see all fields in  the documents of the index, especially you should check if the property location is  classified as geo_point.

The whole process is described in detail at the below link.

http://www.viaboxx.de/code/easily-generate-live-heatmaps-for-geolocations-with-elk/#codesyntax_1

Title: Unable to load data into logstash

Body:
I'm trying to follow the guide on the link below:

http://www.viaboxx.de/code/easily-generate-live-heatmaps-for-geolocations-with-elk/#codesyntax_1

It worked fine for me the first time but when I try it now, it gives me the following error at a step where I'm trying to load the csv data. The command I execute is:

cat test.csv | /opt/logstash/bin/logstash -f geostore.conf

and I get the following error:

Settings: Default pipeline workers: 2
Pipeline main started
Error parsing csv {:field=>"message", :source=>"", :exception=>#<NoMethodError: undefined method `each_index' for nil:NilClass>, :level=>:warn}
Pipeline main has been shutdown
stopping pipeline {:id=>"main"}

Can you please help !!! I've spent days on it trying to figure out.

Edit adding the geostore.conf:

 input { stdin {} }
    filter { # Step 1, drop the csv header line
       if [message] =~ /^#/ {
          drop {}
        } # Step 2, split latitude and longitude
        csv {
          separator => ','
          columns => [ 'lat', 'lon' ] }
           # Step 3 # move lat and lon into location object # for defined geo_point type in ES
        mutate {
             rename => [ "lat", "[location][lat]", "lon", "[location][lon]" ]
         }
       }
    output {
       elasticsearch {
         hosts => 'localhost'
         index => 'geostore'
         document_type => "locality"
         flush_size => 1000
      }
    }

I've changed my output section from this:

output {
  elasticsearch {
    hosts => 'localhost'
    index => 'geostore'
    document_type  => "locality"
    flush_size => 1000
  }

to this

output {
  elasticsearch {
    hosts => 'localhost'
    index => 'geostore'
    document_type  => "locality"
    flush_size => 1000
    stdout {}
  }

and now I'm getting a bit more verbose error message:

    fetched an invalid config {:config=>"input {\n    stdin {}\n}\nfilter {\n  #
 Step 1, drop the csv header line\n  if [message] =~ /^#/ {\n    drop {}\n  }\n
\n  # Step 2, split latitude and longitude\n  csv {\n    separator => ','\n
columns => [ 'lat', 'lon' ]\n  }\n \n  # Step 3\n  # move lat and lon into
location object \n  # for defined geo_point type in ES\n  mutate {  \n    rename
=> [ \"lat\", \"[location][lat]\", \"lon\", \"[location][lon]\" ]\n
}\n}\noutput {\n  elasticsearch {\n    hosts => 'localhost'\n    index =>
'geostore'\n    document_type  => \"locality\"\n    flush_size => 1000\n
stdout {}\n  }\n}\n\n", :reason=>"Expected one of #, => at line 29, column 12
(byte 543) after output {\n  elasticsearch {\n    hosts => 'localhost'\n
index => 'geostore'\n    document_type  => \"locality\"\n    flush_size =>
1000\n    stdout ", :level=>:error}

Can't understand why it worked for the first time.

Settings: Default pipeline workers: 2
Pipeline main started
Error parsing csv {:field=>"message", :source=>"", :exception=>#<NoMethodError: undefined method `each_index' for nil:NilClass>, :level=>:warn}
2017-03-30T13:46:31.171Z localhost.localdomain 53.97917361, -6.389038611
2017-03-30T13:46:31.171Z localhost.localdomain 54.00310028, -6.397707778
2017-03-30T13:46:31.172Z localhost.localdomain 53.99960056, -6.381966111
2017-03-30T13:46:31.172Z localhost.localdomain 54.00534917, -6.423718889
2017-03-30T13:46:31.172Z localhost.localdomain 51.92071667, -8.475726111
2017-03-30T13:46:31.172Z localhost.localdomain 51.82731222, -8.381912222
2017-03-30T13:46:31.173Z localhost.localdomain 51.81096639, -8.415731667
2017-03-30T13:46:31.173Z localhost.localdomain 54.28450222, -8.463775556
2017-03-30T13:46:31.173Z localhost.localdomain 54.27841, -8.495700278
2017-03-30T13:46:31.173Z localhost.localdomain 54.2681225, -8.462056944
2017-03-30T13:46:31.174Z localhost.localdomain 52.276167, -9.680497
2017-03-30T13:46:31.174Z localhost.localdomain 52.25660139, -9.703921389
2017-03-30T13:46:31.174Z localhost.localdomain 52.27031306, -9.723975556
2017-03-30T13:46:31.174Z localhost.localdomain 54.95663111, -7.714384167
2017-03-30T13:46:31.175Z localhost.localdomain 54.00133111, -7.352790833
2017-03-30T13:46:31.175Z localhost.localdomain 52.34264222, -6.4854175
2017-03-30T13:46:31.176Z localhost.localdomain 52.32439028, -6.464626111
2017-03-30T13:46:31.176Z localhost.localdomain 52.33008944, -6.487005
2017-03-30T13:46:31.176Z localhost.localdomain 53.70765861, -6.374657778
2017-03-30T13:46:31.177Z localhost.localdomain 53.72636306, -6.326768611
2017-03-30T13:46:31.177Z localhost.localdomain 53.71461361, -6.336066111
2017-03-30T13:46:31.177Z localhost.localdomain 51.55948417, -9.244535833
2017-03-30T13:46:31.177Z localhost.localdomain 53.52894667, -7.358543056
2017-03-30T13:46:31.177Z localhost.localdomain 53.51801167, -7.324215
2017-03-30T13:46:31.179Z localhost.localdomain 53.16202278, -6.795522222
2017-03-30T13:46:31.179Z localhost.localdomain 53.182702, -6.819299
2017-03-30T13:46:31.179Z localhost.localdomain 52.83053972, -8.991989444
2017-03-30T13:46:31.180Z localhost.localdomain 52.85651944, -8.965725833
2017-03-30T13:46:31.180Z localhost.localdomain 53.02885028, -7.300381667
2017-03-30T13:46:31.180Z localhost.localdomain
Pipeline main has been shutdown
stopping pipeline {:id=>"main"}

Body:
Hopefull, this would help other's as well.

I deleted the pattern from the command line:

curl -XDELETE 'localhost:9200/geostore?pretty';

and then went to to kibana to delete it from there as well. Reloaded the pattern back again as below and it worked.

    curl -XPUT 'http://localhost:9200/geostore'

curl -XPUT 'http://localhost:9200/geostore/_mapping/locality' -d '
{
   "locality" : {
       "properties" : {
              "location" : {
                  "type" : "geo_point",
                  "geohash_prefix":     true,
                  "geohash_precision":  "1km"
              }
          }
       }
}'

cat test.csv | /opt/logstash/bin/logstash -f geostore.conf

This will take a few seconds to startup logstash, parse the input and store the result into Elasticsearch.

Now that we have the data in Elasticsearch, let's move to Kibana 4. After logged into Kibana, you need to add the index to Kibana.

Go to: Settings -> Indices -> Add New -> Write "geostore" in the index name field.

After you add the index, you'll see all fields in  the documents of the index, especially you should check if the property location is  classified as geo_point.

The whole process is described in detail at the below link.

http://www.viaboxx.de/code/easily-generate-live-heatmaps-for-geolocations-with-elk/#codesyntax_1


问:
Android checkbox and text box on top of the other
I have the following FrameLayout, this layout is used to my RecyclerView as the rows. In etch row I have text box and checkbox. The problem is the checkbox and the text box are connected to each other and the checkbox on the top of the text and it's hide the text box.

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="56dp"
android:focusable="false"
>

<Button
    android:id="@+id/undo_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_undo"
    android:textAllCaps="true"
    android:textColor="@android:color/white"
    android:layout_gravity="end|center_vertical"
    style="@style/Base.Widget.AppCompat.Button.Borderless"
    />

<!-- quick and dirty divider -->
<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/darker_gray"
    android:layout_gravity="bottom"
    />

<TextView
    android:id="@+id/title_text_view"
    android:layout_width="323dp"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    android:allowUndo="true"
    android:elevation="0dp"
    android:gravity="center_vertical"
    android:textSize="16sp"
    android:textStyle="bold" />

<CheckBox
    android:id="@+id/CheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</FrameLayout>
</code>```

I would be happy if someone can help me to fix this problem. Thanks.

答:
```<code><?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:background="@color/greenbar"
        android:layout_height="wrap_content"
        android:focusable="false"
        >

        <Button
            android:id="@+id/undo_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="button"
            android:textAllCaps="true"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            android:textColor="@android:color/white"
            android:layout_gravity="end|center_vertical"
            />
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@android:color/darker_gray"
            android:layout_gravity="bottom"
            android:id="@+id/d"
            />

        <CheckBox
            android:id="@+id/dummycheckbox"
            android:layout_width="wrap_content"
            android:layout_below="@+id/d"
            android:layout_marginTop="10dp"
            android:layout_height="wrap_content"/>

        <TextView
            android:id="@+id/dummytittletxt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="16sp"
            android:layout_marginLeft="10dp"
            android:paddingTop="5dp"
            android:layout_alignParentTop="true"
            android:layout_toLeftOf="@+id/undo_button"
            android:layout_alignBottom="@+id/dummycheckbox"
            android:layout_toRightOf="@+id/dummycheckbox"
            android:gravity="center_vertical"
            android:textStyle="bold"
            android:text="textview" />

    </RelativeLayout>
</code>```

Body:
I have the following FrameLayout, this layout is used to my RecyclerView as the rows. In etch row I have text box and checkbox. The problem is the checkbox and the text box are connected to each other and the checkbox on the top of the text and it's hide the text box.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="56dp"
android:focusable="false"
>

<Button
    android:id="@+id/undo_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_undo"
    android:textAllCaps="true"
    android:textColor="@android:color/white"
    android:layout_gravity="end|center_vertical"
    style="@style/Base.Widget.AppCompat.Button.Borderless"
    />

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/darker_gray"
    android:layout_gravity="bottom"
    />

<TextView
    android:id="@+id/title_text_view"
    android:layout_width="323dp"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    android:allowUndo="true"
    android:elevation="0dp"
    android:gravity="center_vertical"
    android:textSize="16sp"
    android:textStyle="bold" />

<CheckBox
    android:id="@+id/CheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</FrameLayout>

I would be happy if someone can help me to fix this problem. Thanks.


答:
In this line:

```<code>$("#temperature").append(temp.main.temp + " <a class='temper' href='#'>C</a>");
</code>```

you are adding some html content dynamically.

So use:

```<code>$(document).on('click', '.temper', function(){

});
</code>```

instead of static listener i.e.

```<code>$(".temper").click()
</code>```

because this kind of listener works for static html only.

Title: What is wrong with my logic my button only changes once and the onclick function stops?

Body:
In this line:

$("#temperature").append(temp.main.temp + " <a class='temper' href='#'>C</a>");

you are adding some html content dynamically.

So use:

$(document).on('click', '.temper', function(){

});

instead of static listener i.e.

$(".temper").click()

because this kind of listener works for static html only.


问:
Show active navigation for current page
i'm having some problems with my html, php code. With this code, my nav will show the active li but the other pages which are not active won't have style or links. </p>

```<code>    <!--/. PHP "active" -->
    <?php
    $current_url = basename($_SERVER['PHP_SELF']);
    $active = "class=\"active-menu\"";
    ?>
    <!--/. PHP "active" -->

    <nav class="navbar-default navbar-side" role="navigation">
        <div class="sidebar-collapse">
            <ul class="nav" id="main-menu">
                <li>
                    <?php if ($current_url == "home.php") { ?>
                    <a <?php echo $active;?> href="home.php"><?php } ?><i class="fa fa-dashboard"></i> Dashboard</a>
                </li>
                <li>
                    <?php if ($current_url == "new.php") { ?>
                    <a <?php echo $active;?> href="new.php"><?php } ?><i class="fa fa-qrcode"></i> Nieuw item toevoegen</a>
                </li>
                <li>
                    <?php if ($current_url == "show.php") { ?>
                    <a <?php echo $active;?> href="show.php"><?php } ?><i class="fa fa-qrcode"></i> Bekijk inventaris</a>
                </li>
                <li>
                    <?php if ($current_url == "profile.php") { ?>
                    <a <?php echo $active;?> href="profile.php"><?php } ?><i class="fa fa-user"></i> Gebruikersprofiel</a>
                </li>
                <li>
                    <a href="#"><i class="fa fa-sitemap"></i> Gebruikers<span class="fa arrow"></span></a>
                    <ul class="nav nav-second-level">
                        <li>
                            <a href="#">Beheerders</a>
                        </li>
                        <li>
                            <a href="#">ICT - Verantwoordelijken</a>
                        </li>
                        <li>
                            <a href="#">Raadplegers</a>
                        </li>
                    </ul>
                </li>
                <li>
                    <?php if ($current_url == "empty.php") { ?>
                    <a <?php echo $active;?> href="empty.php"><?php } ?><i class="fa fa-fw fa-file"></i> Lege pagina</a>
                </li>
            </ul>

        </div>

    </nav>
</code>```

<p>the pages with no styling will also not have a link. The active-menu class has the styling. </p>

答:
Your if condition it is wrong.

Try something like this in every
.

```<code><li>
    <a <?php echo $current_url == "home.php" ? $active : ''; ?> href="home.php"><i class="fa fa-dashboard"></i> Dashboard</a>
</li>
</code>```

Title: Show active navigation for current page

Body:
i'm having some problems with my html, php code. With this code, my nav will show the active li but the other pages which are not active won't have style or links.

    <?php
    $current_url = basename($_SERVER['PHP_SELF']);
    $active = "class=\"active-menu\"";
    ?>

                    <?php if ($current_url == "home.php") { ?>
                    <a <?php echo $active;?> href="home.php"><?php } ?> Dashboard

                    <?php if ($current_url == "new.php") { ?>
                    <a <?php echo $active;?> href="new.php"><?php } ?> Nieuw item toevoegen

                    <?php if ($current_url == "show.php") { ?>
                    <a <?php echo $active;?> href="show.php"><?php } ?> Bekijk inventaris

                    <?php if ($current_url == "profile.php") { ?>
                    <a <?php echo $active;?> href="profile.php"><?php } ?> Gebruikersprofiel

                     Gebruikers

                            Beheerders

                            ICT - Verantwoordelijken

                            Raadplegers

                    <?php if ($current_url == "empty.php") { ?>
                    <a <?php echo $active;?> href="empty.php"><?php } ?> Lege pagina

the pages with no styling will also not have a link. The active-menu class has the styling.

Body:
Your if condition it is wrong.

Try something like this in every <li>.

<li>
    <a <?php echo $current_url == "home.php" ? $active : ''; ?> href="home.php"><i class="fa fa-dashboard"></i> Dashboard</a>
</li>


问:
Facebook auth AuthenticationManager.GetExternalLoginInfoAsync() suddenly returns NULL
```<code>public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
        {

            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (loginInfo == null) { return RedirectToAction("Login"); }
            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
</code>```

So in my ExternalLoginCallback method AuthenticationManager.GetExternalLoginInfoAsync() used to work just fine, then suddenly a few days ago it no longer does anything and returns NULL, causing the entire "Register with Facebook" process to be skipped, redirecting the user to the Login page.

I had a separate ASP.NET MVC5 project that I made just to play around witth the Facebook Graph API and when I went back to it (I left it 2 weeks ago and the register/login with Facebook worked just fine on this project) it had the same problem, it returned null ! redirecting the user to the login page.

Is it possible there is something with my Facebook App ? or their API ? I have failed the app review 3 times (had some problems further down the code), put it back to development mode to try to work it out and now its not even hitting the previous problem, it stops at the AuthenticationManager.GetExternalLoginInfoAsync() and I cannot understand whats going on since I did not have this problem last week.

Here is the ExternalLogin method:

```<code>public ActionResult ExternalLogin(string provider, string returnUrl)
        {

            ControllerContext.HttpContext.Session.RemoveAll();

            return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
        }
</code>```

I've added ControllerContext.HttpContext.Session.RemoveAll(); to a suggestion I've found here on stackoverflow but it doesn't seem to do anything.

答: Had to update the Microsoft Owin package to 3.1.0-rc1 and now it works. (have the "include prerelease" in your update tab in the package manager)</p>

Body:
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
        {

            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (loginInfo == null) { return RedirectToAction("Login"); }
            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);

So in my ExternalLoginCallback method AuthenticationManager.GetExternalLoginInfoAsync() used to work just fine, then suddenly a few days ago it no longer does anything and returns NULL, causing the entire "Register with Facebook" process to be skipped, redirecting the user to the Login page.

I had a separate ASP.NET MVC5 project that I made just to play around witth the Facebook Graph API and when I went back to it (I left it 2 weeks ago and the register/login with Facebook worked just fine on this project) it had the same problem, it returned null ! redirecting the user to the login page.

Is it possible there is something with my Facebook App ? or their API ? I have failed the app review 3 times (had some problems further down the code), put it back to development mode to try to work it out and now its not even hitting the previous problem, it stops at the AuthenticationManager.GetExternalLoginInfoAsync() and I cannot understand whats going on since I did not have this problem last week.

Here is the ExternalLogin method:

public ActionResult ExternalLogin(string provider, string returnUrl)
        {

            ControllerContext.HttpContext.Session.RemoveAll();

            return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
        }

I've added ControllerContext.HttpContext.Session.RemoveAll(); to a suggestion I've found here on stackoverflow but it doesn't seem to do anything.


问:
Java ArrayList Index
```<code>int[] alist = new int [3];
alist.add("apple");
alist.add("banana");
alist.add("orange");
</code>```

Say that I want to use the second item in the ArrayList. What is the coding in order to get the following output?

output:

banana

答:
Here is how I would write it.</p>

```<code>String[] fruit = "apple banana orange".split(" ");
System.out.println(fruit[1]);
</code>```

Title: Java ArrayList Index

Body:
int[] alist = new int [3];
alist.add("apple");
alist.add("banana");
alist.add("orange");

Say that I want to use the second item in the ArrayList. What is the coding in order to get the following output?

output:

banana

Body:
Here is how I would write it.

String[] fruit = "apple banana orange".split(" ");
System.out.println(fruit[1]);


答:
You need to use an inner join, to join the sums back to the table. See below.</p>

```<code>UPDATE p1
SET p1.Price= p1.Price * 100
FROM Products p1
INNER JOIN (
            SELECT SupplierID, SUM(Price) AS Price
            FROM Products
            GROUP BY SupplierID
            HAVING SUM(Price) = 47
           ) p2
    ON p1.SupplierID = p2.SupplierID
</code>```

Title: SQL GROUP BY explanation

Body:
You need to use an inner join, to join the sums back to the table. See below.

UPDATE p1
SET p1.Price= p1.Price * 100
FROM Products p1
INNER JOIN (
            SELECT SupplierID, SUM(Price) AS Price
            FROM Products
            GROUP BY SupplierID
            HAVING SUM(Price) = 47
           ) p2
    ON p1.SupplierID = p2.SupplierID