答:
You can try this</p>

```<code>import java.util.*;
import java.io.*;

public class tap1
{
    public static void main(String[] args) throws IOException
    {
        System.out.println("Please enter number:");
        File outFile = new File ("CardNumbers.txt");
        FileWriter fWriter = new FileWriter (outFile, true);
        PrintWriter pWriter = new PrintWriter (fWriter);
        Scanner scan = new Scanner(System.in);
        String num = "";
        while(true){
        num=scan.nextLine();
        if(num.equals("exit")){
           break;
        }
        pWriter.println (num);
        }
        pWriter.close();
    }
}
</code>```

Title: How do I keep java program running (loop) so I can use the scanner to input to the same text file text file?

Body:
I am trying to use the java scanner input to read multiple inputs (numbers as a string eg. 12345) from keyboard and send to a text file, I have a scanner reading input.nextLine(), where it will read in each line. I just would like to run my program and have it stay running so it will populate the text file with each scanner input. I am using the following code:

import java.util.*;
import java.io.*;

public class tap1
{
    public static void main(String[] args) throws IOException
    {
        System.out.println("Please enter number:");
        File outFile = new File ("CardNumbers.txt");
        FileWriter fWriter = new FileWriter (outFile, true);
        PrintWriter pWriter = new PrintWriter (fWriter);
        Scanner scan = new Scanner(System.in);
        String num = scan.nextLine();
        pWriter.println (num);
        pWriter.close();
    }
}

Body:
You can try this

import java.util.*;
import java.io.*;

public class tap1
{
    public static void main(String[] args) throws IOException
    {
        System.out.println("Please enter number:");
        File outFile = new File ("CardNumbers.txt");
        FileWriter fWriter = new FileWriter (outFile, true);
        PrintWriter pWriter = new PrintWriter (fWriter);
        Scanner scan = new Scanner(System.in);
        String num = "";
        while(true){
        num=scan.nextLine();
        if(num.equals("exit")){
           break;
        }
        pWriter.println (num);
        }
        pWriter.close();
    }
}


来源: stackexchange

问:
Multiple variable let in Kotlin
Is there any way to chain multiple lets for multiple nullable variables in kotlin?

```<code>fun example(first: String?, second: String?) {
    first?.let {
        second?.let {
            // Do something just if both are != null
        }
    }
}
</code>```

I mean, something like this:

```<code>fun example(first: String?, second: String?) {
    first?.let && second?.let {
        // Do something just if both are != null
    }
}
</code>```

答:
For the case of just checking two values and also not having to work with lists:

```<code>fun <T1, T2> ifNotNull(value1: T1?, value2: T2?, bothNotNull: (T1, T2) -> (Unit)) {
    if (value1 != null && value2 != null) {
        bothNotNull(value1, value2)
    }
}
</code>```

Usage example:

```<code>var firstString: String?
var secondString: String?
ifNotNull(firstString, secondString) { first, second -> Log.d(TAG, "$first, $second") }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Multiple variable let in Kotlin

Body:
Is there any way to chain multiple lets for multiple nullable variables in kotlin?

fun example(first: String?, second: String?) {
    first?.let {
        second?.let {
            // Do something just if both are != null
        }
    }
}

I mean, something like this:

fun example(first: String?, second: String?) {
    first?.let && second?.let {
        // Do something just if both are != null
    }
}

Body:
For the case of just checking two values and also not having to work with lists:

fun <T1, T2> ifNotNull(value1: T1?, value2: T2?, bothNotNull: (T1, T2) -> (Unit)) {
    if (value1 != null && value2 != null) {
        bothNotNull(value1, value2)
    }
}

Usage example:

var firstString: String?
var secondString: String?
ifNotNull(firstString, secondString) { first, second -> Log.d(TAG, "$first, $second") }


问:
Hook up in cucumber check for scenario failure in java
While I was reading how to add a cleanup for a cucumber scenario on failure I got this piece of code in the internet.

```<code>After do |s|
  if s.failed?
    #If you are on an iOS Device
        $driver.quit
         sleep(time_for_driver_ready)
    #else
         reset
  end
end
</code>```

This is in ruby. I am working in java and is there any way to implement s.failed? in java, because in java the after method declaration does not include a scenario variable.

答:
You can pass the Scenario as a parameter to the After hook, the framework will inject the current scenario object to the method.</p>

```<code>@After
public void afterMethod(Scenario scenario) {
    if(scenario.isFailed()) {

    }
}
</code>```

Body:
While I was reading how to add a cleanup for a cucumber scenario on failure I got this piece of code in the internet.

After do |s|
  if s.failed?
    #If you are on an iOS Device
        $driver.quit
         sleep(time_for_driver_ready)
    #else
         reset
  end
end

This is in ruby. I am working in java and is there any way to implement s.failed? in java, because in java the after method declaration does not include a scenario variable.

Body:
You can pass the Scenario as a parameter to the After hook, the framework will inject the current scenario object to the method.

@After
public void afterMethod(Scenario scenario) {
    if(scenario.isFailed()) {

    }
}


问:
How to get an HTML file using Python?
I am not very familiar with Python. I am trying to extract the artist names (for a start :)) from the following page: http://www.infolanka.com/miyuru_gee/art/art.html.

How do I retrieve the page? My two main concerns are; what functions to use and how to filter out useless links from the page?

答:
Example using urlib and lxml.html:</p>

```<code>import urllib
from lxml import html

url = "http://www.infolanka.com/miyuru_gee/art/art.html"
page = html.fromstring(urllib.urlopen(url).read())

for link in page.xpath("//a"):
    print "Name", link.text, "URL", link.get("href")

output >>
    [('Aathma Liyanage', 'athma.html'),
     ('Abewardhana Balasuriya', 'abewardhana.html'),
     ('Aelian Thilakeratne', 'aelian_thi.html'),
     ('Ahamed Mohideen', 'ahamed.html'),
    ]
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to get an HTML file using Python?

Body:
Example using urlib and lxml.html:

import urllib
from lxml import html

url = "http://www.infolanka.com/miyuru_gee/art/art.html"
page = html.fromstring(urllib.urlopen(url).read())

for link in page.xpath("//a"):
    print "Name", link.text, "URL", link.get("href")

output >>
    [('Aathma Liyanage', 'athma.html'),
     ('Abewardhana Balasuriya', 'abewardhana.html'),
     ('Aelian Thilakeratne', 'aelian_thi.html'),
     ('Ahamed Mohideen', 'ahamed.html'),
    ]


问:
Vertically centering Bootstrap modal window
I would like to center my modal on the viewport (middle) I tried to add some css properties

```<code> .modal { position: fixed; top:50%; left:50%; }
</code>```

I'm using this example http://jsfiddle.net/rniemeyer/Wjjnd/

I tried

```<code>$("#MyModal").modal('show').css(
    {
        'margin-top': function () {
            return -($(this).height() / 2);
        },
        'margin-left': function () {
            return -($(this).width() / 2);
        }
    })
</code>```

答:
.modal.in .modal-dialog {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}```

Body:
I would like to center my modal on the viewport (middle) I tried to add some css properties

 .modal { position: fixed; top:50%; left:50%; }

I'm using this example http://jsfiddle.net/rniemeyer/Wjjnd/

I tried

$("#MyModal").modal('show').css(
    {
        'margin-top': function () {
            return -($(this).height() / 2);
        },
        'margin-left': function () {
            return -($(this).width() / 2);
        }
    })


问:
How to add classes in Yii form button submit
I have this line of code for create profile button :

```<code> <?php echo $form->bsBtnSubmit(Yii::t('idea', "Create Profile")); ?>
</code>```

I want to add these classes for the button's styling:

```<code>btn btn-sd btn-sd-green full-width
</code>```

I tried as below:

```<code> <?php echo $form->bsBtnSubmit(Yii::t('idea', "Create Profile", 'class'=>'btn btn-sd btn-sd-green full-width')); ?>
</code>```

but it's not working. How can I add these classes to my button above?

答:
using Html :

```<code><?= Html::submitButton('Create Profile', ['class' => 'btn btn-sd btn-sd-green full-width', 'value'=>'create_add', 'name'=>'submit']) ?>
</code>```

using CHtml

```<code><?php echo CHtml::submitButton('Create Profile', array('class' => 'btn btn-sd btn-sd-green full-width')); ?>
</code>```

Body:
I have this line of code for create profile button :

 <?php echo $form->bsBtnSubmit(Yii::t('idea', "Create Profile")); ?>

I want to add these classes for the button's styling:

btn btn-sd btn-sd-green full-width

I tried as below:

 <?php echo $form->bsBtnSubmit(Yii::t('idea', "Create Profile", 'class'=>'btn btn-sd btn-sd-green full-width')); ?>

but it's not working. How can I add these classes to my button above?

Body:
using Html :

<?= Html::submitButton('Create Profile', ['class' => 'btn btn-sd btn-sd-green full-width', 'value'=>'create_add', 'name'=>'submit']) ?>

using CHtml

<?php echo CHtml::submitButton('Create Profile', array('class' => 'btn btn-sd btn-sd-green full-width')); ?>


问:
Get Class Type of inherited object?
In C#, how can I get the inherited Class Type of an object where the object is an inherited object instead of the Type of the instantiated object?

Here is some code:

```<code>public class ClassA
{
    public virtual void GetClassType()
    {
        var type = this.GetType();
        Console.WriteLine(type.Name);
    }
}
public class ClassB : ClassA
{
    public override void GetClassType()
    {
        base.GetClassType();
        var type = this.GetType();
        Console.WriteLine(type.Name);
    }
}
public class ClassC : ClassB
{
    public override void GetClassType()
    {
        base.GetClassType();
        var type = this.GetType();
        Console.WriteLine(type.Name);
    }
}

