问:
Safe use of HttpURLConnection
When using HttpURLConnection does the InputStream need to be closed if we do not 'get' and use it?

i.e. is this safe?

```<code>HttpURLConnection conn = (HttpURLConnection) uri.getURI().toURL().openConnection();
conn.connect();
// check for content type I don't care about
if (conn.getContentType.equals("image/gif") return;
// get stream and read from it
InputStream is = conn.getInputStream();
try {
    // read from is
} finally {
    is.close();
}
</code>```

Secondly, is it safe to close an InputStream before all of it's content has been fully read?

Is there a risk of leaving the underlying socket in ESTABLISHED or even CLOSE_WAIT state?

答:
When using HttpURLConnection does the InputStream need to be closed if we do not 'get' and use it?

Yes, it always needs to be closed.

i.e. is this safe?

Not 100%, you run the risk of getting a NPE. Safer is:

```<code>InputStream is = null;
try {
    is = conn.getInputStream()
    // read from is
} finally {
    if (is != null) {
        is.close();
    }
}
</code>```

Title: Safe use of HttpURLConnection

Body:
When using HttpURLConnection does the InputStream need to be closed if we do not 'get' and use it?

i.e. is this safe?

HttpURLConnection conn = (HttpURLConnection) uri.getURI().toURL().openConnection();
conn.connect();
// check for content type I don't care about
if (conn.getContentType.equals("image/gif") return;
// get stream and read from it
InputStream is = conn.getInputStream();
try {
    // read from is
} finally {
    is.close();
}

Secondly, is it safe to close an InputStream before all of it's content has been fully read?

Is there a risk of leaving the underlying socket in ESTABLISHED or even CLOSE_WAIT state?

Body:
When using HttpURLConnection does the InputStream need to be closed if we do not 'get' and use it?

Yes, it always needs to be closed.

i.e. is this safe?

Not 100%, you run the risk of getting a NPE. Safer is:

InputStream is = null;
try {
    is = conn.getInputStream()
    // read from is
} finally {
    if (is != null) {
        is.close();
    }
}


来源: stackexchange

问:
Using strsplit within dplyr::mutate (without tibble::data_frame) raises "Evaluation error: non-character argument"
Edit: there was a typo in my df creation, with a missing _ on the last value of MediaName; this is now corrected.

I want to create a new variable TrialId in a data frame as part of the value of another variable MediaName depending on the value of a third variable Phase, and thought I could do that using strsplit and ifelse within a dplyr::mutate as follows:

```<code>library(dplyr)

# Creating a simple data frame for the example
df <- data.frame(Phase = c(rep("Familiarisation",8),rep("Test",3)),
                 MediaName = c("Flip_A1_G1","Reg_B2_S1","Reg_A2_G1","Flip_B1_S1",
                               "Reg_A1_G2","Flip_B2_S2","Reg_A2_G2","Flip_B1_S2",
                               "HC_A1L","TC_B1R","RC_BL_2R"))

# Creating a new column
df <- df %>%
  mutate(TrialId = ifelse(Phase == "Familiarisation",
                          sapply(strsplit(MediaName, "_"), "[", 2),
                          sapply(strsplit(MediaName, "_"), "[", 1)))
</code>```

The expected result being

```<code>> df$TrialId
[1] "A1" "B2" "A2" "B1" "A1" "B2" "A2" "B1" "HC" "TC" "RC"
</code>```

However this gives me the following error because, I believe, of the strsplit:

```<code>Error in mutate_impl(.data, dots) :
  Evaluation error: non-character argument.
</code>```

I know from this SO question that I can easily solve my issue by defining, in this small example, my data frame as a tibble::data_frame, without knowing why this solves the issue. I can't do exactly that though as in my actual code df comes from reading a csv file (with read.csv()). I have been thinking that using df <- df %>% as_tibble() %>% mutate(...) would solve the issue in a similar way, but it doesn't (why?).

Is there a way to actually use tibble even when reading files? Or is there another way of achieving what I need to do, without using strsplit maybe?

I'm also reading on this other SO question that you can use tidyr::separate but it isn't doing exactly what I want as I need to keep either the first or second value depending on the value of Phase.

答:
The problem you encountered is because the string was automatically converted in a factor, therefore you cannot apply strsplit() to a non-string object. My solution simply convert the MediaName into a string type.

```<code>require(dplyr)
df <- df %>%
        dplyr::mutate(MediaName = as.character(levels(df$MediaName))[df$MediaName]) %>%
                dplyr::mutate(TrialId = ifelse(Phase == "Familiarisation",
                                        sapply(strsplit(MediaName, "_"), "[", 2),
                                        sapply(strsplit(MediaName, "_"), "[", 1)))

solution<- c("A1", "B2", "A2", "B1", "A1", "B2", "A2", "B1", "HC", "TC", "RC")
identical(solution, df$TrialId)
[1] TRUE
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Edit: there was a typo in my df creation, with a missing _ on the last value of MediaName; this is now corrected.

I want to create a new variable TrialId in a data frame as part of the value of another variable MediaName depending on the value of a third variable Phase, and thought I could do that using strsplit and ifelse within a dplyr::mutate as follows:

library(dplyr)

# Creating a simple data frame for the example
df <- data.frame(Phase = c(rep("Familiarisation",8),rep("Test",3)),
                 MediaName = c("Flip_A1_G1","Reg_B2_S1","Reg_A2_G1","Flip_B1_S1",
                               "Reg_A1_G2","Flip_B2_S2","Reg_A2_G2","Flip_B1_S2",
                               "HC_A1L","TC_B1R","RC_BL_2R"))

# Creating a new column
df <- df %>%
  mutate(TrialId = ifelse(Phase == "Familiarisation",
                          sapply(strsplit(MediaName, "_"), "[", 2),
                          sapply(strsplit(MediaName, "_"), "[", 1)))

The expected result being

> df$TrialId
[1] "A1" "B2" "A2" "B1" "A1" "B2" "A2" "B1" "HC" "TC" "RC"

However this gives me the following error because, I believe, of the strsplit:

Error in mutate_impl(.data, dots) :
  Evaluation error: non-character argument.

I know from this SO question that I can easily solve my issue by defining, in this small example, my data frame as a tibble::data_frame, without knowing why this solves the issue. I can't do exactly that though as in my actual code df comes from reading a csv file (with read.csv()). I have been thinking that using df <- df %>% as_tibble() %>% mutate(...) would solve the issue in a similar way, but it doesn't (why?).

Is there a way to actually use tibble even when reading files? Or is there another way of achieving what I need to do, without using strsplit maybe?

I'm also reading on this other SO question that you can use tidyr::separate but it isn't doing exactly what I want as I need to keep either the first or second value depending on the value of Phase.

Body:
The problem you encountered is because the string was automatically converted in a factor, therefore you cannot apply strsplit() to a non-string object. My solution simply convert the MediaName into a string type.

require(dplyr)
df <- df %>%
        dplyr::mutate(MediaName = as.character(levels(df$MediaName))[df$MediaName]) %>%
                dplyr::mutate(TrialId = ifelse(Phase == "Familiarisation",
                                        sapply(strsplit(MediaName, "_"), "[", 2),
                                        sapply(strsplit(MediaName, "_"), "[", 1)))

solution<- c("A1", "B2", "A2", "B1", "A1", "B2", "A2", "B1", "HC", "TC", "RC")
identical(solution, df$TrialId)
[1] TRUE


问:
Notification of Bluetooth connection in UWP app
I'm using Windows.Devices API in a WinForms App on Windows 10. I'm connecting to a Bluetooth Barcode scanner. The connection works fine and I'm getting an Event when the connection has been established and also when the connection has been dropped (disconnected).
But when I change the battery in the scanner and the scanner re-connects to Windows I'm getting no Event.
My question now is: if there's any possibility to get an Event when the device re-connects over Bleutooth?

My need is to reconnect the socket to the device after the device has been reconnected over Bluetooth.

EDIT: Dear admins, this is not a WinForms issue. This issue even doesn't deal with UI at all. It's just an API issue with the Windows.Devices UWP API. Please stop suggesting changing the tags.

Thanks
Sven

Some Sample Code:

```<code>_device = await BluetoothDevice.FromBluetoothAddressAsync(decimalAddress);
_device.ConnectionStatusChanged += OnDeviceConnectionStatusChanged;
</code>```

Event is called only on first connect and on disconnect of device:

```<code>private void OnDeviceConnectionStatusChanged(BluetoothDevice sender, object args)
{
}
</code>```

答:
What I've found out so far is that it seems very common that the event never raises again. One has to actively create a new connection to the device, that is, for example by opening a socket for receiving data.
So the solution for my problem was to connect to the bluetooth device by calling

```<code>StreamSocket.ConnectAsync()
</code>```

again to establish a new connection. Afterwards the ConnectionStatusChanged is raised with state connected.

Good luck

Sven

Body:
I'm using Windows.Devices API in a WinForms App on Windows 10. I'm connecting to a Bluetooth Barcode scanner. The connection works fine and I'm getting an Event when the connection has been established and also when the connection has been dropped (disconnected).
But when I change the battery in the scanner and the scanner re-connects to Windows I'm getting no Event.
My question now is: if there's any possibility to get an Event when the device re-connects over Bleutooth?

My need is to reconnect the socket to the device after the device has been reconnected over Bluetooth.

EDIT: Dear admins, this is not a WinForms issue. This issue even doesn't deal with UI at all. It's just an API issue with the Windows.Devices UWP API. Please stop suggesting changing the tags.

Thanks
Sven

Some Sample Code:

_device = await BluetoothDevice.FromBluetoothAddressAsync(decimalAddress);
_device.ConnectionStatusChanged += OnDeviceConnectionStatusChanged;

Event is called only on first connect and on disconnect of device:

private void OnDeviceConnectionStatusChanged(BluetoothDevice sender, object args)
{
}

Body:
What I've found out so far is that it seems very common that the event never raises again. One has to actively create a new connection to the device, that is, for example by opening a socket for receiving data.
So the solution for my problem was to connect to the bluetooth device by calling

StreamSocket.ConnectAsync()

again to establish a new connection. Afterwards the ConnectionStatusChanged is raised with state connected.

Good luck

Sven


问:
How to automatically add !default to all SASS/SCSS variables
To impmlement themes using SASS/SCSS we have default.scss file with global variables (and the default theme at the same time) where some variables are derived from the basic theme color. In SCSS theme file (theme.scss) loaded before defaults.css we always override the basic theme color and also override some variables specific to the theme. For omitted variables we expect that they will get values from the defaults.scss but if there is $text-color = $basic-color assignment then value of $basic-color should be taken from the theme, not the default one.

/* theme.scss... */
$base-color: green;
/* Some variables may be omitted in some themes
   to use theme base-color by default.
   In this theme $text-color is expected to be green.
  $text-color: teal;
*/
$button-color: black;

/* default.scss */
$base-color: blue          !default;
$text-color: $base-color   !default;
$button-color: $base-color !default;
```

See this example at https://jsfiddle.net/ena66ag3/

It works fine but I don't wish to append !default to each line of default.scss as there are hundreds of lines and it makes it hard to read the values. Is there a way to make it automatically with some optiopns in the import directive or in the top of the file?

答:
Unfortunately there is no current support in sass to specify variable flags for multiple variables at once. They have to be added to each line, and that is the current best practice for declaring your theme defaults.

You can see that both bootstrap (v4) and foundation sites do it this way, as both are respectable frameworks built on Sass I would recommend going that route.

There is also no way to declare variables with dynamic variable names, so the only way to work around it at this point would be to have some preprocessing that appends the default flag to all the variables in your default file, but that is probably a bigger issue as it would hide rather important implementation details from anyone reading it.

If you still want to have the behavior of defaults without default flags with something that is supported by the language it would be using a map.

```<code>/*
 * In theme.scss
 */
$globals: (
  line-height: 10,             // theme value
  something-special: 'black',  // theme value
);

/*
 * In defaults.scss
 */
// Ensure there is an empty globals map if no theme is loaded
$globals: () !default;

// Merge theme defaults over the default values
$globals: map-merge((
  font-size: 1,      // default value
  line-height: 2,    // default value
), $globals);

/**
 * Usage
 */
div {
  font-size: map-get($globals, font-size);              // 1
  line-height: map-get($globals, line-height);          // 10
  border-radius: map-get($globals, something-special);  // black
}
</code>```

However I would not go with this as it leads to somewhat bizarre code for accessing basic theme variables. With the currently available options appending a default flag to all the lines is probably your best bet.

Body:
To impmlement themes using SASS/SCSS we have default.scss file with global variables (and the default theme at the same time) where some variables are derived from the basic theme color. In SCSS theme file (theme.scss) loaded before defaults.css we always override the basic theme color and also override some variables specific to the theme. For omitted variables we expect that they will get values from the defaults.scss but if there is $text-color = $basic-color assignment then value of $basic-color should be taken from the theme, not the default one.

/* theme.scss... */
$base-color: green;
/* Some variables may be omitted in some themes
   to use theme base-color by default.
   In this theme $text-color is expected to be green.
  $text-color: teal;
*/
$button-color: black;

/* default.scss */
$base-color: blue          !default;
$text-color: $base-color   !default;
$button-color: $base-color !default;

See this example at https://jsfiddle.net/ena66ag3/

It works fine but I don't wish to append !default to each line of default.scss as there are hundreds of lines and it makes it hard to read the values. Is there a way to make it automatically with some optiopns in the import directive or in the top of the file?

Body:
Unfortunately there is no current support in sass to specify variable flags for multiple variables at once. They have to be added to each line, and that is the current best practice for declaring your theme defaults.

You can see that both bootstrap (v4) and foundation sites do it this way, as both are respectable frameworks built on Sass I would recommend going that route.

There is also no way to declare variables with dynamic variable names, so the only way to work around it at this point would be to have some preprocessing that appends the default flag to all the variables in your default file, but that is probably a bigger issue as it would hide rather important implementation details from anyone reading it.

If you still want to have the behavior of defaults without default flags with something that is supported by the language it would be using a map.

/*
 * In theme.scss
 */
$globals: (
  line-height: 10,             // theme value
  something-special: 'black',  // theme value
);

/*
 * In defaults.scss
 */
// Ensure there is an empty globals map if no theme is loaded
$globals: () !default;

// Merge theme defaults over the default values
$globals: map-merge((
  font-size: 1,      // default value
  line-height: 2,    // default value
), $globals);

/**
 * Usage
 */
div {
  font-size: map-get($globals, font-size);              // 1
  line-height: map-get($globals, line-height);          // 10
  border-radius: map-get($globals, something-special);  // black
}

However I would not go with this as it leads to somewhat bizarre code for accessing basic theme variables. With the currently available options appending a default flag to all the lines is probably your best bet.


问:
How to use DTO in this case?
I have a bunch of methods in my controller and now it looks like this:

```<code>class ItemController
{
     public function getItems(Request $request)
     {
         return $this->itemService->getItems($this->getUser(), $request->get('category_id'));
     }

     public function getItem(int $id, Request $request)
     {
         return $this->itemService->getItem($this->getUser(), $id, $request->get('category_id'));
     }

     public function patchItem(ItemDTO $item, Request $request)
     {
         return $this->itemService->patchItem($this->getUser(), $item, $request->get('category_id'));
     }
}
</code>```

I want to avoid transfer a lot of parameters to remote interface and add categoryId, id and user to my ItemDTO. Is it good approach if I have many fields in my ItemDTO, but I use only two? Like this:

```<code> public function getItem(int $id, Request $request)
 {
     $itemDTO = new ItemDTO($this->getUser(), $id, $request->get('category_id')); //here $title and others is empty
     return $this->itemService->getItem($itemDTO);
 }
</code>```

And my DTO like this:

```<code>class ItemDTO
{
    final public $user;

    final public $id;

    final public $categoryId;

    final public $title;

    //...

    public function __construct($user = null, $id = null, $categoryId = null, $title = null, ...)
    {
       //assign variables
    }
}
</code>```

Maybe I need separate DTOs for each method? Also, can DTO contains fields like $pageNumber,$pageSize and other filters? Is it good approach?

答: If you were just considering using the two parameters, I would consider it a query by example pattern, and it would be fairly acceptable.  Because you are considering adding things like PageNumber & PageSize, I'd say you have blown that out, and you should now consider a separate ItemQuery DTO which has the parameters you need.</p>

Title: How to use DTO in this case?

Body:
I have a bunch of methods in my controller and now it looks like this:

class ItemController
{
     public function getItems(Request $request)
     {
         return $this->itemService->getItems($this->getUser(), $request->get('category_id'));
     }

     public function getItem(int $id, Request $request)
     {
         return $this->itemService->getItem($this->getUser(), $id, $request->get('category_id'));
     }

     public function patchItem(ItemDTO $item, Request $request)
     {
         return $this->itemService->patchItem($this->getUser(), $item, $request->get('category_id'));
     }
}

I want to avoid transfer a lot of parameters to remote interface and add categoryId, id and user to my ItemDTO. Is it good approach if I have many fields in my ItemDTO, but I use only two? Like this:

 public function getItem(int $id, Request $request)
 {
     $itemDTO = new ItemDTO($this->getUser(), $id, $request->get('category_id')); //here $title and others is empty
     return $this->itemService->getItem($itemDTO);
 }

And my DTO like this:

class ItemDTO
{
    final public $user;

    final public $id;

    final public $categoryId;

    final public $title;

    //...

    public function __construct($user = null, $id = null, $categoryId = null, $title = null, ...)
    {
       //assign variables
    }
}

Maybe I need separate DTOs for each method? Also, can DTO contains fields like $pageNumber,$pageSize and other filters? Is it good approach?


问:
Accessing Knockout component DOM from required AMD viewModel
I load my Knockout component this way:

```<code>ko.components.register("example", {
    viewModel: {require: "widgets/example"},
    template:  {require: "text!widgets/example.html"}
});
</code>```

with example.js (extremely simplified):

```<code>"use strict";

define(["knockout"], function(ko) {

    function ExampleWidgetViewModel(params) {

        this.editedText = ko.observable("Example");
    }

    return ExampleWidgetViewModel;
});
</code>```

and example.html:

```<code><div id="example-dlg", data-bind="text: editedText"></div>
</code>```

The component is called as usual as <example></example> and everything works perfectly. But I want to access the DOM to remove the need of the id in the template.
Tried the method from the documentation changing example.js to be:

```<code>"use strict";

define(["knockout"], function(ko) {

    function ExampleWidgetViewModel(params, componentInfo) {

        this.editedText = ko.observable("Example");
    }

    return {createViewModel: ExampleWidgetViewModel};
});
</code>```

But it complains that editedText is not found. Same problem with other variations like this:

```<code>"use strict";

define(["knockout"], function(ko) {

    function creaExample(params, componentInfo) {
        let ExampleWidgetViewModel = (params) => {

             this.editedText = ko.observable("Example");
        }
        return ExampleWidgetViewModel;
    }
    return {createViewModel: creaExample};
});
</code>```

Could you provide a working example? Thanks!

答:
Nothing better than asking for help to find a solution... I was wrongly calling the view model. The correct example.js file is:

```<code>"use strict";

define(["jquery", "knockout"], function($, ko) {

    function factory(params, componentInfo) {
        function ViewModel() {

            // To show how to access the component external div
            console.log($(componentInfo.element.firstChild).attr("id"));

            // To show it can correctly access parameters
            this.editedText = params.oneParameter;
        }
        return new ViewModel();
    }
    return {createViewModel: factory};
});
</code>```

Body:
I load my Knockout component this way:

ko.components.register("example", {
    viewModel: {require: "widgets/example"},
    template:  {require: "text!widgets/example.html"}
});

with example.js (extremely simplified):

"use strict";

define(["knockout"], function(ko) {

    function ExampleWidgetViewModel(params) {

        this.editedText = ko.observable("Example");
    }

    return ExampleWidgetViewModel;
});

and example.html:

The component is called as usual as <example></example> and everything works perfectly. But I want to access the DOM to remove the need of the id in the template.
Tried the method from the documentation changing example.js to be:

"use strict";

define(["knockout"], function(ko) {

    function ExampleWidgetViewModel(params, componentInfo) {

        this.editedText = ko.observable("Example");
    }

    return {createViewModel: ExampleWidgetViewModel};
});

But it complains that editedText is not found. Same problem with other variations like this:

"use strict";

define(["knockout"], function(ko) {

    function creaExample(params, componentInfo) {
        let ExampleWidgetViewModel = (params) => {

             this.editedText = ko.observable("Example");
        }
        return ExampleWidgetViewModel;
    }
    return {createViewModel: creaExample};
});

Could you provide a working example? Thanks!

Body:
Nothing better than asking for help to find a solution... I was wrongly calling the view model. The correct example.js file is:

"use strict";

define(["jquery", "knockout"], function($, ko) {

    function factory(params, componentInfo) {
        function ViewModel() {

            // To show how to access the component external div
            console.log($(componentInfo.element.firstChild).attr("id"));

            // To show it can correctly access parameters
            this.editedText = params.oneParameter;
        }
        return new ViewModel();
    }
    return {createViewModel: factory};
});


问:
Live search through table rows
I want to do a live search through the table rows, using jQuery, the "live" word is the key, because I want to type the keywords in the text input, on the same site and I'd like jQuery to  automaticaly sort (or remove those who doesn't match the search query) the table rows.