private void GetClassType()
{
    var objectA = new ClassC();
    objectA.GetClassType();
}
</code>```

The GetClassType method outputs the following to the console:

ClassC
  ClassC
  ClassC

Is it possible to get the Type of the Class, instead of the Type of the object such that the following is the console output?

ClassA
  ClassB
  ClassC

答:
If you got the class which inherits the base type you already know which class it inherits.

if you want to check you can do as follows.

```<code>if(object is BaseType)
{
 //Dostuff
}
</code>```

Title: Get Class Type of inherited object?

Body:
In C#, how can I get the inherited Class Type of an object where the object is an inherited object instead of the Type of the instantiated object?

Here is some code:

public class ClassA
{
    public virtual void GetClassType()
    {
        var type = this.GetType();
        Console.WriteLine(type.Name);
    }
}
public class ClassB : ClassA
{
    public override void GetClassType()
    {
        base.GetClassType();
        var type = this.GetType();
        Console.WriteLine(type.Name);
    }
}
public class ClassC : ClassB
{
    public override void GetClassType()
    {
        base.GetClassType();
        var type = this.GetType();
        Console.WriteLine(type.Name);
    }
}

private void GetClassType()
{
    var objectA = new ClassC();
    objectA.GetClassType();
}

The GetClassType method outputs the following to the console:

ClassC
  ClassC
  ClassC

Is it possible to get the Type of the Class, instead of the Type of the object such that the following is the console output?

ClassA
  ClassB
  ClassC

Body:
If you got the class which inherits the base type you already know which class it inherits.

if you want to check you can do as follows.

if(object is BaseType)
{
 //Dostuff
}


问:
How to convert PNG image to grayscale using java?
I have a problem with regards to changing my PNG image to grayscale. I wanted to make a method that would accept byte[] image as a parameter and return back as a newly modified grayscale image as byte[] also.

I found some links that make images grayscale with JPEG images using below snippet.

```<code>private byte[] makeItGray(byte[] img, String contentType) throws IOException, Exception{

    InputStream in = new ByteArrayInputStream(img);
    BufferedImage bimg = ImageIO.read(in);

    for(int y=0; y < bimg.getHeight(); y++){
        for(int x=0; x < bimg.getWidth(); x++){
            Color color = new Color(bimg.getRGB(x,y));
            int graylevel = (color.getRed() + color.getGreen() + color.getBlue()) / 3;
            int r = graylevel;
            int g = graylevel;
            int b = graylevel;
            int rgb = ( r<<16 ) | ( g<<8 ) | b;
            bimg.setRGB(x, y, rgb);
        }
    }

    in.close();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    if(contentType.equals(MediaType.IMAGE_PNG_VALUE)){
        ImageIO.write(bimg, "png", baos);
        System.out.println("PNG!!!");
    }
    else if(contentType.equals(MediaType.IMAGE_JPEG_VALUE)){
        ImageIO.write(bimg, "jpg", baos);
    }
    else
        throw new Exception();

    baos.flush();
    byte[] grayImage = baos.toByteArray();
    baos.close();

    return grayImage;
}
</code>```

My references were on below :
How can I use ImageJ as a library for a separate Java application?
https://www.mkyong.com/java/how-to-convert-byte-to-bufferedimage-in-java/

It works on JPEG images but on PNG, it sends me a transparent image.

```<code>// converting orig image to grayscale in byte[]
imageBytes = makeItGray(imageBytes, file.getContentType());
Path path = Paths.get("some path here that would overwrite existing image");
Files.write(path, imageBytes);
</code>```

When I try to open the image manually to check if it is grayscale, it gives me transparent image or no image is showing but not null since it returns byte[] data. I was wondering if the above method is ok with PNG formats?

Please let me know for any questions. Thanks!

答:
Actually, the getRGB and setRGB methods, despite their names, actually returns and accepts a pixel in 32 bit packed ARGB format. That means that if the color model of your BufferedImage actually contains an alpha channel, leaving the alpha values of the pixel empty (0x00) as you do, will result in an all transparent image...

The PNG format supports alpha, while JPEG normally don't use it, that is why you see the results you do, and why it seems to work different for the different formats.

The fix is simple though, just prepend the pixel value with all opaque alpha:

```<code>int rgb = 0xff000000 | (r << 16) | (g << 8) | b;
bimg.setRGB(x, y, rgb);
</code>```

If you want to retain the alpha of the original, you can do that too (I simpliedfied the code a little):

```<code>int oldrgb = bimg.getRGB(x,y);
Color color = new Color(oldrgb);
int gray = (color.getRed() + color.getGreen() + color.getBlue()) / 3;
int rgb = (oldrgb & 0xff000000) | (gray << 16) | (gray << 8) | gray;
bimg.setRGB(x, y, rgb);
</code>```

PS: Note that your way of computing gray values by averaging isn't the recommended way to convert RGB to grayscale, so your images may look off compared to other tools. See for example Converting color to grayscale.

Body:
I have a problem with regards to changing my PNG image to grayscale. I wanted to make a method that would accept byte[] image as a parameter and return back as a newly modified grayscale image as byte[] also.

I found some links that make images grayscale with JPEG images using below snippet.

private byte[] makeItGray(byte[] img, String contentType) throws IOException, Exception{

    InputStream in = new ByteArrayInputStream(img);
    BufferedImage bimg = ImageIO.read(in);

    for(int y=0; y < bimg.getHeight(); y++){
        for(int x=0; x < bimg.getWidth(); x++){
            Color color = new Color(bimg.getRGB(x,y));
            int graylevel = (color.getRed() + color.getGreen() + color.getBlue()) / 3;
            int r = graylevel;
            int g = graylevel;
            int b = graylevel;
            int rgb = ( r<<16 ) | ( g<<8 ) | b;
            bimg.setRGB(x, y, rgb);
        }
    }

    in.close();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    if(contentType.equals(MediaType.IMAGE_PNG_VALUE)){
        ImageIO.write(bimg, "png", baos);
        System.out.println("PNG!!!");
    }
    else if(contentType.equals(MediaType.IMAGE_JPEG_VALUE)){
        ImageIO.write(bimg, "jpg", baos);
    }
    else
        throw new Exception();

    baos.flush();
    byte[] grayImage = baos.toByteArray();
    baos.close();

    return grayImage;
}

My references were on below :
How can I use ImageJ as a library for a separate Java application?
https://www.mkyong.com/java/how-to-convert-byte-to-bufferedimage-in-java/

It works on JPEG images but on PNG, it sends me a transparent image.

// converting orig image to grayscale in byte[]
imageBytes = makeItGray(imageBytes, file.getContentType());
Path path = Paths.get("some path here that would overwrite existing image");
Files.write(path, imageBytes);

When I try to open the image manually to check if it is grayscale, it gives me transparent image or no image is showing but not null since it returns byte[] data. I was wondering if the above method is ok with PNG formats?

Please let me know for any questions. Thanks!

Body:
Actually, the getRGB and setRGB methods, despite their names, actually returns and accepts a pixel in 32 bit packed ARGB format. That means that if the color model of your BufferedImage actually contains an alpha channel, leaving the alpha values of the pixel empty (0x00) as you do, will result in an all transparent image...

The PNG format supports alpha, while JPEG normally don't use it, that is why you see the results you do, and why it seems to work different for the different formats.

The fix is simple though, just prepend the pixel value with all opaque alpha:

int rgb = 0xff000000 | (r << 16) | (g << 8) | b;
bimg.setRGB(x, y, rgb);

If you want to retain the alpha of the original, you can do that too (I simpliedfied the code a little):

int oldrgb = bimg.getRGB(x,y);
Color color = new Color(oldrgb);
int gray = (color.getRed() + color.getGreen() + color.getBlue()) / 3;
int rgb = (oldrgb & 0xff000000) | (gray << 16) | (gray << 8) | gray;
bimg.setRGB(x, y, rgb);

PS: Note that your way of computing gray values by averaging isn't the recommended way to convert RGB to grayscale, so your images may look off compared to other tools. See for example Converting color to grayscale.


问:
MySQL - At least one of something and greater than between 3 tables
I have 3 tables :

I need to retrieve the name of the sellers that have sold during January AT LEAST one product where the total amount of sales of this said product during January is greater than 1000.

I thought about starting like this :

```<code>SELECT c.nom, c.prenom
FROM Commerciaux c
LEFT JOIN Ventes v ON c.id_commerciaux = v.id_commerciaux
WHERE  EXISTS (SELECT 1
FROM Produits p, Ventes v
WHERE p.id_produits = v.id_produits
AND MONTH(v.date) = 1
GROUP BY p.nom
HAVING SUM(v.montant) > 200)
AND MONTH(v.date) = 1
GROUP BY c.nom, c.prenom
</code>```

The SELECT in the WHERE EXISTS seems to be working, but when I have to get link the table Sellers, I don't know how to write it.

Any help would be great !

答:
You can use something like this:

```<code>select distinct s.name
from Sellers s,
    (   -- get all those products that qualify (more than 1000 sales)
        select product_id, sum(amount) as total
        from Sales
        where Month(date) = 1
        group by product_id
        having total > 1000
    ) vp,
     Sales sa
where
    s.id = sa.commercial_id and
    sa.product_id = vp.id and
    Month(sa.date) = 1
</code>```

@Leo answer would return only those Sellers that have sold more than 100 of the product in January instead of returning all Sellers that have sold any amount of the product that has been sold in an amount greater than 1000 across the board.

Body:
I have 3 tables :

I need to retrieve the name of the sellers that have sold during January AT LEAST one product where the total amount of sales of this said product during January is greater than 1000.

I thought about starting like this :

SELECT c.nom, c.prenom
FROM Commerciaux c
LEFT JOIN Ventes v ON c.id_commerciaux = v.id_commerciaux
WHERE  EXISTS (SELECT 1
FROM Produits p, Ventes v
WHERE p.id_produits = v.id_produits
AND MONTH(v.date) = 1
GROUP BY p.nom
HAVING SUM(v.montant) > 200)
AND MONTH(v.date) = 1
GROUP BY c.nom, c.prenom

The SELECT in the WHERE EXISTS seems to be working, but when I have to get link the table Sellers, I don't know how to write it.

Any help would be great !

Body:
You can use something like this:

select distinct s.name
from Sellers s,
    (   -- get all those products that qualify (more than 1000 sales)
        select product_id, sum(amount) as total
        from Sales
        where Month(date) = 1
        group by product_id
        having total > 1000
    ) vp,
     Sales sa
where
    s.id = sa.commercial_id and
    sa.product_id = vp.id and
    Month(sa.date) = 1

@Leo answer would return only those Sellers that have sold more than 100 of the product in January instead of returning all Sellers that have sold any amount of the product that has been sold in an amount greater than 1000 across the board.


问:
How to change text color based on specific option?
I want to change the first option's color to #ccc, others remain #000, but it doesn't work.Why? thanks.
 I don't wnat to use change function, which I think it's unnecessary.

something like this:

HTML:

```<code>  <select id="continent">
      <option value="-1">continent</option>
      <option value="1">US</option>
      <option value="2">UK</option>
  </select>
</code>```

JS:

```<code>$("#continent option[value='-1']").css('color','#ccc');
</code>```

答:
$("#continent").change(function(){
    $("#continent").val() == "-1" ? $("#continent").css("color", "red") : $("#continent").css("color", "blue");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="continent">
    <option value="-1">continent</option>
    <option value="1">US</option>
    <option value="2">UK</option>
</select></code>```

Remember to preset the color of the default option

Body:
I want to change the first option's color to #ccc, others remain #000, but it doesn't work.Why? thanks.
 I don't wnat to use change function, which I think it's unnecessary.

something like this:

HTML:

  <select id="continent">
      <option value="-1">continent</option>
      <option value="1">US</option>
      <option value="2">UK</option>
  </select>

JS:

$("#continent option[value='-1']").css('color','#ccc');

Body:
$("#continent").change(function(){
    $("#continent").val() == "-1" ? $("#continent").css("color", "red") : $("#continent").css("color", "blue");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="continent">
    <option value="-1">continent</option>
    <option value="1">US</option>
    <option value="2">UK</option>
</select>

Remember to preset the color of the default option


问:
Building a website project as 32-bit on a 64-bit build server
I have a VS 2010 solution that contains a website that has a web service within it.  The web service references a COM dll that is causing problems when the solution is built on our 64-bit build server.  I get the typical 32/64-bit error:

ASPNETCOMPILER : error ASPCONFIG: Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

When I build the site using the 32-bit aspnet_compiler it builds okay.  So, how do I specify that a website should be built as 32-bit?  The Configuration Manager within VS will only let me choose Any CPU, so I cannot change it to x86 for this website...

Thanks.

答:
Its not the compilation problem but the environment problem. The ASP.NET Website will always be built as Any CPU.

However, if you load it on 64 bit machine, by default 64 bit version of IIS is running which
is unable to load COM DLL and it fails.

You need to configure IIS to run 32 bit applications on 64 bit Windows:
http://www.microsoft.com/technet/prodtechnol/windowsserver2003/library/iis/405f5bb5-87a3-43d2-8138-54b75db73aa1.mspx


问:
How can I change android navigation bar color with service
developers...I want to make an app that can change the color of navigation bar in android. Usually we can do this with this simple code.

```<code>if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().setNavigationBarColor(getResources().getColor(R.color.your_awesome_color)); }
</code>```

But the problem is, I want to make this code work when application is not running (in the background) like this image.

This is android's home screen
I think this can be done with the help of android services. But we can not use getWindow() method in services.

So plese help me how can I do that, should i use WindowManager ?? or anything else plzz help me and provide me a code.☺☺☺

答:
A good way to go is to persist the color you choose inside your service. You could use sharedPreferences for this:

```<code>int yourColor = R.color.someColor;
SharedPreferences sharedPref = context.getSharedPreferences(
    "com.example.your_filename", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("COLOR_KEY", yourColor);
editor.apply();
</code>```

In your Activity you load the persisted color from the SharedPreference like this:

```<code>SharedPreferences sharedPref =getSharedPreferences(
    "com.example.your_filename", Context.MODE_PRIVATE);
int yourColor = sharedPref.getInt("COLOR_KEY", R.color.defaultColor);

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    getWindow().setNavigationBarColor(
        ContextCompat.getColor(getContext(), yourColor)
    );
}
</code>```

Body:
developers...I want to make an app that can change the color of navigation bar in android. Usually we can do this with this simple code.

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().setNavigationBarColor(getResources().getColor(R.color.your_awesome_color)); }

But the problem is, I want to make this code work when application is not running (in the background) like this image.

This is android's home screen
I think this can be done with the help of android services. But we can not use getWindow() method in services.

So plese help me how can I do that, should i use WindowManager ?? or anything else plzz help me and provide me a code.☺☺☺

Body:
A good way to go is to persist the color you choose inside your service. You could use sharedPreferences for this:

int yourColor = R.color.someColor;
SharedPreferences sharedPref = context.getSharedPreferences(
    "com.example.your_filename", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("COLOR_KEY", yourColor);
editor.apply();

In your Activity you load the persisted color from the SharedPreference like this:

SharedPreferences sharedPref =getSharedPreferences(
    "com.example.your_filename", Context.MODE_PRIVATE);
int yourColor = sharedPref.getInt("COLOR_KEY", R.color.defaultColor);

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    getWindow().setNavigationBarColor(
        ContextCompat.getColor(getContext(), yourColor)
    );
}


问:
MS Access: count the name
How to count the student name and display all the data

ID Name      Subject
1  Jack      English
2  Tiffany   English
3  Ben       Mathematics
4  Tiffany   Science
5  Jack      Mathematics
```

<p>Then the return of the result for the output will show the subject taken of each person. </p>

<pre class="lang-none prettyprint-override"><code>ID Name      Subject       [Subject Taken]
1  Jack      English       2
2  Tiffany   English       2
3  Ben       Mathematics   1
4  Tiffany   Science       2
5  Jack      Mathematics   2
</code>```

答:
you could achieve this with a subquery but not without a group by. make a group by first then join that group by with the original table.

SubQuery Group by result

```<code>Name    CountOfSubject
Ben     1
jack    2
Tiffany 2
</code>```

-

```<code> SELECT SubQuery.Name, Table1.Subject, SubQuery.CountOfSubject
 FROM
            ( SELECT Table1.Name,
                     Count(Table1.Subject) AS CountOfSubject
              FROM Table1
              GROUP BY Table1.Name) AS SubQuery
 INNER JOIN Table1 ON SubQuery.Name = Table1.Name;
</code>```

result

```<code>Name    Subject     CountOfSubject
jack    English     2
Tiffany English     2
Ben     Mathematics 1
Tiffany Science     2
jack    Mathematics 2
</code>```

Title: MS Access: count the name

Body:
How to count the student name and display all the data

ID Name      Subject
1  Jack      English
2  Tiffany   English
3  Ben       Mathematics
4  Tiffany   Science
5  Jack      Mathematics

Then the return of the result for the output will show the subject taken of each person.

ID Name      Subject       [Subject Taken]
1  Jack      English       2
2  Tiffany   English       2
3  Ben       Mathematics   1
4  Tiffany   Science       2
5  Jack      Mathematics   2

Body:
you could achieve this with a subquery but not without a group by. make a group by first then join that group by with the original table.

SubQuery Group by result

Name    CountOfSubject
Ben     1
jack    2
Tiffany 2

-

 SELECT SubQuery.Name, Table1.Subject, SubQuery.CountOfSubject
 FROM
            ( SELECT Table1.Name,
                     Count(Table1.Subject) AS CountOfSubject
              FROM Table1
              GROUP BY Table1.Name) AS SubQuery
 INNER JOIN Table1 ON SubQuery.Name = Table1.Name;

result

Name    Subject     CountOfSubject
jack    English     2
Tiffany English     2
Ben     Mathematics 1
Tiffany Science     2
jack    Mathematics 2


问:
React Router v4 & CSS Transition Group
I have a simple example of react-router v4 & route transitions. It follows the example shown at https://reacttraining.com/react-router/web/example/animated-transitions. The result, however, is only the last route is shown. The others are just blank. https://codesandbox.io/s/r0PvB30wk.</p>

```<code>import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import { CSSTransitionGroup } from 'react-transition-group'

import About from './components/About';
import Home from './components/Home';
import Topics from './components/Topics';

import './styles.css'

const BasicExample = () => (
  <Router>
    <Route render={({ location }) => (
      <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/topics">Topics</Link></li>
        </ul>

        <hr />
        <CSSTransitionGroup
          transitionEnterTimeout={300}
          transitionLeaveTimeout={300}
          transitionName="fade"
        >
          <Route exact path="/"       component={Home}   location={location} key={location.key} />
          <Route       path="/about"  component={About}  location={location} key={location.key} />
          <Route       path="/topics" component={Topics} location={location} key={location.key} />
        </CSSTransitionGroup>
      </div>
    )}/>
  </Router>
);

render(<BasicExample />, document.body);
</code>```

答:
For anyone interested, the only way I could get this to work was to use a <switch> from react-router.

```<code>import React from 'react'
import { render } from 'react-dom'
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom'
import { CSSTransitionGroup } from 'react-transition-group'

import About from './components/About'
import Home from './components/Home'
import Topics from './components/Topics'

import './styles.css'

const BasicExample = () => (
  <Router>
    <Route render={({ location, history, match }) => (
      <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/topics">Topics</Link></li>
        </ul>

        <hr />
        <CSSTransitionGroup
          transitionEnterTimeout={500}
          transitionLeaveTimeout={500}
          transitionName="fade"
        >
          <Switch key={location.key} location={location}>
            <Route exact path="/"       component={Home}   location={location} key={location.key} />
            <Route       path="/about"  component={About}  location={location} key={location.key} />
            <Route       path="/topics" component={Topics} location={location} key={location.key} />
          </Switch>
        </CSSTransitionGroup>
      </div>
    )}/>
  </Router>
)

render(<BasicExample />, document.body)
</code>```

Title: React Router v4 & CSS Transition Group

Body:
I have a simple example of react-router v4 & route transitions. It follows the example shown at https://reacttraining.com/react-router/web/example/animated-transitions. The result, however, is only the last route is shown. The others are just blank. https://codesandbox.io/s/r0PvB30wk.

import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import { CSSTransitionGroup } from 'react-transition-group'

import About from './components/About';
import Home from './components/Home';
import Topics from './components/Topics';

import './styles.css'

const BasicExample = () => (
  <Router>
    <Route render={({ location }) => (

<Link to="/">Home</Link>

<Link to="/about">About</Link>

<Link to="/topics">Topics</Link>

        <CSSTransitionGroup
          transitionEnterTimeout={300}
          transitionLeaveTimeout={300}
          transitionName="fade"
        >
          <Route exact path="/"       component={Home}   location={location} key={location.key} />
          <Route       path="/about"  component={About}  location={location} key={location.key} />
          <Route       path="/topics" component={Topics} location={location} key={location.key} />
        </CSSTransitionGroup>

    )}/>
  </Router>
);

render(<BasicExample />, document.body);

Body:
For anyone interested, the only way I could get this to work was to use a <switch> from react-router.

import React from 'react'
import { render } from 'react-dom'
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom'
import { CSSTransitionGroup } from 'react-transition-group'

import About from './components/About'
import Home from './components/Home'
import Topics from './components/Topics'

import './styles.css'

const BasicExample = () => (
  <Router>
    <Route render={({ location, history, match }) => (
      <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/topics">Topics</Link></li>
        </ul>

        <hr />
        <CSSTransitionGroup
          transitionEnterTimeout={500}
          transitionLeaveTimeout={500}
          transitionName="fade"
        >
          <Switch key={location.key} location={location}>
            <Route exact path="/"       component={Home}   location={location} key={location.key} />
            <Route       path="/about"  component={About}  location={location} key={location.key} />
            <Route       path="/topics" component={Topics} location={location} key={location.key} />
          </Switch>
        </CSSTransitionGroup>
      </div>
    )}/>
  </Router>
)

render(<BasicExample />, document.body)


问:
Search dictionary values and return List of keys meeting conditions
I've got a problem searching a Dictionary looking like this.

```<code>Dictionary<string, string[]> dic = new Dictionary<string, string[]>(){
    {"a", new string[](){"a_val","2"}},
    {"b", new string[](){"b_val","1"}},
    {"b", new string[](){"b_val","0"}}
};
</code>```

I need to return a List of the Keys where the value of the stingArray[1] element is bigger than "1" like:

```<code>List<string> list = new List<string>{
    "a"
};
</code>```

Because I'm not really good at using LINQ, my current solution is iterating over the Dictionary and adding the keys to a new list. But that method looks ugly and I'm trying to find another solution to the problem.

答:
Try this(You're dictionary definition has some compiling errors and I made some guess):</p>

```<code>        static void Main(string[] args)
    {
        var dic = new Dictionary<string, string[]>(){
        {"a", new string[]{"a_val","2"}},
        {"b", new string[]{ "b_val","1"}},
        {"c", new string[]{ "b_val","0"}}};
        string[] expected = dic
            .Where(kv => Convert.ToInt32(kv.Value[1]) > 1)
            .Select(kv => kv.Key).ToArray();
    }
</code>```

Body:
I've got a problem searching a Dictionary looking like this.

Dictionary<string, string[]> dic = new Dictionary<string, string[]>(){
    {"a", new string[](){"a_val","2"}},
    {"b", new string[](){"b_val","1"}},
    {"b", new string[](){"b_val","0"}}
};

I need to return a List of the Keys where the value of the stingArray[1] element is bigger than "1" like:

List<string> list = new List<string>{
    "a"
};

Because I'm not really good at using LINQ, my current solution is iterating over the Dictionary and adding the keys to a new list. But that method looks ugly and I'm trying to find another solution to the problem.

Body:
Try this(You're dictionary definition has some compiling errors and I made some guess):

        static void Main(string[] args)
    {
        var dic = new Dictionary<string, string[]>(){
        {"a", new string[]{"a_val","2"}},
        {"b", new string[]{ "b_val","1"}},
        {"c", new string[]{ "b_val","0"}}};
        string[] expected = dic
            .Where(kv => Convert.ToInt32(kv.Value[1]) > 1)
            .Select(kv => kv.Key).ToArray();
    }


问:
Codeigniter views not refreshing
I have a codeigniter site running. Once a user has performed an action on a page, that page seems to remain chached in the browser and no data on the page refreshes. Even if a record is added to or removed from a grid on the page, it will not display. I've printed out the variables on the pages and the new data is always there. I've tried forcing the browser to refresh:

```<code><meta http-equiv="cache-control" content="no-cache, must-revalidate, post-check=0, pre-check=0" />
      <meta http-equiv="cache-control" content="max-age=0" />
      <meta http-equiv="expires" content="0" />
      <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
      <meta http-equiv="pragma" content="no-cache" />
</code>```

This has had no effect. Below is an example of an insert and select with the views:

Add new record controller:

```<code>function add_new() {
    $current_date = date('Y-m-d');
    $data = array(

        'catalogue_name' => $_POST['catalogue_name'] ,
        'creation_date' => $current_date
        );
    $this->load->model('catalogue_model');
    $last_id = $this->catalogue_model->add_catalogue($data);
    $data['catalogue_id'] = $last_id;
    redirect('catalogues/edit/'.$last_id);
}
</code>```

Model:

```<code>function add_catalogue($data){

    $this->db->insert('catalogue', $data);
    return $this->db->insert_id();

}
</code>```

View:

```<code><div class="container">
    <div class="row">
    <div class="row">
      <div class="searchable-container">
        <form action="<?php echo base_url('index.php/catalogues/add_new'); ?>" method="POST" role="form" id="name_catalogue">
            <div class="col-xs-2 col-sm-2 col-md-2 col-lg-2">
                <label>Catalogue Name</label>
                <input type="text" name="catalogue_name" id="catalogue_name" class="form-control" title="">
            </div>
            <div class="col-xs-2 col-sm-2 col-md-2 col-lg-2">
                <button type="submit" class="btn btn-block btn-info">Create Catalogue</button>
            </div>
            </form>
      </div>
    </div>
    </div>
</div>
</code>```

Then the select and display controller:

```<code>public function index() {
    $this->output->set_template('default');
    $data['catalogues'] = $this->catalogue_model->get_catalogues();
    $this->load->view('catalogues/list', $data);
}
</code>```

Model:

```<code>function get_catalogues() {
    $this->db->select('*');
    $this->db->from('catalogue');
    $query = $this->db->get();
    return $query->result();
}
</code>```

View:

```<code><div class="container">
    <?php if ($this->session->flashdata('message')) :?>
    <div class="alert alert-success">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
         <?php echo $this->session->flashdata('message');?>
    </div>
    <?php endif ; ?>
    <div class="row">
        <div class="row">
            <a class="btn btn-large btn-block btn-success" href="<?php echo base_url('index.php/catalogues/new_catalogue'); ?>" role="button">Add New Catalogue</a>
        </div>
        <hr>
        <div class="row">
            <?php foreach ($catalogues as $catalogue): ?>
                <div class="col-md-12">
                    <div class="col-md-3">
                        <h4><?php echo $catalogue->catalogue_name ?></h4>
                    </div>
                    <div class="col-md-3">
                        <h4><?php echo $catalogue->creation_date ?></h4>
                    </div>
                    <div class="col-md-3">
                        <a class="btn btn-large btn-block btn-default" href="<?php echo base_url('index.php/catalogues/edit'); ?>/<?php echo $catalogue->id; ?>" role="button">View</a>
                    </div>
                    <div class="col-md-3">
                        <a class="btn btn-large btn-block btn-danger" href="<?php echo base_url('index.php/catalogues/delete_catalogue'); ?>/<?php echo $catalogue->id; ?>" role="button">Delete Catalogue</a>
                    </div>
                    <hr>
                </div>
            <?php endforeach; ?>
        </div>
        <?php
        $last = $this->uri->total_segments();
        $catalogue_id = $this->uri->segment($last);
        ?>
    </div>
</div>
</code>```

So when adding a record here, the record shows in the database, but does not show in the view once you go to the "list" page. If I use print_f to print out the data, the new data is printed, but not displayed in the html.

It doesn't seem like a codeigniter problem, but I might be wrong. I'm using bootstrap 3 for the theme.

```<code><html lang="en">
    <head>
        <title></title>
        <meta http-equiv="cache-control" content="no-cache, must-revalidate, post-check=0, pre-check=0" />
      <meta http-equiv="cache-control" content="max-age=0" />
      <meta http-equiv="expires" content="0" />
      <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
      <meta http-equiv="pragma" content="no-cache" />

        <meta name="keywords" content="" />
        <meta name="description" content="" />

    <!-- Le styles -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link href="/assets/themes/default/hero_files/bootstrap-responsive.css" rel="stylesheet">
    <link href="/assets/themes/default/css/general.css" rel="stylesheet">
    <link href="/assets/themes/default/css/custom.css" rel="stylesheet">

        <script
  src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
    <script type="text/javascript" src="/assets/js/core.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script type="text/javascript" src="/assets/themes/default/js/bootstrap.js"></script>
        <script type="text/javascript" src="/assets/themes/default/js/bootstrap-confirmation.min.js"></script>
        <script src="/assets/grocery_crud/themes/bootstrap/js/bootstrap/dropdown.min.js"></script>

    <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->

    <!-- Le fav and touch icons -->
    <link rel="shortcut icon" href="/assets/themes/default/images/favicon.png" type="image/x-icon"/>
    <meta property="og:image" content="/assets/themes/default/images/facebook-thumb.png"/>
    <link rel="image_src" href="/assets/themes/default/images/facebook-thumb.png" />
    <style type="text/css">

    </style>

</head>
</code>```

答:
This issue was resolved by moving to a new hosting provider. The hosting provider changed their hosting environment and the codeigniter sessions stopped working. This has happened before with another codeigniter program of mine. So if you experience similar issues, set up a localhost or hosting on another server and test your code there.

Other ways to identify this problem. If your program allows users to only see data they created, Logging in with different usernames will display the same or all data.

Log into the program on one browser, go to a record that requires authentication to view, copy and paste that url into a different browser. If you see the page, your sessions are not working properly.

Title: Codeigniter views not refreshing

Body:
I have a codeigniter site running. Once a user has performed an action on a page, that page seems to remain chached in the browser and no data on the page refreshes. Even if a record is added to or removed from a grid on the page, it will not display. I've printed out the variables on the pages and the new data is always there. I've tried forcing the browser to refresh:

<meta http-equiv="cache-control" content="no-cache, must-revalidate, post-check=0, pre-check=0" />
      <meta http-equiv="cache-control" content="max-age=0" />
      <meta http-equiv="expires" content="0" />
      <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
      <meta http-equiv="pragma" content="no-cache" />

This has had no effect. Below is an example of an insert and select with the views:

Add new record controller:

function add_new() {
    $current_date = date('Y-m-d');
    $data = array(

        'catalogue_name' => $_POST['catalogue_name'] ,
        'creation_date' => $current_date
        );
    $this->load->model('catalogue_model');
    $last_id = $this->catalogue_model->add_catalogue($data);
    $data['catalogue_id'] = $last_id;
    redirect('catalogues/edit/'.$last_id);
}

Model:

function add_catalogue($data){

    $this->db->insert('catalogue', $data);
    return $this->db->insert_id();

}

View:

        <form action="<?php echo base_url('index.php/catalogues/add_new'); ?>" method="POST" role="form" id="name_catalogue">

                Catalogue Name
                <input type="text" name="catalogue_name" id="catalogue_name" class="form-control" title="">

                <button type="submit" class="btn btn-block btn-info">Create Catalogue</button>

            </form>

Then the select and display controller:

public function index() {
    $this->output->set_template('default');
    $data['catalogues'] = $this->catalogue_model->get_catalogues();
    $this->load->view('catalogues/list', $data);
}

Model:

function get_catalogues() {
    $this->db->select('*');
    $this->db->from('catalogue');
    $query = $this->db->get();
    return $query->result();
}

View:

    <?php if ($this->session->flashdata('message')) :?>

        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
         <?php echo $this->session->flashdata('message');?>

    <?php endif ; ?>

            <a class="btn btn-large btn-block btn-success" href="<?php echo base_url('index.php/catalogues/new_catalogue'); ?>" role="button">Add New Catalogue

            <?php foreach ($catalogues as $catalogue): ?>

<?php echo $catalogue->catalogue_name ?>

<?php echo $catalogue->creation_date ?>

                        <a class="btn btn-large btn-block btn-default" href="<?php echo base_url('index.php/catalogues/edit'); ?>/<?php echo $catalogue->id; ?>" role="button">View

                        <a class="btn btn-large btn-block btn-danger" href="<?php echo base_url('index.php/catalogues/delete_catalogue'); ?>/<?php echo $catalogue->id; ?>" role="button">Delete Catalogue

            <?php endforeach; ?>

        <?php
        $last = $this->uri->total_segments();
        $catalogue_id = $this->uri->segment($last);
        ?>

So when adding a record here, the record shows in the database, but does not show in the view once you go to the "list" page. If I use print_f to print out the data, the new data is printed, but not displayed in the html.

It doesn't seem like a codeigniter problem, but I might be wrong. I'm using bootstrap 3 for the theme.

        <title></title>
        <meta http-equiv="cache-control" content="no-cache, must-revalidate, post-check=0, pre-check=0" />
      <meta http-equiv="cache-control" content="max-age=0" />
      <meta http-equiv="expires" content="0" />
      <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
      <meta http-equiv="pragma" content="no-cache" />

        <meta name="keywords" content="" />
        <meta name="description" content="" />

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link href="/assets/themes/default/hero_files/bootstrap-responsive.css" rel="stylesheet">
    <link href="/assets/themes/default/css/general.css" rel="stylesheet">
    <link href="/assets/themes/default/css/custom.css" rel="stylesheet">

    <link rel="shortcut icon" href="/assets/themes/default/images/favicon.png" type="image/x-icon"/>
    <meta property="og:image" content="/assets/themes/default/images/facebook-thumb.png"/>
    <link rel="image_src" href="/assets/themes/default/images/facebook-thumb.png" />


问:
MissingResourceException: Can't find bundle for base name sun.util.logging.resources.logging, locale en_US
I am getting,

```<code>Caused by java.lang.InternalError: java.util.MissingResourceException: Can't find bundle for base name sun.util.logging.resources.logging, locale en_US
</code>```

in my application from firebase crash report.

Other details

```<code>Manufacturer: HTC
Model: HTC 10
Android API: 24
</code>```

Here is the stack trace

```<code>java.util.logging.Logger$1.run (Logger.java:1385)
java.util.logging.Logger$1.run (Logger.java:1379)
java.security.AccessController.doPrivileged (AccessController.java:41)
java.util.logging.Logger.findSystemResourceBundle (Logger.java:1378)
java.util.logging.Logger.findResourceBundle (Logger.java:1425)
java.util.logging.Logger.setupResourceInfo (Logger.java:1523)
java.util.logging.Logger.<init> (Logger.java:266)
java.util.logging.Logger.<init> (Logger.java:261)
java.util.logging.LogManager$SystemLoggerContext.demandLogger (LogManager.java:734)
java.util.logging.LogManager.demandSystemLogger (LogManager.java:399)
java.util.logging.Logger.getPlatformLogger (Logger.java:474)
java.util.logging.LoggingProxyImpl.getLogger (LoggingProxyImpl.java:41)
sun.util.logging.LoggingSupport.getLogger (LoggingSupport.java:100)
sun.util.logging.PlatformLogger$JavaLoggerProxy.<init> (PlatformLogger.java:636)
sun.util.logging.PlatformLogger$JavaLoggerProxy.<init> (PlatformLogger.java:631)
sun.util.logging.PlatformLogger.<init> (PlatformLogger.java:246)
sun.util.logging.PlatformLogger.getLogger (PlatformLogger.java:205)
java.net.CookieManager.put (CookieManager.java:262)
okhttp3.JavaNetCookieJar.saveFromResponse (JavaNetCookieJar.java:47)
okhttp3.internal.http.HttpHeaders.receiveHeaders (HttpHeaders.java:182)
okhttp3.internal.http.BridgeInterceptor.intercept (BridgeInterceptor.java:95)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept (RetryAndFollowUpInterceptor.java:120)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:67)
okhttp3.RealCall.getResponseWithInterceptorChain (RealCall.java:185)
okhttp3.RealCall.execute (RealCall.java:69)
</code>```

Here is the relevant Logger code

```<code>private static ResourceBundle findSystemResourceBundle(final Locale var0) {
        return (ResourceBundle)AccessController.doPrivileged(new PrivilegedAction() {
            public ResourceBundle run() {
                try {
                    return ResourceBundle.getBundle("sun.util.logging.resources.logging", var0, ClassLoader.getSystemClassLoader());
                } catch (MissingResourceException var2) {
                    throw new InternalError(var2.toString());
                }
            }
        });
    }
</code>```

I have got crash report for locale en_AU too.

Since the crashing code is not controlled by me, how do I prevent this crash?

答:
If it works a resource file as suggested by the other answer is a better option, but if that doesn't pan out I have another option. Assuming that you don't need the logging you should be able to disable it like this:

```<code>try {
    Class<?> cls = Class.forName("sun.util.logging.PlatformLogger");
    Field field = cls.getDeclaredField("loggingEnabled");
    field.setAccessible(true);
    field.set(null, Boolean.FALSE);
} catch(Exception e) {
    // Failed
}
</code>```

If you do that early the PlatformLogger should construct a DefaultLoggerProxy instead of a JavaLoggerProxy, so the broken code never runs. This is ugly as it depends on internal implementation details and as it disables logging, but perhaps it works for your application?

Body:
I am getting,

Caused by java.lang.InternalError: java.util.MissingResourceException: Can't find bundle for base name sun.util.logging.resources.logging, locale en_US

in my application from firebase crash report.

Other details

Manufacturer: HTC
Model: HTC 10
Android API: 24

Here is the stack trace

java.util.logging.Logger$1.run (Logger.java:1385)
java.util.logging.Logger$1.run (Logger.java:1379)
java.security.AccessController.doPrivileged (AccessController.java:41)
java.util.logging.Logger.findSystemResourceBundle (Logger.java:1378)
java.util.logging.Logger.findResourceBundle (Logger.java:1425)
java.util.logging.Logger.setupResourceInfo (Logger.java:1523)
java.util.logging.Logger.<init> (Logger.java:266)
java.util.logging.Logger.<init> (Logger.java:261)
java.util.logging.LogManager$SystemLoggerContext.demandLogger (LogManager.java:734)
java.util.logging.LogManager.demandSystemLogger (LogManager.java:399)
java.util.logging.Logger.getPlatformLogger (Logger.java:474)
java.util.logging.LoggingProxyImpl.getLogger (LoggingProxyImpl.java:41)
sun.util.logging.LoggingSupport.getLogger (LoggingSupport.java:100)
sun.util.logging.PlatformLogger$JavaLoggerProxy.<init> (PlatformLogger.java:636)
sun.util.logging.PlatformLogger$JavaLoggerProxy.<init> (PlatformLogger.java:631)
sun.util.logging.PlatformLogger.<init> (PlatformLogger.java:246)
sun.util.logging.PlatformLogger.getLogger (PlatformLogger.java:205)
java.net.CookieManager.put (CookieManager.java:262)
okhttp3.JavaNetCookieJar.saveFromResponse (JavaNetCookieJar.java:47)
okhttp3.internal.http.HttpHeaders.receiveHeaders (HttpHeaders.java:182)
okhttp3.internal.http.BridgeInterceptor.intercept (BridgeInterceptor.java:95)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept (RetryAndFollowUpInterceptor.java:120)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:67)
okhttp3.RealCall.getResponseWithInterceptorChain (RealCall.java:185)
okhttp3.RealCall.execute (RealCall.java:69)

Here is the relevant Logger code

private static ResourceBundle findSystemResourceBundle(final Locale var0) {
        return (ResourceBundle)AccessController.doPrivileged(new PrivilegedAction() {
            public ResourceBundle run() {
                try {
                    return ResourceBundle.getBundle("sun.util.logging.resources.logging", var0, ClassLoader.getSystemClassLoader());
                } catch (MissingResourceException var2) {
                    throw new InternalError(var2.toString());
                }
            }
        });
    }

I have got crash report for locale en_AU too.

Since the crashing code is not controlled by me, how do I prevent this crash?

Body:
If it works a resource file as suggested by the other answer is a better option, but if that doesn't pan out I have another option. Assuming that you don't need the logging you should be able to disable it like this:

try {
    Class<?> cls = Class.forName("sun.util.logging.PlatformLogger");
    Field field = cls.getDeclaredField("loggingEnabled");
    field.setAccessible(true);
    field.set(null, Boolean.FALSE);
} catch(Exception e) {
    // Failed
}

If you do that early the PlatformLogger should construct a DefaultLoggerProxy instead of a JavaLoggerProxy, so the broken code never runs. This is ugly as it depends on internal implementation details and as it disables logging, but perhaps it works for your application?


问:
Get database connection from a connection pool
I am refactoring others code.  The one thing I notice is that of the manner on how the system is getting a connection from the connection pool.

Sample is like this. On every call of the service method, the system is making a context lookup on the JNDI for the datasource.

```<code>public class CheckinServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            //Obtain Connection
            InitialContext initialContext = new InitialContext();
            javax.sql.DataSource ds = (javax.sql.DataSource) initialContext
                    .lookup("jdbc/mysqldb");
            java.sql.Connection conn = ds.getConnection();
            //business logic
            //redirect
        } finally {
            conn.close();
        }
    }
}
</code>```

I do think that there is a performance hit on doing this every time.  I am thinking of another way around these on how to retrieve a connection from a connection pool.

I am thinking about using the servlet's init() method but I think that is not optimal.

答:
Do it once in a ServletContextListener instead of everytime in init() of many servlets. The contextInitialized() method is executed only once during webapp's startup.

```<code>public class Config implements ServletContextListener {
    private static final String ATTRIBUTE_NAME = "config";
    private DataSource dataSource;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext servletContext = event.getServletContext();
        String databaseName = servletContext.getInitParameter("database.name");
        try {
            dataSource = (DataSource) new InitialContext().lookup(databaseName);
        } catch (NamingException e) {
            throw new RuntimeException("Config failed: datasource not found", e);
        }
        servletContext.setAttribute(ATTRIBUTE_NAME, this);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        // NOOP.
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public static Config getInstance(ServletContext servletContext) {
        return (Config) servletContext.getAttribute(ATTRIBUTE_NAME);
    }
}
</code>```

Configure it as follows in web.xml:

```<code><context-param>
    <param-name>database.name</param-name>
    <param-value>jdbc/mysqldb</param-value>
</context-param>
<listener>
    <listener-class>com.example.Config</listener-class>
</listener>
</code>```

You can obtain it in your servlet as follows (init() or doXXX() method, you choose):

```<code>DataSource dataSource = Config.getInstance(getServletContext()).getDataSource();
</code>```

I'd however refactor it a step further, JDBC code should preferably be placed in its own classes, not in servlets. Lookup the DAO pattern.

Body:
I am refactoring others code.  The one thing I notice is that of the manner on how the system is getting a connection from the connection pool.

Sample is like this. On every call of the service method, the system is making a context lookup on the JNDI for the datasource.

public class CheckinServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            //Obtain Connection
            InitialContext initialContext = new InitialContext();
            javax.sql.DataSource ds = (javax.sql.DataSource) initialContext
                    .lookup("jdbc/mysqldb");
            java.sql.Connection conn = ds.getConnection();
            //business logic
            //redirect
        } finally {
            conn.close();
        }
    }
}