Here is my HTML:

```<code><table>
    <tr><th>Unique ID</th><th>Random ID</th></tr>
    <tr><td>214215</td><td>442</td></tr>
    <tr><td>1252512</td><td>556</td></tr>
    <tr><td>2114</td><td>4666</td></tr>
    <tr><td>3245466</td><td>334</td></tr>
    <tr><td>24111</td><td>54364</td></tr>
</table>
</code>```

And if I would fe. search by the Unique ID, it should show the only rows that starts from the certain number for the Unique ID. Fe. if I would type '2' in the search input box, the following rows should stay, as they begin with 2:

```<code><table>
    <tr><th>Unique ID</th><th>Random ID</th></tr>
    <tr><td>214215</td><td>442</td></tr>
    <tr><td>2114</td><td>4666</td></tr>
    <tr><td>24111</td><td>54364</td></tr>
</table>
</code>```

If I would type 24, then there should be only one row visible as it begins from the 24:

```<code><table>
    <tr><th>Unique ID</th><th>Random ID</th></tr>
    <tr><td>24111</td><td>54364</td></tr>
</table>
</code>```

If you guys could give me some tips on how to do something like this I would appreciate it so much.

Thank you.

答:
Old question but i find out how to do it faster. For my example: i have about 10k data in my table so i need some fast search machine.