I do think that there is a performance hit on doing this every time.  I am thinking of another way around these on how to retrieve a connection from a connection pool.

I am thinking about using the servlet's init() method but I think that is not optimal.

Body:
Do it once in a ServletContextListener instead of everytime in init() of many servlets. The contextInitialized() method is executed only once during webapp's startup.

public class Config implements ServletContextListener {
    private static final String ATTRIBUTE_NAME = "config";
    private DataSource dataSource;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext servletContext = event.getServletContext();
        String databaseName = servletContext.getInitParameter("database.name");
        try {
            dataSource = (DataSource) new InitialContext().lookup(databaseName);
        } catch (NamingException e) {
            throw new RuntimeException("Config failed: datasource not found", e);
        }
        servletContext.setAttribute(ATTRIBUTE_NAME, this);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        // NOOP.
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public static Config getInstance(ServletContext servletContext) {
        return (Config) servletContext.getAttribute(ATTRIBUTE_NAME);
    }
}

Configure it as follows in web.xml:

<context-param>
    <param-name>database.name</param-name>
    <param-value>jdbc/mysqldb</param-value>
</context-param>
<listener>
    <listener-class>com.example.Config</listener-class>
</listener>

You can obtain it in your servlet as follows (init() or doXXX() method, you choose):

DataSource dataSource = Config.getInstance(getServletContext()).getDataSource();