Here is what i did:

```<code>$('input[name="search"]').on('keyup', function() {

        var input, filter, tr, td, i;

        input  = $(this);
        filter = input.val().toUpperCase();
        tr     = $("table tr");

        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[0]; // <-- change number if you want other column to search
            if (td) {
                if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
    })
</code>```

Hope it helps somebody.

Title: Live search through table rows

Body:
I want to do a live search through the table rows, using jQuery, the "live" word is the key, because I want to type the keywords in the text input, on the same site and I'd like jQuery to  automaticaly sort (or remove those who doesn't match the search query) the table rows.

Here is my HTML:

Unique ID	Random ID

214215	442

1252512	556

2114	4666

3245466	334

24111	54364

And if I would fe. search by the Unique ID, it should show the only rows that starts from the certain number for the Unique ID. Fe. if I would type '2' in the search input box, the following rows should stay, as they begin with 2:

Unique ID	Random ID

214215	442

2114	4666

24111	54364

If I would type 24, then there should be only one row visible as it begins from the 24:

Unique ID	Random ID

24111	54364

If you guys could give me some tips on how to do something like this I would appreciate it so much.

Thank you.

Body:
Old question but i find out how to do it faster. For my example: i have about 10k data in my table so i need some fast search machine.

Here is what i did:

$('input[name="search"]').on('keyup', function() {

        var input, filter, tr, td, i;

        input  = $(this);
        filter = input.val().toUpperCase();
        tr     = $("table tr");

        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[0]; // <-- change number if you want other column to search
            if (td) {
                if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
    })

Hope it helps somebody.


问:
If i try to change width & height of an image the image size increases.What should i do in order to get a reduced size image?
Change width & height of an image with reduced size

```<code>Image Resize(Image image, int w, int h)
    {
        Bitmap bmp = new Bitmap(w, h);
        Graphics graphic = Graphics.FromImage(bmp);

        graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        graphic.CompositingQuality = CompositingQuality.HighQuality;
        graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
        graphic.DrawImage(image, 0, 0, w, h);

        graphic.Dispose();
        return bmp;
    }
</code>```

Even if i'm reducing the width & height of an image my image size increases.How to fix this ?

I expect the converted file to be of less size than the original image.

答:
Well, if u want to reduce storage of image, this can be what u want:

```<code>// Make sure to include this at the top
using System.Drawing.Imaging;

/// <summary>
/// Saves an image as a jpeg image, with the given quality
/// </summary>
/// <param name="path"> Path to which the image would be saved. </param>
/// <param name="quality"> An integer from 0 to 100, with 100 being the highest quality. </param>
public static void SaveJpeg (string path, Image img, int quality)
{
    if (quality<0  ||  quality>100)
        throw new ArgumentOutOfRangeException("quality must be between 0 and 100.");

     // Encoder parameter for image quality
     EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, quality);
     // JPEG image codec
     ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
     EncoderParameters encoderParams = new EncoderParameters(1);
     encoderParams.Param[0] = qualityParam;
     img.Save(path, jpegCodec, encoderParams);
}

/// <summary>
/// Returns the image codec with the given mime type
/// </summary>
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
     // Get image codecs for all image formats
     ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

     // Find the correct image codec
     for(int i=0; i<codecs.Length; i++)
         if(codecs[i].MimeType == mimeType)
             return codecs[i];

     return null;
 }
</code>```

Then you can do this:

```<code>// First load the image somehow
Image myImage = Image.FromFile(pathToImage, true);
// Save the image with a quality of 50%
SaveJpeg (destImagePath, myImage, 50);
</code>```

Body:
Change width & height of an image with reduced size

Image Resize(Image image, int w, int h)
    {
        Bitmap bmp = new Bitmap(w, h);
        Graphics graphic = Graphics.FromImage(bmp);

        graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        graphic.CompositingQuality = CompositingQuality.HighQuality;
        graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
        graphic.DrawImage(image, 0, 0, w, h);

        graphic.Dispose();
        return bmp;
    }

Even if i'm reducing the width & height of an image my image size increases.How to fix this ?

I expect the converted file to be of less size than the original image.

Body:
Well, if u want to reduce storage of image, this can be what u want:

// Make sure to include this at the top
using System.Drawing.Imaging;

/// <summary>
/// Saves an image as a jpeg image, with the given quality
/// </summary>
/// <param name="path"> Path to which the image would be saved. </param>
/// <param name="quality"> An integer from 0 to 100, with 100 being the highest quality. </param>
public static void SaveJpeg (string path, Image img, int quality)
{
    if (quality<0  ||  quality>100)
        throw new ArgumentOutOfRangeException("quality must be between 0 and 100.");

     // Encoder parameter for image quality
     EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, quality);
     // JPEG image codec
     ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
     EncoderParameters encoderParams = new EncoderParameters(1);
     encoderParams.Param[0] = qualityParam;
     img.Save(path, jpegCodec, encoderParams);
}

/// <summary>
/// Returns the image codec with the given mime type
/// </summary>
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
     // Get image codecs for all image formats
     ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

     // Find the correct image codec
     for(int i=0; i<codecs.Length; i++)
         if(codecs[i].MimeType == mimeType)
             return codecs[i];

     return null;
 }

Then you can do this:

// First load the image somehow
Image myImage = Image.FromFile(pathToImage, true);
// Save the image with a quality of 50%
SaveJpeg (destImagePath, myImage, 50);


问:
Google App Engine Incremental Identifier (ID)
I'm building a software for a school hosted at GAE and I need to create and sequence identifier to a new student when created, it doesn't really need to be the "key", but need this number to be incremented by one, each time a new student is added, it's gonna be the student number printed at the school card.

Using the low level API, I'm doing this:

```<code>student = new Entity("student")
student << params.subMap(["name", "birthdate"])
student.save()
</code>```

It's creating the ID but it not been increment by one, it is kind of random...

I also tried to understand the KeyRange, but got nothing out of it.

Some help?

答: You might want to look at How to implement "autoincrement" on Google AppEngine where you find a Python implementation of sequence numbers.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm building a software for a school hosted at GAE and I need to create and sequence identifier to a new student when created, it doesn't really need to be the "key", but need this number to be incremented by one, each time a new student is added, it's gonna be the student number printed at the school card.

Using the low level API, I'm doing this:

student = new Entity("student")
student << params.subMap(["name", "birthdate"])
student.save()

It's creating the ID but it not been increment by one, it is kind of random...

I also tried to understand the KeyRange, but got nothing out of it.

Some help?


问:
How to get all Connected Clients of Redis Cluster?
How to get all connected clients of a redis cluster?
I am using AWS elasticCache redis with non cluster mode and redission as my redis client.
My Use Case:
I need to run specific code from only 1 connected redis client.

Thanks

答:
redis has command about client information like CLIENT LIST, check out this page .

you could checkout this page for the command redisson has not supported yet.


问:
d3js onmouseover highlight not working
I have a table with row and column head texts which have ids like row3, col1, ...

I'm using

```<code>.on("mouseover", highlight)
</code>```

on a rect inside the table, and the function looks like this:

```<code>function highlight(d){

  var txt = d3.select("#col"+d3.select(this).attr("colNr"));
  txt.style('fill', 'darkOrange');
}
</code>```

The "#col"+d3.select(this).attr("colNr") gives me the correct "col2" (saw it in the debugger + alert). But it seems like

```<code>d3.select("col2").style('fill', 'darkOrange');
</code>```

is not changing anything for me...
Does anybody know whats wrong here?

EDIT:
Sorry wasn't possible to solve this without the rest of the code:
With trial and error I reduced the possible failure-sources and its something different then I thought. I think I've got a problem with the scope(?),reduced my example, it still hast the failure but here is the complete relevant javascript code:

```<code><script>
var links;

var svgContainer = d3.select("div#container")
//.call(zm = d3.behavior.zoom().scaleExtent([0.1,3]).on("zoom", redraw))
.append("svg").attr("preserveAspectRatio", "xMinYMin meet").attr("viewBox",
        "0 0 1920 1080").classed("svg-container", true);

var g = svgContainer.append("g");

//exchange later with string
d3.json("graph.json", function(error, graph) {
    if (error)
        throw error;

    links = graph.links;

    addRects();
});

alert(links.length);

//end exchange
function addRects(){

    g.append("rect")
        .attr("x", 100)
        .attr("y", 100)
        .attr("width", 120)
        .attr("height", 80)
        .attr("fill", "#eeeeee")
        .attr("id","this1");

    g.append("rect")
        .attr("x", 300)
        .attr("y", 100)
        .attr("width", 120)
        .attr("height", 80)
        .attr("fill", "#eeeeee")
        .attr("id","this2");
}

d3.select("#this2").style("fill","#ff0000");
</code>```

If I copy d3.select("#this2").style("fill","#ff0000"); inside the inner function (@the json part) it works. But not when its outside. I'm still struggling with this type of inner function (this is a closure, right?). I know it has its parents functions scope. But I thought for example by declaring var links; at the top(global var?) it has the links in the alert but I get "links is undefined" ... so the inner functions links is a different var?

答:
d3.select Selects the first element that matches the specified selector string.
It expects an element type or an identifier.

So presumably you need -

```<code>d3.select("#col2").style('fill', 'darkOrange');
</code>```

Notice the # pound sign that marks the string as an identifier.

Without it the select function is looking for an element called col2 - <col2></col2> - rather than an element with the id col2 - <x id='col2'></x> (where x is any valid element type).

Title: d3js onmouseover highlight not working

Body:
I have a table with row and column head texts which have ids like row3, col1, ...

I'm using

.on("mouseover", highlight)

on a rect inside the table, and the function looks like this:

function highlight(d){

  var txt = d3.select("#col"+d3.select(this).attr("colNr"));
  txt.style('fill', 'darkOrange');
}

The "#col"+d3.select(this).attr("colNr") gives me the correct "col2" (saw it in the debugger + alert). But it seems like

d3.select("col2").style('fill', 'darkOrange');

is not changing anything for me...
Does anybody know whats wrong here?

EDIT:
Sorry wasn't possible to solve this without the rest of the code:
With trial and error I reduced the possible failure-sources and its something different then I thought. I think I've got a problem with the scope(?),reduced my example, it still hast the failure but here is the complete relevant javascript code:

Body:
d3.select Selects the first element that matches the specified selector string.
It expects an element type or an identifier.

So presumably you need -

d3.select("#col2").style('fill', 'darkOrange');

Notice the # pound sign that marks the string as an identifier.

Without it the select function is looking for an element called col2 - <col2></col2> - rather than an element with the id col2 - <x id='col2'></x> (where x is any valid element type).


问:
Android Experts - Need your help to display Images quickly in low internet areas and low quality phones
We are developing a private social media App for colleges in Android. However, my current Android App rendering speed for images are very slow. It takes approx. 5 seconds for images to appear and in this day and age its criminal.

We have tried different options and our current android developer is not able to solve this. Can anyone suggest alternate options?
Here is what we have done so far.

Few Questions Upfront:
    1. Where are we messing up in the process? Please advise
    2. Is the sizing of thumbnails correct?
    3. Any suggestions for libraries in Java to compress images (lossless) before sending to backend server

Here are the steps that we followed

```<code>1. Compress the image from device before sending to server via API - We are doing this for jpeg only. Need to do this for .PNG
AFAIK, this is the code used. As I am not an Android developer, I am not sure this is complete.

*Bitmap scaledBitmap = ImageCompression.compressImage(1328.0f, 1771.0f, sourceFile.getAbsolutePath());

        FileOutputStream out = new FileOutputStream(destFile);
        if (null != scaledBitmap)
            scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
        return destFile;
public static File getCompressedImage(File srcFile, File destFile) throws FileNotFoundException {
        Bitmap scaledBitmap = ImageCompression.compressImage(1328.0f, 1771.0f, srcFile.getAbsolutePath());
        FileOutputStream out = new FileOutputStream(destFile);
        if (null != scaledBitmap)
            scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
        return destFile;
    }

######### Used this code to do compression - https://gist.github.com/walteranyika/2db99439225a82d2c1497e6ab61a8a3d  #################### ImageCompression.Java ######## Relevant parts are pasted here.
*Canvascanvas=null;
if(scaledBitmap!=null){
canvas=newCanvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp,middleX-bmp.getWidth()/2,middleY-bmp.getHeight()/2,newPaint(Paint.FILTER_BITMAP_FLAG));
}**

2. Server is creating thumbnails using thumbnilator
    a. We are creating 4 sized thumbnails for 4 phone sizes with size less than 100 KB by reducing quality
        i. All Portrait images and all width * height and in DP
        ii. Small - 150 * 150
        iii. Medium - 200 * 200
        iv. Large - 210 * 420
        v. X-Large - 500 * 640
3. Enabled BucketAccelerateConfiguration in AWS
4. Thumbnails along with original image is sent to target device from server via API
5. Using a combination of Glide and Picasso libraries to display thumbnails and original image in the backend
    a. If thumbnails are empty, we are displaying original URL
    b. If the thumbnails are available, we are displaying Thumbnail till original image is displayed

*if(TextUtils.isEmpty(thumbUrl)){
    GlideApp.with(getContext())
    .load(imageUrl)
    .placeholder(R.drawable.image_placeholder)
    .diskCacheStrategy(DiskCacheStrategy.DATA)
    .dontAnimate()
    .dontTransform()
    .into(imageView);
}else{
Picasso.with(context.getApplicationContext())
    .load(thumbUrl)//thumbnailurlgoeshere
    .placeholder(R.drawable.image_placeholder)
    .resize(AppConstants.IMAGE_SIZE,AppConstants.IMAGE_HEIGHT)
    .transform(HomeActivity.blurTransformation)
    .into(imageView,newCallback(){
    @Override
publicvoidonSuccess(){
    Picasso.with(context.getApplicationContext())
    .load(imageUrl)//imageurlgoeshere
    .placeholder(imageView.getDrawable())
    .into(imageView);
    }
@Override
publicvoidonError(){
    GlideApp.with(getContext())
    .load(imageUrl)
    .placeholder(R.drawable.image_placeholder)
    .diskCacheStrategy(DiskCacheStrategy.DATA)
    .dontAnimate()
    .dontTransform()
    .into(imageView);
    }
    });
}
}*
</code>```

答:
Try to use Androids ThumbnailUtils and generate as per your requirement thumbnail of the selected image and than convert it to bitmap and set.

It works faster.

You can get all the information about ThumbnailUtils here,
https://developer.android.com/reference/android/media/ThumbnailUtils.html

Body:
We are developing a private social media App for colleges in Android. However, my current Android App rendering speed for images are very slow. It takes approx. 5 seconds for images to appear and in this day and age its criminal.

We have tried different options and our current android developer is not able to solve this. Can anyone suggest alternate options?
Here is what we have done so far.

Few Questions Upfront:
    1. Where are we messing up in the process? Please advise
    2. Is the sizing of thumbnails correct?
    3. Any suggestions for libraries in Java to compress images (lossless) before sending to backend server

Here are the steps that we followed

1. Compress the image from device before sending to server via API - We are doing this for jpeg only. Need to do this for .PNG
AFAIK, this is the code used. As I am not an Android developer, I am not sure this is complete.

*Bitmap scaledBitmap = ImageCompression.compressImage(1328.0f, 1771.0f, sourceFile.getAbsolutePath());

        FileOutputStream out = new FileOutputStream(destFile);
        if (null != scaledBitmap)
            scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
        return destFile;
public static File getCompressedImage(File srcFile, File destFile) throws FileNotFoundException {
        Bitmap scaledBitmap = ImageCompression.compressImage(1328.0f, 1771.0f, srcFile.getAbsolutePath());
        FileOutputStream out = new FileOutputStream(destFile);
        if (null != scaledBitmap)
            scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
        return destFile;
    }

######### Used this code to do compression - https://gist.github.com/walteranyika/2db99439225a82d2c1497e6ab61a8a3d  #################### ImageCompression.Java ######## Relevant parts are pasted here.
*Canvascanvas=null;
if(scaledBitmap!=null){
canvas=newCanvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp,middleX-bmp.getWidth()/2,middleY-bmp.getHeight()/2,newPaint(Paint.FILTER_BITMAP_FLAG));
}**

2. Server is creating thumbnails using thumbnilator
    a. We are creating 4 sized thumbnails for 4 phone sizes with size less than 100 KB by reducing quality
        i. All Portrait images and all width * height and in DP
        ii. Small - 150 * 150
        iii. Medium - 200 * 200
        iv. Large - 210 * 420
        v. X-Large - 500 * 640
3. Enabled BucketAccelerateConfiguration in AWS
4. Thumbnails along with original image is sent to target device from server via API
5. Using a combination of Glide and Picasso libraries to display thumbnails and original image in the backend
    a. If thumbnails are empty, we are displaying original URL
    b. If the thumbnails are available, we are displaying Thumbnail till original image is displayed

*if(TextUtils.isEmpty(thumbUrl)){
    GlideApp.with(getContext())
    .load(imageUrl)
    .placeholder(R.drawable.image_placeholder)
    .diskCacheStrategy(DiskCacheStrategy.DATA)
    .dontAnimate()
    .dontTransform()
    .into(imageView);
}else{
Picasso.with(context.getApplicationContext())
    .load(thumbUrl)//thumbnailurlgoeshere
    .placeholder(R.drawable.image_placeholder)
    .resize(AppConstants.IMAGE_SIZE,AppConstants.IMAGE_HEIGHT)
    .transform(HomeActivity.blurTransformation)
    .into(imageView,newCallback(){
    @Override
publicvoidonSuccess(){
    Picasso.with(context.getApplicationContext())
    .load(imageUrl)//imageurlgoeshere
    .placeholder(imageView.getDrawable())
    .into(imageView);
    }
@Override
publicvoidonError(){
    GlideApp.with(getContext())
    .load(imageUrl)
    .placeholder(R.drawable.image_placeholder)
    .diskCacheStrategy(DiskCacheStrategy.DATA)
    .dontAnimate()
    .dontTransform()
    .into(imageView);
    }
    });
}
}*


问:
How do I read a random line from one file?
Is there a built-in method to do it? If not how can I do this without costing too much overhead?</p>

答:
This may be bulky, but it works I guess? (at least for txt files)

```<code>import random
choicefile=open("yourfile.txt","r")
linelist=[]
for line in choicefile:
    linelist.append(line)
choice=random.choice(linelist)
print(choice)
</code>```

It reads each line of a file, and appends it to a list. It then chooses a random line from the list.
If you want to remove the line once it's chosen, just do

```<code>linelist.remove(choice)
</code>```

Hope this may help, but at least no extra modules and imports (apart from random) and relatively lightweight.

ContentLicense: CC BY-SA 4.0

Body:
This may be bulky, but it works I guess? (at least for txt files)

import random
choicefile=open("yourfile.txt","r")
linelist=[]
for line in choicefile:
    linelist.append(line)
choice=random.choice(linelist)
print(choice)