I'd however refactor it a step further, JDBC code should preferably be placed in its own classes, not in servlets. Lookup the DAO pattern.


问:
Caching an object on the server for cross page access
I'm looking for an easy way to create a server side cached instance of an object so that I can refer to it upon later return. Basically, I'm using ASP.NET MVC Core in C# on a .NET web application. In a controller I call TutorialsController I have an action result for index that gets a collection of my videos and displays them on the index view. Then, when I select one of the videos, I want to go back to the previous controller and use a cached version of the original collection to retrieve the selected video object. I'm thinking that using some sort of server side caching would do the trick so I don't have to keep calling the YouTube API a bunch of times.

If you have any answers for server side caching or any other technique, I'd appreciate the feedback.

Thanks

答:
Because the OP mentions MVC Core App without the use of a Load Balancer please take a look at In-Memory caching provided by the IMemoryCache interface.

The following link to Microsoft documentation explains well how to set this up:

https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed

Within the documentation, there is mention the use of distributed caching using the IDistributedCache interface, only if you need it when/if you decide to host multiple instances.

https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed


问:
pandas: groupby multiple columns. How to get all combinations?
I have the following dataframe describing persons, where age_range has been computed from the age column

```<code>   age  gender group    age_range
0   46  F      1       >= 30 and < 60
1   50  F      1       >= 30 and < 60
2   63  F      2       >= 60
3   65  F      2       >= 60
4   34  F      1       >= 30 and < 60
5   42  F      2       >= 30 and < 60
6   55  F      1       >= 30 and < 60
7   57  M      1       >= 30 and < 60
</code>```