It reads each line of a file, and appends it to a list. It then chooses a random line from the list.
If you want to remove the line once it's chosen, just do

linelist.remove(choice)

Hope this may help, but at least no extra modules and imports (apart from random) and relatively lightweight.


问:
How to rotate file pdf and all image kinds
I have a html page that display PDF and all kinds image.
I'm looking for a way to rotate the file that i display with jQuery.

I tried:

add css class - not working.

Example of the code:

```<code>.rotate90 {
    webkit-transform: rotate(90deg);
    moz-transform: rotate(90deg);
    o-transform: rotate(90deg);
    ms-transform: rotate(90deg);
    transform: rotate(90deg); }

$("buttonId").click(function(){
    $( "objectPdfId" ).addClass( "rotate90" );
});
</code>```

I'm pretty sure it's not the right way

function in JavaScript - not working.

Code:

```<code>    var html = '<object id="objectPdfId" data="' + pathFile + '" type="application/pdf" on click="+rotateMe(this)+"'><embed id="embedPdfId" src="' + pathFile + '" type="application/pdf"></embed></object>';
    $("body").append($(html));

var rotate_factor = 0;

function rotateMe(e) {
    rotate_factor += 1;
    var rotate_angle = (180 * rotate_factor) % 360;
    $(e).rotate({angle:rotate_angle});
}
</code>```

Thanks,

Tal

答:
try to add class on    you object container</p>

```<code><div class=" rotate90">
<object  >
 </object>
 </div>
</code>```

Body:
I have a html page that display PDF and all kinds image.
I'm looking for a way to rotate the file that i display with jQuery.

I tried:

add css class - not working.

Example of the code:

.rotate90 {
    webkit-transform: rotate(90deg);
    moz-transform: rotate(90deg);
    o-transform: rotate(90deg);
    ms-transform: rotate(90deg);
    transform: rotate(90deg); }

$("buttonId").click(function(){
    $( "objectPdfId" ).addClass( "rotate90" );
});

I'm pretty sure it's not the right way

function in JavaScript - not working.

Code:

    var html = '<object id="objectPdfId" data="' + pathFile + '" type="application/pdf" on click="+rotateMe(this)+"'><embed id="embedPdfId" src="' + pathFile + '" type="application/pdf"></embed></object>';
    $("body").append($(html));

var rotate_factor = 0;

function rotateMe(e) {
    rotate_factor += 1;
    var rotate_angle = (180 * rotate_factor) % 360;
    $(e).rotate({angle:rotate_angle});
}

Thanks,

Tal

Body:
try to add class on    you object container

<div class=" rotate90">
<object  >
 </object>
 </div>


问:
Docker and Angular CLI app
I'm trying to use Docker to containerize an app built using the Angular CLI. It's just the default files that come when you use ng new so that I can learn how to do this. I'm trying to use a two-step build, where the first step runs ng-build --prod --build-optimizer, and then the result of that in the ./dist folder is put into a container with Nginx that serves the app. I know that if I manually build the app from my command line, then run a Dockerfile with only the second step that I can get the Angular app to be served, but I'd like Docker to do that for me.

Here's my Dockerfile:

```<code>FROM node:8.9-alpine as angular-built
COPY package.json package.json
RUN npm install
COPY . .
RUN ng build --prod --build-optimizer

FROM nginx:alpine
LABEL author="Preston Lamb"
COPY --from=angular-built ./dist /usr/share/nginx/html
EXPOSE 80 443
ENTRYPOINT [ "nginx", "-g", "daemon off;" ]
</code>```

I've tried using the node:8.9-alpine base image as well as the johnpapa/angular-cli base image on the first step of the Dockerfile. Everything works until the RUN ng build --prod --build-optimizer command, at which point it fails with this error:

Cannot read property 'config' of null
      TypeError: Cannot read property 'config' of null
          at Class.run (/node_modules/@angular/cli/tasks/build.js:15:56)
          at Class.run (/node_modules/@angular/cli/commands/build.js:216:26)
          at resolve (/node_modules/@angular/cli/ember-cli/lib/models/command.js:261:20)
          at new Promise ()
          at Class.validateAndRun (/node_modules/@angular/cli/ember-cli/lib/models/command.js:240:12)
          at Promise.resolve.then.then (/node_modules/@angular/cli/ember-cli/lib/cli/cli.js:140:24)
          at

After googling that, I found that it's because the CLI can't find the .angular-cli.json file. Then I read that by default, Linux doesn't copy hidden files, so it doesn't copy the .angular-cli.json file, and that's where the error comes up.

My next step was trying to force that file to be copied. I tried both of the following, putting this step right before the COPY . . command:

```<code>COPY .angular-cli.json .angular-cli.json
</code>```

and

```<code>RUN shopt -s dotglob
</code>```

The first one doesn't seem to do anything; I got the same error as before. The second one produces a different error:

```<code>/bin/sh: shopt: not found
</code>```

So the command I found to run to tell Linux to copy the hidden files as well doesn't work. I saw one question that was different than this but related say to change the shopt call a little to the following:

```<code>RUN /bin/sh -c "shopt -s dotglob"
</code>```

But that didn't do anything. I got the same not found error.

So I'm not sure where to go from here. any help would be greatly appreciated.

答:
If you use a node alpine image to build your angular app, you need to install the angular cli. Notice the npm i -g @angular/cli in the Dockerfile below. I also added a working directory to the first build stage.

Then you can run the docker compose commands (or docker build and docker run) for an out of the box angular cli app to run on nginx

Dockerfile

```<code>FROM node:8.9-alpine as angular-built
WORKDIR /usr/src/app
RUN npm i -g @angular/cli
COPY package.json package.json
RUN npm install --silent
COPY . .
RUN ng build --prod

FROM nginx:alpine
LABEL author="John Papa"
COPY --from=angular-built /usr/src/app/dist /usr/share/nginx/html
EXPOSE 80 443
CMD [ "nginx", "-g", "daemon off;" ]
</code>```

docker-compose.debug.yml

```<code>version: '2.1'

services:
  clean:
    image: clean
    build: .
    environment:
      NODE_ENV: development
    ports:
      - 80:80
      - 443:443
      - 9229:9229
    ## set your startup file here
    command: [nginx-debug, '-g', 'daemon off;']
</code>```

If you want to use an image based on alpine node 8.9 with the angular cli 1.5.5 already baked in, use this:

Dockerfile

```<code>FROM johnpapa/angular-cli as angular-built
WORKDIR /usr/src/app
COPY package.json package.json
RUN npm install --silent
COPY . .
RUN ng build --prod

FROM nginx:alpine
LABEL author="John Papa"
COPY --from=angular-built /usr/src/app/dist /usr/share/nginx/html
EXPOSE 80 443
CMD [ "nginx", "-g", "daemon off;" ]
</code>```

BTW - the 1.5 version of the CLI has the --build-optimizer baked in, so it is not needed there

Title: Docker and Angular CLI app

Body:
I'm trying to use Docker to containerize an app built using the Angular CLI. It's just the default files that come when you use ng new so that I can learn how to do this. I'm trying to use a two-step build, where the first step runs ng-build --prod --build-optimizer, and then the result of that in the ./dist folder is put into a container with Nginx that serves the app. I know that if I manually build the app from my command line, then run a Dockerfile with only the second step that I can get the Angular app to be served, but I'd like Docker to do that for me.

Here's my Dockerfile:

FROM node:8.9-alpine as angular-built
COPY package.json package.json
RUN npm install
COPY . .
RUN ng build --prod --build-optimizer

FROM nginx:alpine
LABEL author="Preston Lamb"
COPY --from=angular-built ./dist /usr/share/nginx/html
EXPOSE 80 443
ENTRYPOINT [ "nginx", "-g", "daemon off;" ]

I've tried using the node:8.9-alpine base image as well as the johnpapa/angular-cli base image on the first step of the Dockerfile. Everything works until the RUN ng build --prod --build-optimizer command, at which point it fails with this error:

Cannot read property 'config' of null
      TypeError: Cannot read property 'config' of null
          at Class.run (/node_modules/@angular/cli/tasks/build.js:15:56)
          at Class.run (/node_modules/@angular/cli/commands/build.js:216:26)
          at resolve (/node_modules/@angular/cli/ember-cli/lib/models/command.js:261:20)
          at new Promise ()
          at Class.validateAndRun (/node_modules/@angular/cli/ember-cli/lib/models/command.js:240:12)
          at Promise.resolve.then.then (/node_modules/@angular/cli/ember-cli/lib/cli/cli.js:140:24)
          at

After googling that, I found that it's because the CLI can't find the .angular-cli.json file. Then I read that by default, Linux doesn't copy hidden files, so it doesn't copy the .angular-cli.json file, and that's where the error comes up.

My next step was trying to force that file to be copied. I tried both of the following, putting this step right before the COPY . . command:

COPY .angular-cli.json .angular-cli.json

and

RUN shopt -s dotglob

The first one doesn't seem to do anything; I got the same error as before. The second one produces a different error:

/bin/sh: shopt: not found

So the command I found to run to tell Linux to copy the hidden files as well doesn't work. I saw one question that was different than this but related say to change the shopt call a little to the following:

RUN /bin/sh -c "shopt -s dotglob"

But that didn't do anything. I got the same not found error.

So I'm not sure where to go from here. any help would be greatly appreciated.

Body:
If you use a node alpine image to build your angular app, you need to install the angular cli. Notice the npm i -g @angular/cli in the Dockerfile below. I also added a working directory to the first build stage.

Then you can run the docker compose commands (or docker build and docker run) for an out of the box angular cli app to run on nginx

Dockerfile

FROM node:8.9-alpine as angular-built
WORKDIR /usr/src/app
RUN npm i -g @angular/cli
COPY package.json package.json
RUN npm install --silent
COPY . .
RUN ng build --prod

FROM nginx:alpine
LABEL author="John Papa"
COPY --from=angular-built /usr/src/app/dist /usr/share/nginx/html
EXPOSE 80 443
CMD [ "nginx", "-g", "daemon off;" ]

docker-compose.debug.yml

version: '2.1'

services:
  clean:
    image: clean
    build: .
    environment:
      NODE_ENV: development
    ports:
      - 80:80
      - 443:443
      - 9229:9229
    ## set your startup file here
    command: [nginx-debug, '-g', 'daemon off;']

If you want to use an image based on alpine node 8.9 with the angular cli 1.5.5 already baked in, use this:

Dockerfile

FROM johnpapa/angular-cli as angular-built
WORKDIR /usr/src/app
COPY package.json package.json
RUN npm install --silent
COPY . .
RUN ng build --prod

FROM nginx:alpine
LABEL author="John Papa"
COPY --from=angular-built /usr/src/app/dist /usr/share/nginx/html
EXPOSE 80 443
CMD [ "nginx", "-g", "daemon off;" ]

BTW - the 1.5 version of the CLI has the --build-optimizer baked in, so it is not needed there


问:
Iterating through all the subfolders of a folder in iphone
IS there any efficient way to iterate through all the subfolders I've created inside my iphone App's Documents folder ? (Of course, without knowing their names or how many there are...)

Thanks...
Guy.

答: See the documentation for -[NSFileManager enumeratorAtPath:]. It contains sample code that does what you want.


问:
How to get url just clicked before confirm popup comes in angular 4
I am new to angular 4. I have multiple tabs in one page, when I switch from one tab to another or to other nav bar, my requirement is to provide a popup dialog which asked "are you sure to move ?" and when I pressed ok , it should go to desired tab/nav (last clicked url) otherwise it should remain at the same page.

I have used  CanDeactivateGuard , to popup the dialog before i leave the tab/switch to other nav bar { path: 'exception/:id', component: LpExceptionComponent , canDeactivate: [CanDeactivateGuard]}

Now I am not sure how to redirect to desired tab on pressing ok button?
how I will get the last clicked url here?

答:
You probably don't even need to know the url. You can just return a promise from the canDeactivate function, and once the user clicks ok, you resolve the promise to true and the transition continues automatically. Observables are also supported if you prefer that over promises.

But if you do need to know the state that the user is trying to go to, then it's provided as the fourth parameter to the canDeactivate function (the first three parameters being component, currentRoute, and currentState)

See documentation here: https://angular.io/api/router/CanDeactivate


问:
filter NSArray by properties in Objective-C
I have an array of objects (Person) with type described as follow:

```<code>@inteface Person : NSObject

@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSNumber *age;

@end
</code>```

Is there any fast way to convert the list of Person to list of names and list of ages ?

Or better question is how to filter an array by a property of its objects?

```<code>NSArray <Person*> *list = ; //- initiate a list of people here...
NSArray <NSString*> *names;
NSArray <NSNumber*> *ages;
</code>```

答:
You can use valueForKey:

```<code>NSArray *names = [persons valueForKey:@"name"];
NSArray *ages = [persons valueForKey:@"age"];
</code>```

Body:
I have an array of objects (Person) with type described as follow:

@inteface Person : NSObject

@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSNumber *age;

@end

Is there any fast way to convert the list of Person to list of names and list of ages ?

Or better question is how to filter an array by a property of its objects?

NSArray <Person*> *list = ; //- initiate a list of people here...
NSArray <NSString*> *names;
NSArray <NSNumber*> *ages;

Body:
You can use valueForKey:

NSArray *names = [persons valueForKey:@"name"];
NSArray *ages = [persons valueForKey:@"age"];


问:
Source maps in webpack + closure compiler
I would like to use SourceMaps generated by Closure Compiler using Webpack but I cant figure out how to do it.

Here is my webpack config:

```<code>const ClosureCompiler = require('google-closure-compiler-js').webpack;

module.exports = {
    devtool: 'source-map',
    entry: './src/app.js',
    output: {
        path: __dirname + "/build/",
        filename: "bundle.js",
        //sourceMapFilename: "./app.js.map",
    },
    plugins: [
        new ClosureCompiler({
            compiler: {
                language_in: 'ECMASCRIPT5',
                language_out: 'ECMASCRIPT5',
                compilation_level: 'ADVANCED',
                create_source_map: __dirname + './output.js.map'
            },
            concurrency: 3,
        })
    ]
};
</code>```

When I run webpack, nothing happen. Why? What am I doing wrong?
Thank you for your help.

答:
Using the latest version of google-closure-compiler-js (20170910.0.1), I was able to get it to work using the following options:

```<code>plugins: [
  new ClosureCompiler({
    options: {
      languageIn: 'ECMASCRIPT6',
      languageOut: 'ECMASCRIPT5',
      compilationLevel: 'ADVANCED',
      createSourceMap: true
    }
  })
]
</code>```

Body:
I would like to use SourceMaps generated by Closure Compiler using Webpack but I cant figure out how to do it.

Here is my webpack config:

const ClosureCompiler = require('google-closure-compiler-js').webpack;

module.exports = {
    devtool: 'source-map',
    entry: './src/app.js',
    output: {
        path: __dirname + "/build/",
        filename: "bundle.js",
        //sourceMapFilename: "./app.js.map",
    },
    plugins: [
        new ClosureCompiler({
            compiler: {
                language_in: 'ECMASCRIPT5',
                language_out: 'ECMASCRIPT5',
                compilation_level: 'ADVANCED',
                create_source_map: __dirname + './output.js.map'
            },
            concurrency: 3,
        })
    ]
};

When I run webpack, nothing happen. Why? What am I doing wrong?
Thank you for your help.

Body:
Using the latest version of google-closure-compiler-js (20170910.0.1), I was able to get it to work using the following options:

plugins: [
  new ClosureCompiler({
    options: {
      languageIn: 'ECMASCRIPT6',
      languageOut: 'ECMASCRIPT5',
      compilationLevel: 'ADVANCED',
      createSourceMap: true
    }
  })
]


问:
Rails ActiveRecord summary statement
How to translate this simple query to ruby on rails ActiveRecord

select sum(current*progress) from features;

i have tried

```<code> @feature = Feature.where(project_detail_id: @project_detail.id )
 @current_progress =  @feature.current * @feature.progress
 @total_current_progress =  @feature.sum(@current_progress)
</code>```

but nothing works
i cannot get @total_current_progress result

thanks in advance

答:
```<code>Feature.sum("current * progress")

(0.7ms)  SELECT SUM(current * progress) FROM "features"
</code>```

Title: Rails ActiveRecord summary statement

Body:
How to translate this simple query to ruby on rails ActiveRecord

select sum(current*progress) from features;

i have tried

 @feature = Feature.where(project_detail_id: @project_detail.id )
 @current_progress =  @feature.current * @feature.progress
 @total_current_progress =  @feature.sum(@current_progress)

but nothing works
i cannot get @total_current_progress result

thanks in advance


问:
Linux command: How to 'find' only text files?
After a few searches from Google, what I come up with is:

```<code>find my_folder -type f -exec grep -l "needle text" {} \; -exec file {} \; | grep text
</code>```

which is very unhandy and outputs unneeded texts such as mime type information. Any better solutions? I have lots of images and other binary files in the same folder with a lot of text files that I need to search through.

答:
```<code>find . -type f -print0 | xargs -0 file | grep -P text | cut -d: -f1 | xargs grep -Pil "search"
</code>```

This is unfortunately not space save. Putting this into bash script makes it a bit easier.

This is space safe:

```<code>#!/bin/bash
#if [ ! "$1" ] ; then
    echo "Usage: $0 <search>";
    exit
fi

find . -type f -print0 \
  | xargs -0 file \
  | grep -P text \
  | cut -d: -f1 \
  | xargs -i% grep -Pil "$1" "%"
</code>```

Body:
After a few searches from Google, what I come up with is:

find my_folder -type f -exec grep -l "needle text" {} \; -exec file {} \; | grep text

which is very unhandy and outputs unneeded texts such as mime type information. Any better solutions? I have lots of images and other binary files in the same folder with a lot of text files that I need to search through.

Body:
find . -type f -print0 | xargs -0 file | grep -P text | cut -d: -f1 | xargs grep -Pil "search"

This is unfortunately not space save. Putting this into bash script makes it a bit easier.

This is space safe:

#!/bin/bash
#if [ ! "$1" ] ; then
    echo "Usage: $0 <search>";
    exit
fi

find . -type f -print0 \
  | xargs -0 file \
  | grep -P text \
  | cut -d: -f1 \
  | xargs -i% grep -Pil "$1" "%"


问:
UINavigationController Subview not Scrolling
I am having a navigation controller and a view, which i attached to the subview of navigation controller, i used the below code to hide the navigation bar while swiping up

```<code>    [self.navigationController.view addSubview: categoryView];
    self.navigationController.hidesBarsOnSwipe = YES;
</code>```

it is hiding to the top while swiping the tableview up, but i want that subview should move up along with the navigation controller and it should fit at the top, while swiping down navigation bar should come down along with the subview.

I tried this

[self.navigationController.navigationBar addSubview: categoryView];

In this both navigationBar and the subview is hiding to the top. I guess some simple solutions will be there for this, I searched a lot but didn't find a perfect one. I tried some libraries too, those are not fitting for iPhone X and having some issues in iOS 11.

Update:  adding images for the issue before scrolling
and
after scrolling the tableview

答:
EDITED:

You can add subview to your view with constraints to safe area.

F.e. programmatically:

```<code>self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
if (@available(iOS 11.0, *)) {
    self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    UILayoutGuide *guide = self.view.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
                                              [self.headerView.topAnchor constraintEqualToAnchor:self.view.topAnchor constant:0],
                                              [self.headerView.bottomAnchor constraintEqualToAnchor:guide.topAnchor constant:64],
                                              [self.headerView.leftAnchor constraintEqualToAnchor:self.view.leftAnchor constant:0],
                                              [self.headerView.rightAnchor constraintEqualToAnchor:self.view.rightAnchor constant:0]
                                              ]];
    [NSLayoutConstraint activateConstraints:@[
                                              [self.tableView.topAnchor constraintEqualToAnchor:self.headerView.bottomAnchor constant:0],
                                              [self.tableView.leftAnchor constraintEqualToAnchor:self.view.leftAnchor constant:0],
                                              [self.tableView.rightAnchor constraintEqualToAnchor:self.view.rightAnchor constant:0],
                                              [self.tableView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor constant:0]
                                              ]];

}
</code>```

To show/hide navbar on scroll you may use:

```<code>if (scrollView.contentOffset.y <= 0) {
    [self.navigationController setNavigationBarHidden:NO animated: YES];
} else {
    [self.navigationController setNavigationBarHidden:YES animated: YES];
}
[UIView animateWithDuration:[CATransaction animationDuration]
                 animations:^{
                     [self.view layoutIfNeeded];
                 }];
</code>```

Updated example: https://github.com/josshad/HideNavBarOnScrollExample

Body:
I am having a navigation controller and a view, which i attached to the subview of navigation controller, i used the below code to hide the navigation bar while swiping up

    [self.navigationController.view addSubview: categoryView];
    self.navigationController.hidesBarsOnSwipe = YES;