From there, I would like a table giving for each group, all age_ranges and the number of persons from the group and the age_range, even for empty bins (no person < 30 in any of the two groups and all members of group 1 are in >= 30 and < 60).

How could I get something like the following?

```<code>    group   age_range       count
0   1       < 30            0
1   1       >= 30 and < 60  5
2   1       >= 60           0
3   2       < 30            0
4   2       >= 30 and < 60  1
5   2       >= 60           2
</code>```

I tried multiple groupby options but never managed to get a complete table.

答:
To get the non-zero counts:

```<code>g = df.groupby(['group','age_range']).size().to_frame('count').reset_index()
</code>```

Then, you'll want a dummy table of all the group and age range combinations:

```<code>from itertools import product
combs = pd.DataFrame(list(product(df['group'], df['age_range'])),
                     columns=['group', 'age_range'])
</code>```

Merge (SQL join) g with this, and replace the NaNs with zeros:

```<code>result = g.merge(combs, how = 'right').fillna(0)
</code>```

A one-liner solution:

```<code>df.groupby(['group','age_range']).size().to_frame('count').reindex(MultiIndex.from_product([df['group'].unique(), df['age_range'].unique()], fill_value = 0))
</code>```

Body:
I have the following dataframe describing persons, where age_range has been computed from the age column

   age  gender group    age_range
0   46  F      1       >= 30 and < 60
1   50  F      1       >= 30 and < 60
2   63  F      2       >= 60
3   65  F      2       >= 60
4   34  F      1       >= 30 and < 60
5   42  F      2       >= 30 and < 60
6   55  F      1       >= 30 and < 60
7   57  M      1       >= 30 and < 60

From there, I would like a table giving for each group, all age_ranges and the number of persons from the group and the age_range, even for empty bins (no person < 30 in any of the two groups and all members of group 1 are in >= 30 and < 60).

How could I get something like the following?

    group   age_range       count
0   1       < 30            0
1   1       >= 30 and < 60  5
2   1       >= 60           0
3   2       < 30            0
4   2       >= 30 and < 60  1
5   2       >= 60           2

I tried multiple groupby options but never managed to get a complete table.

Body:
To get the non-zero counts:

g = df.groupby(['group','age_range']).size().to_frame('count').reset_index()

Then, you'll want a dummy table of all the group and age range combinations:

from itertools import product
combs = pd.DataFrame(list(product(df['group'], df['age_range'])),
                     columns=['group', 'age_range'])

Merge (SQL join) g with this, and replace the NaNs with zeros:

result = g.merge(combs, how = 'right').fillna(0)

A one-liner solution:

df.groupby(['group','age_range']).size().to_frame('count').reindex(MultiIndex.from_product([df['group'].unique(), df['age_range'].unique()], fill_value = 0))


问:
Use public key in RSA algorithm
I have desktop C# code (console, wpf etc) which generate key from base64 string and encrypt by it.

```<code>string b64Key = "";
byte[] decoded = Convert.FromBase64String(b64Key);
int modLength = BitConverter.ToInt32(decoded.Take(4).Reverse().ToArray(), 0);
byte[] mod = decoded.Skip(4).Take(modLength).ToArray();
int expLength = BitConverter.ToInt32(decoded.Skip(modLength + 4).Take(4).Reverse().ToArray(), 0);
byte[] exponent = decoded.Skip(modLength + 8).Take(expLength).ToArray();

RSAParameters key = new RSAParameters();
key.Modulus = mod;
key.Exponent = exponent;

var provider = new RSACryptoServiceProvider();
provider.ImportParameters(key);
var encrypted = provider.Encrypt(Encoding.UTF8.GetBytes("string"), true);
</code>```

I must reuse this part of code for UWP project.

I tried many ways but every time I catch an exception when I am trying to import public key:

```<code>// try to use DESKTOP key for understanding
byte[] mod = key.Modulus;
byte[] exponent = key.Exponent;
// this method concat arrays
var buf = this.Combine(mod, exponent);

// try to create key buffer from array
IBuffer keyBuffer = CryptographicBuffer.CreateFromByteArray(buf);
// try to create key buffer from base64 string
keyBuffer = CryptographicBuffer.DecodeFromBase64String("base64 string");

var provider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
var publicKey = provider.ImportPublicKey(keyBuffer, CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey);
// I tried all values in 'CryptographicPublicKeyBlobType' enum

var encryptData = CryptographicEngine.Encrypt(publicKey, CryptographicBuffer.ConvertStringToBinary("string", BinaryStringEncoding.Utf8), null);
</code>```

How can I import key correctly for the UWP project?

Thanks!

答:
At the first - I have only correct modulus and all. My base64 string is not correct public key (key in this string but there are a lot of other items).
After that I found only one right way to generate public key from modulus and exponent -> combine them. But I was still had exception. After that I tried to generate default key and change modulus part in it -> and it worked!</p>

```<code>           var provider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaOaepSha1);
            // create custom (random) key with size '1024'
            var standardKeyPair = provider.CreateKeyPair(1024);
            // export publick key to this default key
            var standardBuffer = standardKeyPair.ExportPublicKey(CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey);
            // copy it to bytes array
            byte[] standardKey;
            CryptographicBuffer.CopyToByteArray(standardBuffer, out standardKey);

            // change part of the key to our modules
            // I DON'T KNOW WHY, but starndart key has 7 bytes in prefix and 5 in suffix (nail)
            // we have 128 bytes in modulus and 140 in default key -> so we must make 140 bytes from our modulus
            Array.Copy(modulus, 0, standardKey, 7, modulus.Length);
</code>```

Title: Use public key in RSA algorithm

Body:
I have desktop C# code (console, wpf etc) which generate key from base64 string and encrypt by it.

string b64Key = "";
byte[] decoded = Convert.FromBase64String(b64Key);
int modLength = BitConverter.ToInt32(decoded.Take(4).Reverse().ToArray(), 0);
byte[] mod = decoded.Skip(4).Take(modLength).ToArray();
int expLength = BitConverter.ToInt32(decoded.Skip(modLength + 4).Take(4).Reverse().ToArray(), 0);
byte[] exponent = decoded.Skip(modLength + 8).Take(expLength).ToArray();

RSAParameters key = new RSAParameters();
key.Modulus = mod;
key.Exponent = exponent;

var provider = new RSACryptoServiceProvider();
provider.ImportParameters(key);
var encrypted = provider.Encrypt(Encoding.UTF8.GetBytes("string"), true);

I must reuse this part of code for UWP project.

I tried many ways but every time I catch an exception when I am trying to import public key:

// try to use DESKTOP key for understanding
byte[] mod = key.Modulus;
byte[] exponent = key.Exponent;
// this method concat arrays
var buf = this.Combine(mod, exponent);

// try to create key buffer from array
IBuffer keyBuffer = CryptographicBuffer.CreateFromByteArray(buf);
// try to create key buffer from base64 string
keyBuffer = CryptographicBuffer.DecodeFromBase64String("base64 string");

var provider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
var publicKey = provider.ImportPublicKey(keyBuffer, CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey);
// I tried all values in 'CryptographicPublicKeyBlobType' enum

var encryptData = CryptographicEngine.Encrypt(publicKey, CryptographicBuffer.ConvertStringToBinary("string", BinaryStringEncoding.Utf8), null);

How can I import key correctly for the UWP project?

Thanks!

Body:
At the first - I have only correct modulus and all. My base64 string is not correct public key (key in this string but there are a lot of other items).
After that I found only one right way to generate public key from modulus and exponent -> combine them. But I was still had exception. After that I tried to generate default key and change modulus part in it -> and it worked!

           var provider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaOaepSha1);
            // create custom (random) key with size '1024'
            var standardKeyPair = provider.CreateKeyPair(1024);
            // export publick key to this default key
            var standardBuffer = standardKeyPair.ExportPublicKey(CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey);
            // copy it to bytes array
            byte[] standardKey;
            CryptographicBuffer.CopyToByteArray(standardBuffer, out standardKey);

            // change part of the key to our modules
            // I DON'T KNOW WHY, but starndart key has 7 bytes in prefix and 5 in suffix (nail)
            // we have 128 bytes in modulus and 140 in default key -> so we must make 140 bytes from our modulus
            Array.Copy(modulus, 0, standardKey, 7, modulus.Length);


问:
Set session attribute using javascript
I'm using jqueryui autocomplete combobox in my jsp page. I need to set selected value of combo-box to the HttpSession.

I tried as below.

```<code>this._on(this.input, {
    autocompleteselect: function (event, ui) {
        // alert(ui.item.value);
        var value = ui.item.value;
        <% session.setAttribute("comboboxvalue",value); %>

        ui.item.option.selected = true;
        this._trigger("select", event, {
            item: ui.item.option
        });
}
</code>```

Problem with this way is that code don't recognize value param.

How can I solve this and set session attribute using javascript ?

答:
you can use javaScript operating form to post args to a servlet class,
and setSession in this servlet class. </p>

Title: Set session attribute using javascript

Body:
I'm using jqueryui autocomplete combobox in my jsp page. I need to set selected value of combo-box to the HttpSession.

I tried as below.