it is hiding to the top while swiping the tableview up, but i want that subview should move up along with the navigation controller and it should fit at the top, while swiping down navigation bar should come down along with the subview.

I tried this

[self.navigationController.navigationBar addSubview: categoryView];

In this both navigationBar and the subview is hiding to the top. I guess some simple solutions will be there for this, I searched a lot but didn't find a perfect one. I tried some libraries too, those are not fitting for iPhone X and having some issues in iOS 11.

Update:  adding images for the issue before scrolling
and
after scrolling the tableview

Body:
EDITED:

You can add subview to your view with constraints to safe area.

F.e. programmatically:

self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
if (@available(iOS 11.0, *)) {
    self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    UILayoutGuide *guide = self.view.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
                                              [self.headerView.topAnchor constraintEqualToAnchor:self.view.topAnchor constant:0],
                                              [self.headerView.bottomAnchor constraintEqualToAnchor:guide.topAnchor constant:64],
                                              [self.headerView.leftAnchor constraintEqualToAnchor:self.view.leftAnchor constant:0],
                                              [self.headerView.rightAnchor constraintEqualToAnchor:self.view.rightAnchor constant:0]
                                              ]];
    [NSLayoutConstraint activateConstraints:@[
                                              [self.tableView.topAnchor constraintEqualToAnchor:self.headerView.bottomAnchor constant:0],
                                              [self.tableView.leftAnchor constraintEqualToAnchor:self.view.leftAnchor constant:0],
                                              [self.tableView.rightAnchor constraintEqualToAnchor:self.view.rightAnchor constant:0],
                                              [self.tableView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor constant:0]
                                              ]];

}

To show/hide navbar on scroll you may use:

if (scrollView.contentOffset.y <= 0) {
    [self.navigationController setNavigationBarHidden:NO animated: YES];
} else {
    [self.navigationController setNavigationBarHidden:YES animated: YES];
}
[UIView animateWithDuration:[CATransaction animationDuration]
                 animations:^{
                     [self.view layoutIfNeeded];
                 }];

Updated example: https://github.com/josshad/HideNavBarOnScrollExample


问:
Excel VBA "Subscript out of range" Run Error '9'
I have tried to implement the following code so that I can read a cell value and then places this value into another cell on the same Worksheet.

The worksheet has the following name: TestUserGuidance (Has no spaces)
The code is as follows:

```<code>Sub GuideTest()
    Dim dblPower, dblMass, dblRatedSpeed, dblRefLength, dblAwot, dblEngineSpeed, dblRoadSpeed As Double
    Dim dblPMR As Double

    dblPower = Worksheets("TestUserGuidance").Cell("B1").Value
    Worksheets("TestUserGuidance").Cell("E1") = dblPower
End Sub
</code>```

Could anyone please advise where I'm going wrong?

Thanks

答:
This is the way to make your code working:

```<code>Sub GuideTest()
    Dim dblPower, dblEngineSpeed, dblRoadSpeed As Double ' first two are of variant type
    Dim dblPMR As Double

    dblPower = Worksheets(1).Range("B1").Value
    Worksheets(1).Range("E1") = dblPower
End Sub
</code>```

When you use "E1" or "B1" you should use Range, not Cells. In my answer Worksheets(1) refers to Worksheets("TestUserGuidance").

Body:
I have tried to implement the following code so that I can read a cell value and then places this value into another cell on the same Worksheet.

The worksheet has the following name: TestUserGuidance (Has no spaces)
The code is as follows:

Sub GuideTest()
    Dim dblPower, dblMass, dblRatedSpeed, dblRefLength, dblAwot, dblEngineSpeed, dblRoadSpeed As Double
    Dim dblPMR As Double

    dblPower = Worksheets("TestUserGuidance").Cell("B1").Value
    Worksheets("TestUserGuidance").Cell("E1") = dblPower
End Sub

Could anyone please advise where I'm going wrong?

Thanks

Body:
This is the way to make your code working:

Sub GuideTest()
    Dim dblPower, dblEngineSpeed, dblRoadSpeed As Double ' first two are of variant type
    Dim dblPMR As Double

    dblPower = Worksheets(1).Range("B1").Value
    Worksheets(1).Range("E1") = dblPower
End Sub

When you use "E1" or "B1" you should use Range, not Cells. In my answer Worksheets(1) refers to Worksheets("TestUserGuidance").


问:
How to move files and make directory simultaniously and paste in that new folder using one command in BASH
How to move files and make directory simultaniously and paste in that new folder using one command in BASH
I am trying to do this by using this command but its not working:

```<code>cp *.docx /home/ahmed/my-files/first-semester | mkdir islamiyat
</code>```

image description here

答:
```<code>mkdir -p dirxyz && mv *.docx ./dirxyz
</code>```

Body:
How to move files and make directory simultaniously and paste in that new folder using one command in BASH
I am trying to do this by using this command but its not working:

cp *.docx /home/ahmed/my-files/first-semester | mkdir islamiyat

image description here

Body: mkdir -p dirxyz && mv *.docx ./dirxyz


问:
How to write property values of different languages in its native form to a properties file in java by saving the file layout?
I have a localized properties file with a list of key-value pairs.
I want to write property values in japanese,chinese,german etc. to the file and also want to save the already existing file layout with comments and spaces. Need to write these languages in its own native form.

I tried to add a new property ("key = アカウント ナビゲーション コンポーネント") to the existing property file using PropertiesConfigurationLayout. It is possible to add new property in its native form and PropertiesConfigurationLayout helped to save the layout of the file. But the existing keys format will get changed to unicode format.
Useful link : (http://marjavamitjava.com/modifying-property-file-maintaining-order-well-comments/)

This is the code I tried.

Code:

```<code>    File file = new File("base_ch.properties");

    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setEncoding("UTF-8");
    PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
    Properties props = new Properties();

    try(InputStreamReader in = new InputStreamReader(new FileInputStream(file), "UTF-8"))
    {
        layout.load(in);
        OutputStreamWriter out =new OutputStreamWriter(new FileOutputStream(file), "UTF-8");

        props.put("key","アカウント ナビゲーション コンポーネント");
        layout.save(out);
        props.store(out, null);
    }
    catch (ConfigurationException | IOException e) {
        e.printStackTrace();
    }
</code>```

base_ch.properties file content before code runs:

```<code># -----------------------------------------------------------------------
#  All rights reserved.
#  Comments included here
# -----------------------------------------------------------------------
#Tue May 22 13:41:37

account.quote.expiration.time.label = Gültig bis
address.zipcode = 邮政编码:
</code>```

base_ch.properties file content after code runs:

```<code># -----------------------------------------------------------------------
#  All rights reserved.
#  Comments included here
# -----------------------------------------------------------------------
#Tue May 22 13:41:37

account.quote.expiration.time.label = G\u00FCltig bis
address.zipcode = \u90AE\u653F\u7F16\u7801
#Wed Dec 06 17:40:04 IST 2017
key=アカウント ナビゲーション コンポーネント
</code>```

I want to save the file layout without any change and should retain the existing properties in its native form.
It is able to write various languages to the properties file using various classes, but the file layout will get change in that cases.
PropertiesConfigurationLayout is the only way I found to save the layout.

Can anyone help me?

答:
If its only about adding properties to existing file then you can just add it:</p>

```<code>    Properties props = new Properties();
    OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("file", true), "UTF-8");
    props.put("key", "アカウント ナビゲーション コンポーネント");
    props.store(out, null);
</code>```

Body:
I have a localized properties file with a list of key-value pairs.
I want to write property values in japanese,chinese,german etc. to the file and also want to save the already existing file layout with comments and spaces. Need to write these languages in its own native form.

I tried to add a new property ("key = アカウント ナビゲーション コンポーネント") to the existing property file using PropertiesConfigurationLayout. It is possible to add new property in its native form and PropertiesConfigurationLayout helped to save the layout of the file. But the existing keys format will get changed to unicode format.
Useful link : (http://marjavamitjava.com/modifying-property-file-maintaining-order-well-comments/)

This is the code I tried.

Code:

    File file = new File("base_ch.properties");

    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setEncoding("UTF-8");
    PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
    Properties props = new Properties();

    try(InputStreamReader in = new InputStreamReader(new FileInputStream(file), "UTF-8"))
    {
        layout.load(in);
        OutputStreamWriter out =new OutputStreamWriter(new FileOutputStream(file), "UTF-8");

        props.put("key","アカウント ナビゲーション コンポーネント");
        layout.save(out);
        props.store(out, null);
    }
    catch (ConfigurationException | IOException e) {
        e.printStackTrace();
    }

base_ch.properties file content before code runs:

# -----------------------------------------------------------------------
#  All rights reserved.
#  Comments included here
# -----------------------------------------------------------------------
#Tue May 22 13:41:37

account.quote.expiration.time.label = Gültig bis
address.zipcode = 邮政编码:

base_ch.properties file content after code runs:

# -----------------------------------------------------------------------
#  All rights reserved.
#  Comments included here
# -----------------------------------------------------------------------
#Tue May 22 13:41:37

account.quote.expiration.time.label = G\u00FCltig bis
address.zipcode = \u90AE\u653F\u7F16\u7801
#Wed Dec 06 17:40:04 IST 2017
key=アカウント ナビゲーション コンポーネント

I want to save the file layout without any change and should retain the existing properties in its native form.
It is able to write various languages to the properties file using various classes, but the file layout will get change in that cases.
PropertiesConfigurationLayout is the only way I found to save the layout.

Can anyone help me?

Body:
If its only about adding properties to existing file then you can just add it:

    Properties props = new Properties();
    OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("file", true), "UTF-8");
    props.put("key", "アカウント ナビゲーション コンポーネント");
    props.store(out, null);


问:
Backup multiple folders with duplicity (including/excluding)
I would like to backup the following folders with duplicity

```<code>/home
/etc
/usr/local
/root
/var
/boot
</code>```

and exclude

```<code>/var/tmp
/var/run
/var/lock
/home/*/.thumbnails
/home/*/.cache
/home/*/.local/share/Trash
/root/.thumbnails
/root/.cache
/root/.local/share/Trash
</code>```

I already learned that I have to specify one source directory to save and that I can adjust that with include and exclude options.

So, I could give / as source directory and exclude ** (which would sum up to nothing) and include the folders that I want to save.

Source / and --exclude / would give en empty set, --include ... beats the exclude and adds the folders. But then, I will not be able to exclude the folders I want to exclude, right? Or am I missing something?

答:
To complete the answer of @Kurtibert, you need to add ** at the end of the directory you include to be sure files inside are included (and don't forgot the quotes):

```<code>--exclude '/var/tmp'
--exclude '/var/run'
--exclude /var/lock'
--exclude '/home/*/.thumbnails'
--exclude '/home/*/.cache'
--exclude '/home/*/.local/share/Trash'
--exclude '/root/.thumbnails'
--exclude '/root/.cache'
--exclude '/root/.local/share/Trash'
--include '/home/**'
--include '/etc/**'
--include '/usr/local/**'
--include '/root/**'
--include '/var/**'
--include '/boot/**'
--exclude '**'
/
</code>```

Body:
I would like to backup the following folders with duplicity

/home
/etc
/usr/local
/root
/var
/boot

and exclude

/var/tmp
/var/run
/var/lock
/home/*/.thumbnails
/home/*/.cache
/home/*/.local/share/Trash
/root/.thumbnails
/root/.cache
/root/.local/share/Trash

I already learned that I have to specify one source directory to save and that I can adjust that with include and exclude options.

So, I could give / as source directory and exclude ** (which would sum up to nothing) and include the folders that I want to save.

Source / and --exclude / would give en empty set, --include ... beats the exclude and adds the folders. But then, I will not be able to exclude the folders I want to exclude, right? Or am I missing something?

Body:
To complete the answer of @Kurtibert, you need to add ** at the end of the directory you include to be sure files inside are included (and don't forgot the quotes):

--exclude '/var/tmp'
--exclude '/var/run'
--exclude /var/lock'
--exclude '/home/*/.thumbnails'
--exclude '/home/*/.cache'
--exclude '/home/*/.local/share/Trash'
--exclude '/root/.thumbnails'
--exclude '/root/.cache'
--exclude '/root/.local/share/Trash'
--include '/home/**'
--include '/etc/**'
--include '/usr/local/**'
--include '/root/**'
--include '/var/**'
--include '/boot/**'
--exclude '**'
/


问:
Scrollbar on Top Side in Horizontal RecyclerView
I am working on the Simple demo of Horizontal RecyclerView.

I want to display scrollbar along with the recyclerview. So I have added android:scrollbars="horizontal" and android:scrollbarSize="5dp" in XML.

I am able to get the Scrollbar but it is showing on the bottom. What I want to achieve is to show it on Top. I have found some questions like this but none of them are for horizontal recyclerView + top side scrollbar.

Here is the code which I have tried so far:

```<code><android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:isScrollContainer="false"
    android:orientation="horizontal"
    android:scrollbars="horizontal"
    android:scrollbarSize="5dp"
    android:visibility="visible" />
</code>```

Thanks!

答:
I have searched couple of hours but not found anything as per your requirement. But there are some trikes or do with some hacky code we can get output as per your requirement.

Set your RecyclerView as below in your xml file.

```<code><android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbarAlwaysDrawHorizontalTrack="true"
        android:scrollbarSize="10dp"
        android:scrollbarStyle="outsideInset"
        android:scrollbarThumbVertical="@color/black"
        android:scrollbars="horizontal"
        android:verticalScrollbarPosition="right"/>
</code>```

Put your data in revers order in your List or ArrayList because we need to rotate the recyclerviews so when we rotate it then our data will be display as an ASEC order.

```<code>   //call this method for set recyclerview
   private void setRecyclerView()
    {
        //Please make sure with your item that it will be inserted in revers order then an then it will be working
        ArrayList<String> itemList = new ArrayList<>();
        for (int i = 50; i > 0; i--){
            itemList.add("item " + i);
        }

        ContainerAdapter adapterMessage = new ContainerAdapter(MainActivity.this, itemList);
        if (adapterMessage != null)
        {
            rvItemList.setHasFixedSize(true);
            rvItemList.setLayoutManager(new LinearLayoutManager(MainActivity.this,
                    LinearLayoutManager.HORIZONTAL, false);
            rvItemList.setItemAnimator(new DefaultItemAnimator());
            rvItemList.setAdapter(adapterMessage);
            //here is the main line for your requirement
            rvItemList.setRotation(180);
            adapterMessage.notifyDataSetChanged();
        }
</code>```

Now last, In your adapter please rotate your all view in revers direction like below.

```<code>public class ViewHolder extends RecyclerView.ViewHolder
    {
        TextView txt_name;
        public ViewHolder(View itemView) {
            super(itemView);
            txt_name = (TextView) itemView.findViewById(R.id.txt_name);
            // here you need to revers rotate your view because your recyclerview is already rotate it so your view is also rotated and you need to revers rotate that view
            txt_name.setRotation(-180);
        }
    }
</code>```

If you do code as above then your item and its output look like this OutPut

Please make sure to doing this kind of code because android will not responsible for this kind of code, but as per your requirement you can do like this.

Body:
I am working on the Simple demo of Horizontal RecyclerView.

I want to display scrollbar along with the recyclerview. So I have added android:scrollbars="horizontal" and android:scrollbarSize="5dp" in XML.

I am able to get the Scrollbar but it is showing on the bottom. What I want to achieve is to show it on Top. I have found some questions like this but none of them are for horizontal recyclerView + top side scrollbar.

Here is the code which I have tried so far:

<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:isScrollContainer="false"
    android:orientation="horizontal"
    android:scrollbars="horizontal"
    android:scrollbarSize="5dp"
    android:visibility="visible" />

Thanks!

Body:
I have searched couple of hours but not found anything as per your requirement. But there are some trikes or do with some hacky code we can get output as per your requirement.

Set your RecyclerView as below in your xml file.

<android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbarAlwaysDrawHorizontalTrack="true"
        android:scrollbarSize="10dp"
        android:scrollbarStyle="outsideInset"
        android:scrollbarThumbVertical="@color/black"
        android:scrollbars="horizontal"
        android:verticalScrollbarPosition="right"/>

Put your data in revers order in your List or ArrayList because we need to rotate the recyclerviews so when we rotate it then our data will be display as an ASEC order.

   //call this method for set recyclerview
   private void setRecyclerView()
    {
        //Please make sure with your item that it will be inserted in revers order then an then it will be working
        ArrayList<String> itemList = new ArrayList<>();
        for (int i = 50; i > 0; i--){
            itemList.add("item " + i);
        }

        ContainerAdapter adapterMessage = new ContainerAdapter(MainActivity.this, itemList);
        if (adapterMessage != null)
        {
            rvItemList.setHasFixedSize(true);
            rvItemList.setLayoutManager(new LinearLayoutManager(MainActivity.this,
                    LinearLayoutManager.HORIZONTAL, false);
            rvItemList.setItemAnimator(new DefaultItemAnimator());
            rvItemList.setAdapter(adapterMessage);
            //here is the main line for your requirement
            rvItemList.setRotation(180);
            adapterMessage.notifyDataSetChanged();
        }

Now last, In your adapter please rotate your all view in revers direction like below.

public class ViewHolder extends RecyclerView.ViewHolder
    {
        TextView txt_name;
        public ViewHolder(View itemView) {
            super(itemView);
            txt_name = (TextView) itemView.findViewById(R.id.txt_name);
            // here you need to revers rotate your view because your recyclerview is already rotate it so your view is also rotated and you need to revers rotate that view
            txt_name.setRotation(-180);
        }
    }

If you do code as above then your item and its output look like this OutPut

Please make sure to doing this kind of code because android will not responsible for this kind of code, but as per your requirement you can do like this.


问:
Microsoft Graph API accessing Excel doc permissions
I am diving into the Microsoft Graph API and want to use its features to interact with an Excel workbook. I intend to create a client side application that interfaces with my API which in turn interfaces with Microsoft Graph API.

I ran into some confusion with the Microsoft Graph permission documentation. When sifting through the Excel API documentation, I saw that in order to Update Range or Get Worksheet (or really any endpoint) I need to have Delegated (work or school account) permission. I then looked at the Graph permission doc mentioned above and it says:

Delegated permissions are used by apps that have a signed-in user present. For these apps either the user or an administrator consents to the permissions that the app requests and the app is delegated permission to act as the signed-in user when making calls to Microsoft Graph. Some delegated permissions can be consented to by non-administrative users, but some higher-privileged permissions require administrator consent.

To me, this reads "a user must login using oauth to interact with a workbook via the API". I'm hoping that is not the case, because I want to have the workbook data publicly available and to have read/write permission. I understand I will have to authenticate some (admin) user within my organization in order to retrieve/update a workbook (via the Graph API) stored in OneDrive, for example, but I just wanted to see the requirements for accessing the workbook.

答:
Looks like you intend to use Excel workbook as a central source data rather than an individual user based store. In that case you can access API without a user sign-in by using application level consent. See here. Client "app" will call into a server (such as nodeJs) and that in-turn will make API calls to Microsoft Graph to interact with Excel workbook. This server-to-Graph call is abstracted from the client app and hence secure. </p>

<p>The downside of this approach is that you'll need server implementation and you can't implement single page application that doesn't require server side implementation. It is not a big hurdle - just takes different set-up. </p>

Body:
Looks like you intend to use Excel workbook as a central source data rather than an individual user based store. In that case you can access API without a user sign-in by using application level consent. See here. Client "app" will call into a server (such as nodeJs) and that in-turn will make API calls to Microsoft Graph to interact with Excel workbook. This server-to-Graph call is abstracted from the client app and hence secure.

The downside of this approach is that you'll need server implementation and you can't implement single page application that doesn't require server side implementation. It is not a big hurdle - just takes different set-up.


问:
Is it possible to show a 'div' content on an image "mouse over" using RJS Template? If so or not, how?
I am using Ruby on Rails 3 and I would like to have an image that responds to a 'mouseover' event to load and show an HTML 'div' content, just how you can see passing the mouse arrow over a tag present in Stackoverflow.com.

I prefer to use the RJS Template, but I don't know if it is possible using this. I will appreciate if you make me a real example including some codes and explanations.

答:
I'd definitely avoid rjs (I never liked it) and go for JS directly:

http://api.jquery.com/mouseenter/

```<code>$('img').mouseenter(function() {
   $('#my_div').append('<div>Some stuff that need to appear</div>');
});
</code>```

cheers.

Body:
I'd definitely avoid rjs (I never liked it) and go for JS directly:

http://api.jquery.com/mouseenter/

$('img').mouseenter(function() {
   $('#my_div').append('<div>Some stuff that need to appear</div>');
});

cheers.