this._on(this.input, {
    autocompleteselect: function (event, ui) {
        // alert(ui.item.value);
        var value = ui.item.value;
        <% session.setAttribute("comboboxvalue",value); %>

        ui.item.option.selected = true;
        this._trigger("select", event, {
            item: ui.item.option
        });
}

Problem with this way is that code don't recognize value param.

How can I solve this and set session attribute using javascript ?


问:
SQLAlchemy core - how to make a ResultProxy case-insensitive wrt Schema column names?
When using SQL Alchemy core, how to I avoid errors from column name changes between backend databases?  I don't control the backends and I don't need to write to them, I just want to select data and look at the values.

Say you have create table foo(bar int).  Or something similar.  In SQL Server it will be create table FOO(BAR int)

Execute select * from FOO and this will work in fine in Oracle, Postgres and MS Sqlserver.

However, Postgres and Oracle will return sqlalchemy.engine.result.RowProxy instances where I can print(row.bar).

While SQL Server will return the exact same data, using the exact same query but I have to use print(row.BAR).

Now, each RowProxy in a result list uses a shared attribute, _keymap that maps fieldnames to location in the _row attribute which carries the data returned by the query for that database row.

So, given a _keymap {u'bar': (None, None, 0)}, which says that tuple position 0 holds bar, I could (and have done this) change to {u'bar': (None, None, 0),u'BAR': (None, None, 0)}.

Given that I could then print(row.bar) or print(row.BAR) without wondering whether the backend databases stores bar or BAR.

But, abstracting column upper/lower schema names seems a fairly common issue when using SQL Alchemy against multiple database engines, something it seems very competent at doing in general.

Did I miss something? Isn't there a built-in way?

This is SQL Alchemy using raw sql, i.e. my app builds the queries as plain sql.  I can't use the ORM, that's totally out of scope.  I also can't tweak the database backends' configurations to use upper or lower names - I don't control them.

答:
You might be looking for

```<code>create_engine(..., case_sensitive=False)
</code>```

The case_sensitive parameter defaults to True. If set to False, result columns match case-insensitively.

```<code>In [15]: engine = create_engine('sqlite://', case_sensitive=False)

In [16]: metadata = MetaData()

In [17]: metadata.bind = engine

In [18]: tbl = Table('foo', metadata, Column('BAR', Text))

In [19]: metadata.create_all()

In [22]: engine.execute(tbl.insert().values([('asdf',), ('qwer',)]))
Out[22]: <sqlalchemy.engine.result.ResultProxy at 0x7f03b4ba6b00>

In [23]: row = engine.execute(tbl.select()).fetchone()

In [24]: row
Out[24]: ('asdf',)

In [25]: row.BAR
Out[25]: 'asdf'

In [26]: row.BaR
Out[26]: 'asdf'

In [27]: row.bar
Out[27]: 'asdf'
</code>```

Body:
You might be looking for

create_engine(..., case_sensitive=False)

The case_sensitive parameter defaults to True. If set to False, result columns match case-insensitively.

In [15]: engine = create_engine('sqlite://', case_sensitive=False)

In [16]: metadata = MetaData()

In [17]: metadata.bind = engine

In [18]: tbl = Table('foo', metadata, Column('BAR', Text))

In [19]: metadata.create_all()

In [22]: engine.execute(tbl.insert().values([('asdf',), ('qwer',)]))
Out[22]: <sqlalchemy.engine.result.ResultProxy at 0x7f03b4ba6b00>

In [23]: row = engine.execute(tbl.select()).fetchone()

In [24]: row
Out[24]: ('asdf',)

In [25]: row.BAR
Out[25]: 'asdf'

In [26]: row.BaR
Out[26]: 'asdf'

In [27]: row.bar
Out[27]: 'asdf'


问:
Shortcuts for VisualStudio Online
In jira to add a comment we used the C letter as a shortcut. What are the shortcuts in visual studio online task board.

It takes too much time to go to the discussions part and add something there.

答:
I don't think VSTS has a specific shortcut to go to the discussion section.

You can see all the available shortcuts here

https://www.visualstudio.com/en-us/docs/reference/keyboard-shortcuts

Title: Shortcuts for VisualStudio Online


问:
Setting tooltip width and height dynamically
In WPF (C#) is there a way to set the tooltip's height and width dynamically (meaning in code). Thanks for the help.</p>

```<code>System.Windows.Controls.Image td = new System.Windows.Controls.Image();

BitmapImage myBitmapImage = new BitmapImage();
            myBitmapImage.BeginInit();
            myBitmapImage.UriSource = new Uri(Directory.GetCurrentDirectory() + "/Homepage.jpg");
            td.Width = 530;
            td.Height = 392;
            //myBitmapImage.DecodePixelWidth = 430;
            //myBitmapImage.DecodePixelHeight = 292;
            myBitmapImage.EndInit();
            td.Source = myBitmapImage;

            TextBlock textBlock = new TextBlock();
            BrushConverter conv = new BrushConverter();
            string strColor1 = bannerColor.SelectedItem.ToString();
            strColor1 = strColor1.Substring(strColor1.IndexOf(' ') + 1);
            SolidColorBrush col = conv.ConvertFromString(strColor1) as SolidColorBrush;

            textBlock.Foreground = col;
            textBlock.FontWeight = FontWeights.Bold;
            textBlock.FontSize = 18;
            textBlock.FontFamily = new System.Windows.Media.FontFamily("Tahoma");
            textBlock.Width = 100;
            textBlock.Height = 20;
            textBlock.Text = "BACKUP";
            textBlock.Margin = new Thickness(5, 5, 425, 367);

            Grid toolTipPanel = new Grid();
            toolTipPanel.Width = 530;
            toolTipPanel.Height = 392;
            toolTipPanel.Children.Add(td);
            toolTipPanel.Children.Add(textBlock);

            ToolTipService.SetToolTip(image1, toolTipPanel);
            ToolTipService.SetShowDuration(image1, 999999999);`
</code>```

答:
In your code just set the tooltip's height and width property to Double.NaN to have the width and height adjust dynamically.

```<code>_toolTip.Width = Double.NaN;
_toolTip.Height = Double.NaN;
</code>```

This will do the trick.

Body:
In WPF (C#) is there a way to set the tooltip's height and width dynamically (meaning in code). Thanks for the help.

System.Windows.Controls.Image td = new System.Windows.Controls.Image();

BitmapImage myBitmapImage = new BitmapImage();
            myBitmapImage.BeginInit();
            myBitmapImage.UriSource = new Uri(Directory.GetCurrentDirectory() + "/Homepage.jpg");
            td.Width = 530;
            td.Height = 392;
            //myBitmapImage.DecodePixelWidth = 430;
            //myBitmapImage.DecodePixelHeight = 292;
            myBitmapImage.EndInit();
            td.Source = myBitmapImage;

            TextBlock textBlock = new TextBlock();
            BrushConverter conv = new BrushConverter();
            string strColor1 = bannerColor.SelectedItem.ToString();
            strColor1 = strColor1.Substring(strColor1.IndexOf(' ') + 1);
            SolidColorBrush col = conv.ConvertFromString(strColor1) as SolidColorBrush;

            textBlock.Foreground = col;
            textBlock.FontWeight = FontWeights.Bold;
            textBlock.FontSize = 18;
            textBlock.FontFamily = new System.Windows.Media.FontFamily("Tahoma");
            textBlock.Width = 100;
            textBlock.Height = 20;
            textBlock.Text = "BACKUP";
            textBlock.Margin = new Thickness(5, 5, 425, 367);

            Grid toolTipPanel = new Grid();
            toolTipPanel.Width = 530;
            toolTipPanel.Height = 392;
            toolTipPanel.Children.Add(td);
            toolTipPanel.Children.Add(textBlock);

            ToolTipService.SetToolTip(image1, toolTipPanel);
            ToolTipService.SetShowDuration(image1, 999999999);`

Body:
In your code just set the tooltip's height and width property to Double.NaN to have the width and height adjust dynamically.

_toolTip.Width = Double.NaN;
_toolTip.Height = Double.NaN;

This will do the trick.


答:
Without any error handling:

```<code>var list = dic.Where(x => int.Parse(x.Value[1]) > 1)
              .Select(x => x.Key)
              .ToList();
</code>```

With the Where statement the entries where Value[1] is greater 1 will be filtered and with the Select statement the key from this entries will be selected. At least the collection will be converted in a List with the ToList method.

For further information have a look at 101 LINQ Samples in C#

Title: Search dictionary values and return List of keys meeting conditions

Body:
Without any error handling:

var list = dic.Where(x => int.Parse(x.Value[1]) > 1)
              .Select(x => x.Key)
              .ToList();

With the Where statement the entries where Value[1] is greater 1 will be filtered and with the Select statement the key from this entries will be selected. At least the collection will be converted in a List with the ToList method.

For further information have a look at 101 LINQ Samples in C#


问:
Implementing methods from an Angular 4 service in two different components
I have a service that I use in 2 diff components: one on buttons from a paginations and second in sidebar. Those 2 components are on the same level.
The problem is that on buttons components the methods works, but if I use them on sidebar don't work.

The Service

```<code>public navigate(action: string) {
 if (typeof this.ACTIONS[action] === 'undefined')
 return;

 let shift = this.ACTIONS[action];
 this.setCurrent(shift);

 const curr = this.getCurrent();
 this.activeIndex = curr.index;
 return this.router.navigate([curr.name]);
}

public setDisableFirst() {
 const curr = this.getCurrent();
 if(curr.index == 0) {
  return true;
 }
}

public setDisableLast() {
 const curr = this.getCurrent();
 return ((curr.index + 1) == (this._pages.length)) ? true : false;
}

public setActiveIndex() {
 const curr = this.getCurrent();
 return 'done-' + curr.index;

}
</code>```

Buttons

```<code> public disableFirst() {
  return this.PrevNextService.setDisableFirst();
 }

 public disableLast() {
  return this.PrevNextService.setDisableLast();
 }

 <button type="button" (click)="navigate('PREV')" [disabled]="disableFirst()">
 <button type="button" (click)="navigate('NEXT')" [disabled]="disableLast()">
</code>```

Sidebar

```<code> public activeClasss() {
  return this.PrevNextService.setActiveIndex();
 }

 <div class="list-group-wrapper"  [ngClass]="activeClasss()">
</code>```

If I console log in the Service this const curr = this.getCurrent(); inside the methods: navigate, setDisableFirst, setDisableLast, I get the exactly page number(1,2,3, etc) that I am when I click next or back from buttons component.

The last method from Service, setActiveIndex, uses the same variables like in the methods from above. Here, in the Service, if console log const curr = this.getCurrent(); I get only the first(1) page that I'm now. If I keep clicking on next or prev buttons, this const stays the same(1).

I use Angular 4. Can someone please give an idea why I get this behavior?

答:
How are you registering your service? Do you have it in a providers array of one of your modules? Something like the ProductService shown below?

Do you have it registered in more then one module? Or also in a component?

For a service to work correctly as a singleton its provider needs to be registered in only one place via the providers array as shown below.

```<code>@NgModule({
  imports: [
    SharedModule
    ])
  ],
  declarations: [
    ProductListComponent
  ],
  providers: [
    ProductService
  ]
})
export class ProductModule {}
</code>```

Body:
I have a service that I use in 2 diff components: one on buttons from a paginations and second in sidebar. Those 2 components are on the same level.
The problem is that on buttons components the methods works, but if I use them on sidebar don't work.

The Service

public navigate(action: string) {
 if (typeof this.ACTIONS[action] === 'undefined')
 return;

 let shift = this.ACTIONS[action];
 this.setCurrent(shift);

 const curr = this.getCurrent();
 this.activeIndex = curr.index;
 return this.router.navigate([curr.name]);
}

public setDisableFirst() {
 const curr = this.getCurrent();
 if(curr.index == 0) {
  return true;
 }
}

public setDisableLast() {
 const curr = this.getCurrent();
 return ((curr.index + 1) == (this._pages.length)) ? true : false;
}

public setActiveIndex() {
 const curr = this.getCurrent();
 return 'done-' + curr.index;

}

Buttons

 public disableFirst() {
  return this.PrevNextService.setDisableFirst();
 }

 public disableLast() {
  return this.PrevNextService.setDisableLast();
 }

 <button type="button" (click)="navigate('PREV')" [disabled]="disableFirst()">
 <button type="button" (click)="navigate('NEXT')" [disabled]="disableLast()">

Sidebar

 public activeClasss() {
  return this.PrevNextService.setActiveIndex();
 }

If I console log in the Service this const curr = this.getCurrent(); inside the methods: navigate, setDisableFirst, setDisableLast, I get the exactly page number(1,2,3, etc) that I am when I click next or back from buttons component.

The last method from Service, setActiveIndex, uses the same variables like in the methods from above. Here, in the Service, if console log const curr = this.getCurrent(); I get only the first(1) page that I'm now. If I keep clicking on next or prev buttons, this const stays the same(1).

I use Angular 4. Can someone please give an idea why I get this behavior?

Body:
How are you registering your service? Do you have it in a providers array of one of your modules? Something like the ProductService shown below?

Do you have it registered in more then one module? Or also in a component?

For a service to work correctly as a singleton its provider needs to be registered in only one place via the providers array as shown below.

@NgModule({
  imports: [
    SharedModule
    ])
  ],
  declarations: [
    ProductListComponent
  ],
  providers: [
    ProductService
  ]
})
export class ProductModule {}


问:
c++ segmentation fault on an allocation of vector
I'm coding a program for the correction of a DEM, regularly i need some values around a pixel, so i use a vector to store this, here is the code :

```<code>vector<float> choixCoordonne (const vector<vector<float>>& tabMnt, int i, int j, int nbLignes, int nbColonnes)
{

    vector <float> alt (9, numeric_limits<float>::infinity());

    if ( i >= 1 && i < nbLignes -1 && j >= 1 && j < nbColonnes-1)
        coord_InCenter(tabMnt, &alt, i, j);

    //Bordure Nord
    else if (i == 0 && j >= 1 && j <nbColonnes-1)
        coord_BordNord(tabMnt, &alt, i, j);
    //Bordure Sud
    else if (i == nbLignes-1 && j >= 1 && j <nbColonnes-1)
        coord_BordSud(tabMnt, &alt, i, j);
    //Bordure Ouest
    else if (j == 0 && i >= 1 && i <nbLignes-1)
        coord_BordOuest(tabMnt, &alt,i, j);
    //Bordure Est
    else if (j == nbColonnes-1 && i >= 1 && i <nbLignes-1)
        coord_BordEst(tabMnt, &alt, i, j);

    // Coin Nord-Ouest
    else if(i == 0 && j==0)
        coord_CoinNO(tabMnt, &alt, i, j);
    // Coin Nord-Est
    else if (i == 0 && j == nbColonnes-1)
        coord_CoinNE(tabMnt, &alt, i, j);
    // Coin Sud-Ouest
    else if (i == nbLignes-1 && j == 0)
        coord_CoinSO(tabMnt, &alt, i, j);
    // Coin Sud-Est
    else if (i == nbLignes-1 && j == nbColonnes -1)
        coord_CoinSE(tabMnt, &alt, i, j);

    else
    {
        cout <<"Erreur au niveau du repérage des cases dans le D8, cases non-classées"<<endl;
    }

    return alt;
}
</code>```

My segmentation fault appears on the fisrt line of this function. The debugger indicates something wrong with the constructor in stl_vector (particulary with the function allocator_traits>::allocate. I tried to use .resize() instead of the constructor but i obtain the same fault.

I add just below the functions where this function is called :

```<code>void rechercheZoneTraitement(const vector<vector<float>>& DirD8, vector<Position>* zoneTraitement, vector<Position>::iterator itOrigine, const int& nbLignes, const int& nbColonnes)
{
    vector<Position> tempVoisins;
    vector<Position> toTreat;
    vector<Position>::iterator it;

    toTreat.push_back(*itOrigine);
    it = toTreat.begin();

    while (it != toTreat.end())
    {
        cout<<"recherche zone de traitement et longueur d'a traiter : "<<toTreat.size()<<endl;
        cout << "x : "<<it->ligne<<" ; y :"<<it->colonne<<endl;
        tempVoisins = rechercheVoisins(DirD8, *it, nbLignes, nbColonnes);
        for(vector<Position>::iterator itVoisins = tempVoisins.begin(); itVoisins != tempVoisins.end(); ++itVoisins)
        {
            if (find(zoneTraitement->begin(), zoneTraitement->end(), *itVoisins) == zoneTraitement->end())
            {
                toTreat.push_back(*itVoisins);
                zoneTraitement->push_back(*itVoisins);
            }
        }

        toTreat.erase(it);
        it = toTreat.begin();
    }
}

vector<Position> rechercheVoisins (const vector<vector<float>>& DirD8, const Position& origine, const int& nbLignes, const int& nbColonnes)
{
    //vector<float> valeurVoisin;
    vector<Position> posVoisin;
    /*
    cout<<valeurVoisin.size()<<endl;
    valeurVoisin.resize(9);
    cout<<valeurVoisin.size()<<endl;
    */

    vector<float> valeurVoisin = choixCoordonne(DirD8, origine.ligne, origine.colonne, nbLignes, nbColonnes);

    //On commence à +1 car dans valeur voisins il y a aussi la case d'origine
    //et on sait déjà qu'elle est négative !
    //Ici on a pas le soucie des valeurs infinies
    vector<float>::iterator it = find_if (valeurVoisin.begin()+1, valeurVoisin.end(), [](float i){return i<0;});
    while(it != end(valeurVoisin))
    {
        posVoisin.push_back(getPositionWithIndex(distance(valeurVoisin.begin(), it), origine.ligne, origine.colonne));
        it = find_if (next(it), end(valeurVoisin), [](float i){return i<0;});
    }

    return posVoisin;
}
</code>```

The error appears at the second iteration of the while (it != toTreat.end()), and i can print/access the value of the iterator of this iteration.

I'm very confused.

答:
```<code> toTreat.push_back(*itVoisins);
</code>```

After the above statement, it has been invalidated, and then you invoke undefined behaviour when you do

```<code> toTreat.erase(it);
</code>```

Instead you could delete it first then push back

```<code> tempVoisins = rechercheVoisins(DirD8, *it, nbLignes, nbColonnes);
 toTreat.erase(it);//You are any how going to do this.Deleting here will save you from invalidating the iterator.
 for(vector<Position>::iterator itVoisins...)
 {}
 .
 .
 //toTreat.erase(it);// You dont need this now.
 it = toTreat.begin();
</code>```

Body:
I'm coding a program for the correction of a DEM, regularly i need some values around a pixel, so i use a vector to store this, here is the code :

vector<float> choixCoordonne (const vector<vector<float>>& tabMnt, int i, int j, int nbLignes, int nbColonnes)
{

    vector <float> alt (9, numeric_limits<float>::infinity());

    if ( i >= 1 && i < nbLignes -1 && j >= 1 && j < nbColonnes-1)
        coord_InCenter(tabMnt, &alt, i, j);

    //Bordure Nord
    else if (i == 0 && j >= 1 && j <nbColonnes-1)
        coord_BordNord(tabMnt, &alt, i, j);
    //Bordure Sud
    else if (i == nbLignes-1 && j >= 1 && j <nbColonnes-1)
        coord_BordSud(tabMnt, &alt, i, j);
    //Bordure Ouest
    else if (j == 0 && i >= 1 && i <nbLignes-1)
        coord_BordOuest(tabMnt, &alt,i, j);
    //Bordure Est
    else if (j == nbColonnes-1 && i >= 1 && i <nbLignes-1)
        coord_BordEst(tabMnt, &alt, i, j);

    // Coin Nord-Ouest
    else if(i == 0 && j==0)
        coord_CoinNO(tabMnt, &alt, i, j);
    // Coin Nord-Est
    else if (i == 0 && j == nbColonnes-1)
        coord_CoinNE(tabMnt, &alt, i, j);
    // Coin Sud-Ouest
    else if (i == nbLignes-1 && j == 0)
        coord_CoinSO(tabMnt, &alt, i, j);
    // Coin Sud-Est
    else if (i == nbLignes-1 && j == nbColonnes -1)
        coord_CoinSE(tabMnt, &alt, i, j);

    else
    {
        cout <<"Erreur au niveau du repérage des cases dans le D8, cases non-classées"<<endl;
    }

    return alt;
}

My segmentation fault appears on the fisrt line of this function. The debugger indicates something wrong with the constructor in stl_vector (particulary with the function allocator_traits>::allocate. I tried to use .resize() instead of the constructor but i obtain the same fault.

I add just below the functions where this function is called :

void rechercheZoneTraitement(const vector<vector<float>>& DirD8, vector<Position>* zoneTraitement, vector<Position>::iterator itOrigine, const int& nbLignes, const int& nbColonnes)
{
    vector<Position> tempVoisins;
    vector<Position> toTreat;
    vector<Position>::iterator it;

    toTreat.push_back(*itOrigine);
    it = toTreat.begin();

    while (it != toTreat.end())
    {
        cout<<"recherche zone de traitement et longueur d'a traiter : "<<toTreat.size()<<endl;
        cout << "x : "<<it->ligne<<" ; y :"<<it->colonne<<endl;
        tempVoisins = rechercheVoisins(DirD8, *it, nbLignes, nbColonnes);
        for(vector<Position>::iterator itVoisins = tempVoisins.begin(); itVoisins != tempVoisins.end(); ++itVoisins)
        {
            if (find(zoneTraitement->begin(), zoneTraitement->end(), *itVoisins) == zoneTraitement->end())
            {
                toTreat.push_back(*itVoisins);
                zoneTraitement->push_back(*itVoisins);
            }
        }

        toTreat.erase(it);
        it = toTreat.begin();
    }
}

vector<Position> rechercheVoisins (const vector<vector<float>>& DirD8, const Position& origine, const int& nbLignes, const int& nbColonnes)
{
    //vector<float> valeurVoisin;
    vector<Position> posVoisin;
    /*
    cout<<valeurVoisin.size()<<endl;
    valeurVoisin.resize(9);
    cout<<valeurVoisin.size()<<endl;
    */

    vector<float> valeurVoisin = choixCoordonne(DirD8, origine.ligne, origine.colonne, nbLignes, nbColonnes);

    //On commence à +1 car dans valeur voisins il y a aussi la case d'origine
    //et on sait déjà qu'elle est négative !
    //Ici on a pas le soucie des valeurs infinies
    vector<float>::iterator it = find_if (valeurVoisin.begin()+1, valeurVoisin.end(), [](float i){return i<0;});
    while(it != end(valeurVoisin))
    {
        posVoisin.push_back(getPositionWithIndex(distance(valeurVoisin.begin(), it), origine.ligne, origine.colonne));
        it = find_if (next(it), end(valeurVoisin), [](float i){return i<0;});
    }

    return posVoisin;
}

The error appears at the second iteration of the while (it != toTreat.end()), and i can print/access the value of the iterator of this iteration.

I'm very confused.

Body:
 toTreat.push_back(*itVoisins);

After the above statement, it has been invalidated, and then you invoke undefined behaviour when you do

 toTreat.erase(it);

Instead you could delete it first then push back

 tempVoisins = rechercheVoisins(DirD8, *it, nbLignes, nbColonnes);
 toTreat.erase(it);//You are any how going to do this.Deleting here will save you from invalidating the iterator.
 for(vector<Position>::iterator itVoisins...)
 {}
 .
 .
 //toTreat.erase(it);// You dont need this now.
 it = toTreat.begin();


问:
cannot add/push google-services.json in android studio to github
I downloaded google-services.json file and put it in my local machine. I committed and pushed it to my github repository. When I tried to pull from the github repository on my other PC, I could not see the google-services.json file.

How can I push google-services.json file to github? Or is it not possible at all because it contains confidential information?

But I saw some people could add the file on their github repository.

答:
git add + git commit + git push should do the job? Are you sure you added the file and committed it? Was it shown in the commit? If you work with GitHub was it shown online?

How can I push google-services.json file to github? Or is it not possible at all because it contains confidential information?

No, Git/GitHub doesn't check whether information is confidential or not.

Edit: The file was mentioned in the gitignore file. That was the reason why the problem occurred.