问:
How to return proper error response for content-type text/csv?
I have a servlet where in general I return text/csv as response. So a plain comma separated string.

BUT: in case of exceptions, I'd want to show just some error text as response.  But instead Spring generates a custom ResponseEntity object, then tries to convert this response to csv which obviously fails.

Is it possible to replace the requested format to format=json, and then just return the default Spring error response?

```<code>@RestController
public class CsvServlet {

    @RequestMapping(value = "/test", produces = "text/csv")
    @ResponseBody
    public String errorCsv(HttpServletRequest request) {
        return "some, plain, text";
    }
}
</code>```

Usage: localhost:8080/test?format=csv

When having spring.security.enabled=true, this will first validate the basic auth credentials. If they fail, spring will automatically redirect to /error servlet.

Thereby BasicErrorController.error() method comes in, catching the error and generating a ResponseEntity with error attributes like timestamp, exception, path, etc.

Problem: now an Object of type ResponseEntity is returned. This is fine as long as the format parameter is either ?format=json/xml. As the response can then be properly converted.

But in my special case, where I request ?format=csv, the conversation will fail, leading to:

Response could not be created:
  org.springframework.web.HttpMediaTypeNotAcceptableException: Could not
  find acceptable representation

This is partially true, moreover misleading because the user should directly see that the authentication credentials have been invalid. Because in general I'm accepting csv, but Spring and the mappers don't know how to convert a ResponseEntity to a plain format like csv.

Question: how can I preserve the original exception? So that I could just return a plain text error message. It would also be fine if I could return a application/json response in this case!

答:
Workaround as follows for the moment: override the /error servlet handler, and if the ?format parameter is not either json/xml, just return the original http status error without a body.

Thus spring cannot fail on converting the body into plain format and return the response correctly (but without exception details in the body).

```<code>@Controller
public class WorkaroundBasicErrorController extends BasicErrorController {
    //default constructor from ErrorMvcAutoConfiguration
    public DefaultBasicErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties,
                                       ObjectProvider<List<ErrorViewResolver>> errorViewResolversProvider) {
        super(errorAttributes, serverProperties.getError(), errorViewResolversProvider.getIfAvailable());
    }

    @RequestMapping
    @ResponseBody
    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        String format = request.getParameter("format");

        return (StringUtils.containsAny(format, "json", "xml"))
            ? super.error(request)
            : new ResponseEntity<>(getStatus(request)); //neglect body for plain formats
    }
}
</code>```

Body:
I have a servlet where in general I return text/csv as response. So a plain comma separated string.

BUT: in case of exceptions, I'd want to show just some error text as response.  But instead Spring generates a custom ResponseEntity object, then tries to convert this response to csv which obviously fails.

Is it possible to replace the requested format to format=json, and then just return the default Spring error response?

@RestController
public class CsvServlet {

    @RequestMapping(value = "/test", produces = "text/csv")
    @ResponseBody
    public String errorCsv(HttpServletRequest request) {
        return "some, plain, text";
    }
}

Usage: localhost:8080/test?format=csv

When having spring.security.enabled=true, this will first validate the basic auth credentials. If they fail, spring will automatically redirect to /error servlet.

Thereby BasicErrorController.error() method comes in, catching the error and generating a ResponseEntity with error attributes like timestamp, exception, path, etc.

Problem: now an Object of type ResponseEntity is returned. This is fine as long as the format parameter is either ?format=json/xml. As the response can then be properly converted.

But in my special case, where I request ?format=csv, the conversation will fail, leading to:

Response could not be created:
  org.springframework.web.HttpMediaTypeNotAcceptableException: Could not
  find acceptable representation

This is partially true, moreover misleading because the user should directly see that the authentication credentials have been invalid. Because in general I'm accepting csv, but Spring and the mappers don't know how to convert a ResponseEntity to a plain format like csv.

Question: how can I preserve the original exception? So that I could just return a plain text error message. It would also be fine if I could return a application/json response in this case!

Body:
Workaround as follows for the moment: override the /error servlet handler, and if the ?format parameter is not either json/xml, just return the original http status error without a body.

Thus spring cannot fail on converting the body into plain format and return the response correctly (but without exception details in the body).

@Controller
public class WorkaroundBasicErrorController extends BasicErrorController {
    //default constructor from ErrorMvcAutoConfiguration
    public DefaultBasicErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties,
                                       ObjectProvider<List<ErrorViewResolver>> errorViewResolversProvider) {
        super(errorAttributes, serverProperties.getError(), errorViewResolversProvider.getIfAvailable());
    }

    @RequestMapping
    @ResponseBody
    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        String format = request.getParameter("format");

        return (StringUtils.containsAny(format, "json", "xml"))
            ? super.error(request)
            : new ResponseEntity<>(getStatus(request)); //neglect body for plain formats
    }
}


来源: stackexchange

问:
Dynamically generating table containing child table using rowspan and loops
I need the html table for the following table structure.

This is something similar I have tried till now: (this is a .cshtml view, which takes a model as input)

```<code>    <table>
        <tbody>
            <tr>
                <th>Code Number of Equipment</th>
                <th>Name of Equipment</th>
                <th>Brand</th>
                <th>Model</th>
                <th>Quantity</th>

                <th>Check Item</th>
                <th>Note</th>
                <th>Quoted Price</th>
            </tr>
            @foreach (var equipment in Model.Equipments)
            {
                <tr>
                    <td>@equipment.Code</td>
                    <td>@equipment.Name</td>
                    <td>@equipment.EquipmentBrand</td>
                    <td>@equipment.EquipmentModel</td>
                    <td>@String.Format("{0:n0}", equipment.Quantity)</td>
                    <td colspan="2">
                        <table >
                            <tbody >
                                @foreach (var item in equipment.EligibilityChecksheets)
                                {
                                    <tr>
                                        <td>@item.CheckListItem</td>
                                        <td>@item.Note</td>
                                    </tr>
                                }
                            </tbody>
                        </table>
                    </td>
                    <td>@String.Format("{0:n0}", Model.Currency + " " + equipment.UnitPrice)</td>
                </tr>
            }
            <tr>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th>Total : </th>
                <th>@String.Format("{0:n0}", Model.Currency + " " + Model.TotalPrice)</th>
            </tr>
        </tbody>
    </table>
</code>```

The problem with this code is - there is a gap between  and the inner table. I want to do this work using rowspan - is it possible to do it for this scenario?

答:
When you are making an HTML table, the table rows of the table are constructed sequentially in HTML; i.e.- once you create a new
, you can't add new  or other table elements in any previous
 directly from HTML.

For this reason, any variant of this approach will not work as you are expecting:

```<code><table>
    foreach(parent-row in parent-table)
    {
        <tr>
            <!-- parent table data of each row in "td"s with rowspan -->
            foreach(child-row in child-table)
            {
                <tr>
                    <!-- child table data of each row in "td"s without rowspan -->
                </tr>
            }
            <!-- remaining parent table data of each row in "td"s with rowspan -->
        </tr>
    }
</table>
</code>```

One thing I can think of about how you can do what you are asking for is -
completely construct the first row - including the first row of the child table. After constructing that row, you can construct the remaining rows of the child table for that particular parent table row.

In code, the approach will be something like this (considering rowspan = 'number of rows in child table for a particular row in the parent table'):

```<code><table>
    foreach(parent-row in parent-table)
    {
        <tr>
            <!-- parent table data of each row in "td"s with rowspan -->
            foreach(child-row in child-table) // this loop will iterate only once
            {
                <!-- child table data of first row in "td"s without rowspan -->
            }
            <!-- remaining parent table data of each row in "td"s with rowspan -->
        </tr>
        <!-- parent table row with first row of child table for that parent table row created -->
        <!-- creating the remaining rows of the child table -->
        foreach(child-row in child-table) // this loop will iterate (rowspan - 1) times
        {
            <tr>
                <!-- child table data of each row except first row in "td"s without rowspan -->
            </tr>
        }
    } // parent table row with its corresponding child table fully constructed
</table>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need the html table for the following table structure.

This is something similar I have tried till now: (this is a .cshtml view, which takes a model as input)

                Code Number of Equipment
                Name of Equipment
                Brand
                Model
                Quantity

                Check Item
                Note
                Quoted Price

            @foreach (var equipment in Model.Equipments)
            {

                    @equipment.Code
                    @equipment.Name
                    @equipment.EquipmentBrand
                    @equipment.EquipmentModel
                    @String.Format("{0:n0}", equipment.Quantity)

                                @foreach (var item in equipment.EligibilityChecksheets)
                                {

                                        @item.CheckListItem
                                        @item.Note

                                }

                    @String.Format("{0:n0}", Model.Currency + " " + equipment.UnitPrice)

            }

                Total :
                @String.Format("{0:n0}", Model.Currency + " " + Model.TotalPrice)

The problem with this code is - there is a gap between  and the inner table. I want to do this work using rowspan - is it possible to do it for this scenario?

Body:
When you are making an HTML table, the table rows of the table are constructed sequentially in HTML; i.e.- once you create a new <tr>, you can't add new <td> or other table elements in any previous <tr> directly from HTML.

For this reason, any variant of this approach will not work as you are expecting:

<table>
    foreach(parent-row in parent-table)
    {
        <tr>
            <!-- parent table data of each row in "td"s with rowspan -->
            foreach(child-row in child-table)
            {
                <tr>
                    <!-- child table data of each row in "td"s without rowspan -->
                </tr>
            }
            <!-- remaining parent table data of each row in "td"s with rowspan -->
        </tr>
    }
</table>

One thing I can think of about how you can do what you are asking for is -
completely construct the first row - including the first row of the child table. After constructing that row, you can construct the remaining rows of the child table for that particular parent table row.

In code, the approach will be something like this (considering rowspan = 'number of rows in child table for a particular row in the parent table'):

<table>
    foreach(parent-row in parent-table)
    {
        <tr>
            <!-- parent table data of each row in "td"s with rowspan -->
            foreach(child-row in child-table) // this loop will iterate only once
            {
                <!-- child table data of first row in "td"s without rowspan -->
            }
            <!-- remaining parent table data of each row in "td"s with rowspan -->
        </tr>
        <!-- parent table row with first row of child table for that parent table row created -->
        <!-- creating the remaining rows of the child table -->
        foreach(child-row in child-table) // this loop will iterate (rowspan - 1) times
        {
            <tr>
                <!-- child table data of each row except first row in "td"s without rowspan -->
            </tr>
        }
    } // parent table row with its corresponding child table fully constructed
</table>


问:
Reorder to some items and changing primary key
I've a table MENU_ITEMS with a column SEQ to define the position at which each item should be displayed in a menu.  Simplified for the sake of this question, something like...

```<code>MENU_ITEMS:
ITEM_CODE    PARENT_CODE   SEQ* (*unique to parent)
------------------------------
BANANAS      FRUIT         1
APPLES       FRUIT         2
CHERRIES     FRUIT         4
DURIANS      FRUIT         3
POTATOES     VEG           1
</code>```

I've a procedure to re-order the items.  One of its parameters is a string array containing the ITEM_CODEs in the new order.  As it stands, something like this...

```<code>procedure arrange_items(
  ITEM_CODES in CORE.T_STRINGARRAY,
  PARENT in VARCHAR2
)
as
  V_SEQS T_NUMBERARRAY := T_NUMBERARRAY();
begin

  for i in 1..ITEM_CODES.count loop
    V_SEQS.extend();
    V_SEQS(i) := i;
  end loop

  forall i in 1..ITEM_CODES.count
    update MENU_ITEMS
    set SEQ = V_SEQS(i)
    where ITEM_CODE = ITEM_CODES(i) and PARENT_CODE = PARENT;

end arrange_items
</code>```

PROBLEM

When calling the procedure with ITEM_CODES = ("APPLES", "BANANAS", "CHERRIES"), I get a 'unique constraint violated' exception (...presumably because the first item's SEQ can't be set to 1 while there exists another row whose SEQ is also 1)

I don't know how to handle items that weren't specified in the ITEM_CODES parameter, whose sequence is irrelevant (being disabled menu items and never displayed.) NB: Only the items to be re-arranged can be included in the ITEM_CODES array parameter; disabled items not requiring re-arranging can't be passed in.

Reading the Oracle docs seems to suggest a BULK COLLECT/UPDATE is needed to change all the records in one hit without violating the unique constraint (I had thought FORALL instead of FOR LOOP might do this) but I have extremely limited SQL knowledge and can't get the application right, nor can I see a way of taking into account the unspecified ITEM_CODES whose sequence might need changing just to avoid conflicting with the codes that were specified.

Is anyone able to suggest at least the correct approach I should investigate, if not a working solution?

答:
You can't do this directly with FORALL Agreed with Kaushik: disable the constraint.

solution without Disabling the constraint: add Max(SEQ) +1 to every row, then do your thing:

```<code>create or replace procedure arrange_items(
  ITEM_CODES in T_STRINGARRAY,
  PARENT in VARCHAR2
) as
  V_SEQS T_NUMBERARRAY := T_NUMBERARRAY();
  i pls_integer;
  mx number;
begin
  -- calculat max:
  select max(seq) into mx from MENU_ITEMS;
  -- Add max(SEQ)
  update MENU_ITEMS
    set SEQ = SEQ + mx+1
  where PARENT_CODE = PARENT;
  -- then your stuff works
  for i in 1..ITEM_CODES.count loop
    V_SEQS.extend();
    V_SEQS(i) := i;
  end loop;
  forall i in 1..ITEM_CODES.count
    update MENU_ITEMS
    set SEQ = V_SEQS(i)
    where ITEM_CODE = ITEM_CODES(i) and PARENT_CODE = PARENT;
end arrange_items;
/
</code>```

Body:
I've a table MENU_ITEMS with a column SEQ to define the position at which each item should be displayed in a menu.  Simplified for the sake of this question, something like...

MENU_ITEMS:
ITEM_CODE    PARENT_CODE   SEQ* (*unique to parent)
------------------------------
BANANAS      FRUIT         1
APPLES       FRUIT         2
CHERRIES     FRUIT         4
DURIANS      FRUIT         3
POTATOES     VEG           1

I've a procedure to re-order the items.  One of its parameters is a string array containing the ITEM_CODEs in the new order.  As it stands, something like this...

procedure arrange_items(
  ITEM_CODES in CORE.T_STRINGARRAY,
  PARENT in VARCHAR2
)
as
  V_SEQS T_NUMBERARRAY := T_NUMBERARRAY();
begin

  for i in 1..ITEM_CODES.count loop
    V_SEQS.extend();
    V_SEQS(i) := i;
  end loop

  forall i in 1..ITEM_CODES.count
    update MENU_ITEMS
    set SEQ = V_SEQS(i)
    where ITEM_CODE = ITEM_CODES(i) and PARENT_CODE = PARENT;

end arrange_items

PROBLEM

When calling the procedure with ITEM_CODES = ("APPLES", "BANANAS", "CHERRIES"), I get a 'unique constraint violated' exception (...presumably because the first item's SEQ can't be set to 1 while there exists another row whose SEQ is also 1)

I don't know how to handle items that weren't specified in the ITEM_CODES parameter, whose sequence is irrelevant (being disabled menu items and never displayed.) NB: Only the items to be re-arranged can be included in the ITEM_CODES array parameter; disabled items not requiring re-arranging can't be passed in.

Reading the Oracle docs seems to suggest a BULK COLLECT/UPDATE is needed to change all the records in one hit without violating the unique constraint (I had thought FORALL instead of FOR LOOP might do this) but I have extremely limited SQL knowledge and can't get the application right, nor can I see a way of taking into account the unspecified ITEM_CODES whose sequence might need changing just to avoid conflicting with the codes that were specified.

Is anyone able to suggest at least the correct approach I should investigate, if not a working solution?

Body:
You can't do this directly with FORALL Agreed with Kaushik: disable the constraint.

solution without Disabling the constraint: add Max(SEQ) +1 to every row, then do your thing:

create or replace procedure arrange_items(
  ITEM_CODES in T_STRINGARRAY,
  PARENT in VARCHAR2
) as
  V_SEQS T_NUMBERARRAY := T_NUMBERARRAY();
  i pls_integer;
  mx number;
begin
  -- calculat max:
  select max(seq) into mx from MENU_ITEMS;
  -- Add max(SEQ)
  update MENU_ITEMS
    set SEQ = SEQ + mx+1
  where PARENT_CODE = PARENT;
  -- then your stuff works
  for i in 1..ITEM_CODES.count loop
    V_SEQS.extend();
    V_SEQS(i) := i;
  end loop;
  forall i in 1..ITEM_CODES.count
    update MENU_ITEMS
    set SEQ = V_SEQS(i)
    where ITEM_CODE = ITEM_CODES(i) and PARENT_CODE = PARENT;
end arrange_items;
/


问:
filter list of items when clicking category link
I have  a list of items with "ng-repeat". Each item contains a div with a link title and link category. When clicking on a category, I want to filter the list of items, so that it only shows the items belonging to that category. how can I achieve that?

So far I have a list of items:

```<code>  <div class="link_line" ng-repeat="link in links | filter: ? ">
    <div class="title"><a href="{{link.url}}" target="_blank">{{link.title}}</a></div>
    <div class="category_label" ng-click="filterCategory(link)>{{ link.category }}</div>
  </div>
</code>```

And in the controller I have a function "filterCategory" which shows an alert with the link category. And I have the "filter: ?" where I guess the value of the filter has to come. Ths is the controller function:

```<code>  $scope.filterCategory = (link) ->
    alert(link.category)
</code>```

Any idea how to proceed? Thanks!

答:
angular.module('app',[])
  .controller('MainController', function($scope) {
  $scope.team =[
    {cat_id:1,team: 'alpha'},
    {cat_id:2,team: 'beta'},
    {cat_id:3,team: 'gamma'}
               ];

    $scope.players = [
      {name: 'Gene',cat_id : 1},
      {name: 'George',cat_id : 2},
      {name: 'Steve',cat_id : 3},
      {name: 'Pzula',cat_id : 2},
      {name: 'shrikant',cat_id : 3}
    ];
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
<div ng-app="app" ng-controller="MainController">

<ul ng-repeat="(key, value) in team ">
{{value.team}}

 <li ng-repeat="p in players " ng-if="p.cat_id==value.cat_id">
   {{ p.name }}
 </li>

</ul>
</div></code>```

Body:
I have  a list of items with "ng-repeat". Each item contains a div with a link title and link category. When clicking on a category, I want to filter the list of items, so that it only shows the items belonging to that category. how can I achieve that?

So far I have a list of items:

{{link.title}}

{{ link.category }}

And in the controller I have a function "filterCategory" which shows an alert with the link category. And I have the "filter: ?" where I guess the value of the filter has to come. Ths is the controller function:

  $scope.filterCategory = (link) ->
    alert(link.category)

Any idea how to proceed? Thanks!

Body:
angular.module('app',[])
  .controller('MainController', function($scope) {
  $scope.team =[
    {cat_id:1,team: 'alpha'},
    {cat_id:2,team: 'beta'},
    {cat_id:3,team: 'gamma'}
               ];

    $scope.players = [
      {name: 'Gene',cat_id : 1},
      {name: 'George',cat_id : 2},
      {name: 'Steve',cat_id : 3},
      {name: 'Pzula',cat_id : 2},
      {name: 'shrikant',cat_id : 3}
    ];
 });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
<div ng-app="app" ng-controller="MainController">

<ul ng-repeat="(key, value) in team ">
{{value.team}}

 <li ng-repeat="p in players " ng-if="p.cat_id==value.cat_id">
   {{ p.name }}
 </li>

</ul>
</div>


问:
Make sum inside each loop Laravel
I am trying to get the sum of a property inside an each loop. Here is my code:

```<code>    $client_systems_count = 0;
    $client->accounts->each(function ($account) use ($client_systems_count) {
        dd($account->systems->count());
        $client_systems_count += $account->systems->count();
    });
    dump($client_systems_count);
</code>```

Any idea why it isn't working?
I assume that even though I change the $client_systems_count variable inside the loop every time it goes to the next element inside the collection it resets to it's initial value. So which is the correct approach to get the total systems count?

答:
This is your problem:

```<code>$client->accounts->each(function ($account) use ($client_systems_count) {
</code>```

Every time the function runs, it uses the $client_systems_count of the outer scope. Which is 0.

In order to modify that value, you need to pass it by reference:

```<code>$client->accounts->each(function ($account) use (&$client_systems_count) {
                                                 ^ here
</code>```

Title: Make sum inside each loop Laravel

Body:
I am trying to get the sum of a property inside an each loop. Here is my code:

    $client_systems_count = 0;
    $client->accounts->each(function ($account) use ($client_systems_count) {
        dd($account->systems->count());
        $client_systems_count += $account->systems->count();
    });
    dump($client_systems_count);

Any idea why it isn't working?
I assume that even though I change the $client_systems_count variable inside the loop every time it goes to the next element inside the collection it resets to it's initial value. So which is the correct approach to get the total systems count?

Body:
This is your problem:

$client->accounts->each(function ($account) use ($client_systems_count) {

Every time the function runs, it uses the $client_systems_count of the outer scope. Which is 0.

In order to modify that value, you need to pass it by reference:

$client->accounts->each(function ($account) use (&$client_systems_count) {
                                                 ^ here


问:
Can we make localhost inside native iOS app
I have to load a html file using http protocol in UIWebView or WKWebView. Here is my code using WKWebView:

```<code>import UIKit
import WebKit

class ViewController: UIViewController,WKUIDelegate {

    var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: self.view.frame, configuration: webConfiguration)
        webView.uiDelegate = self

        let path = URL(fileURLWithPath: "index.html")
        let myURL = path
        let myRequest = URLRequest(url: myURL)
        webView.load(myRequest)
        self.view.addSubview(webView)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
</code>```

Is it possible to resolve http protocal from native bundle?

答: Yes, it's possible. You need to run HTTP server in your application to achieve that. Personally, I would recommend using GCDWebServer.</p>

Body:
I have to load a html file using http protocol in UIWebView or WKWebView. Here is my code using WKWebView:

import UIKit
import WebKit

class ViewController: UIViewController,WKUIDelegate {

    var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: self.view.frame, configuration: webConfiguration)
        webView.uiDelegate = self

        let path = URL(fileURLWithPath: "index.html")
        let myURL = path
        let myRequest = URLRequest(url: myURL)
        webView.load(myRequest)
        self.view.addSubview(webView)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Is it possible to resolve http protocal from native bundle?


问:
replace url using preg_replace php
Hi all i know preg_replace can be used for formatting string but
i need help in that concerned area
my url will be like this

```<code>www.example.com/en/index.php
</code>```

or

```<code>www.example.com/fr/index.php
</code>```

what i want is to get

result as

```<code>www.example.com/index.php
</code>```

i need it in php code so as to set in a session

can anyone please explain how ?

答: preg_replace('/www.example.com\/(.+)\/index.php/i', "www.example.com/index.php?lang=$1", $url); will do the thing

ContentLicense: CC BY-SA 2.5

Title: replace url using preg_replace php

Body:
Hi all i know preg_replace can be used for formatting string but
i need help in that concerned area
my url will be like this

www.example.com/en/index.php

or

www.example.com/fr/index.php

what i want is to get

result as

www.example.com/index.php

i need it in php code so as to set in a session

can anyone please explain how ?


问:
Comparing a column's value with an array (or a series) of decreasing size
I have the following dataframe. (This isn't necessarily a dataframe; a solution on the numpy array df.values would also be sufficient)

```<code>np.random.seed(42)
df = pd.DataFrame(np.random.random((10,2)),columns=['a', 'b'])
df

        a           b
0   0.374540    0.950714
1   0.731994    0.598658
2   0.156019    0.155995
3   0.058084    0.866176
4   0.601115    0.708073
5   0.020584    0.969910
6   0.832443    0.212339
7   0.181825    0.183405
8   0.304242    0.524756
9   0.431945    0.291229
</code>```

I want to include a new column that has the value as per the below logic:

True : If any of the b values after a particular a value is greater than that partiulcar a value
False : Otherwise

The expected output would be:
(See the explanation for some of the rows below)

```<code>       a           b      c
0   0.374540    0.950714  True
1   0.731994    0.598658  True
2   0.156019    0.155995  True
3   0.058084    0.866176  True   <- np.any(0.058084 < np.array([0.708073, 0.969910, 0.212339, 0.183405, 0.524756, 0.291229]))
4   0.601115    0.708073  True   <- np.any(0.601115 < np.array([0.969910, 0.212339, 0.183405, 0.524756, 0.291229]))
5   0.020584    0.969910  True   <- np.any(0.020584 < np.array([0.212339, 0.183405, 0.524756, 0.291229]))
6   0.832443    0.212339  False  <- np.any(0.832443 < np.array([0.183405, 0.524756, 0.291229]))
7   0.181825    0.183405  True   <- np.any(0.181825 < np.array([0.524756, 0.291229]))
8   0.304242    0.524756  False  <- np.any(0.304242  < np.array([0.291229]))
9   0.431945    0.291229  UNDEFINED <- Ignore this
</code>```

The above should be possible with a for loop but what is the pandas/numpy way to do that?

I was trying for an approach where I apply a lambda function to a but l couldn't find a way to get the index of the respective a value to do the np.any comparison as shown above. (I have later discovered that apply is just syntactic sugar for a for loop, though)

```<code>df['c'] = df['a'].apply(lambda x: np.any(x < df['b'].values[<i>:])) # Where <i> is the respective index value of x; which I didn't know how to find
</code>```

答:
The trick would be to go from bottom up on b and look for accumulated maximum values and compare those against the corresponding values in a.

Hence, the implementation would be -

```<code>a = df.a.values
b = df.b.values
out = a[:-1] < np.maximum.accumulate(b[::-1])[::-1][1:]
</code>```

Porting over to pandas, the counterpart would be df.cummax for np.maximum.accumulate.

Sample run -

```<code>In [45]: df
Out[45]:
          a         b
0  0.374540  0.950714
1  0.731994  0.598658
2  0.156019  0.155995
3  0.058084  0.866176
4  0.601115  0.708073
5  0.020584  0.969910
6  0.832443  0.212339
7  0.181825  0.183405
8  0.304242  0.524756
9  0.431945  0.291229

In [46]: out
Out[46]: array([ True,  True,  True,  True,  True,  True, False,  True, False], dtype=bool)
</code>```

Body:
I have the following dataframe. (This isn't necessarily a dataframe; a solution on the numpy array df.values would also be sufficient)

np.random.seed(42)
df = pd.DataFrame(np.random.random((10,2)),columns=['a', 'b'])
df

        a           b
0   0.374540    0.950714
1   0.731994    0.598658
2   0.156019    0.155995
3   0.058084    0.866176
4   0.601115    0.708073
5   0.020584    0.969910
6   0.832443    0.212339
7   0.181825    0.183405
8   0.304242    0.524756
9   0.431945    0.291229

I want to include a new column that has the value as per the below logic:

True : If any of the b values after a particular a value is greater than that partiulcar a value
False : Otherwise

The expected output would be:
(See the explanation for some of the rows below)

       a           b      c
0   0.374540    0.950714  True
1   0.731994    0.598658  True
2   0.156019    0.155995  True
3   0.058084    0.866176  True   <- np.any(0.058084 < np.array([0.708073, 0.969910, 0.212339, 0.183405, 0.524756, 0.291229]))
4   0.601115    0.708073  True   <- np.any(0.601115 < np.array([0.969910, 0.212339, 0.183405, 0.524756, 0.291229]))
5   0.020584    0.969910  True   <- np.any(0.020584 < np.array([0.212339, 0.183405, 0.524756, 0.291229]))
6   0.832443    0.212339  False  <- np.any(0.832443 < np.array([0.183405, 0.524756, 0.291229]))
7   0.181825    0.183405  True   <- np.any(0.181825 < np.array([0.524756, 0.291229]))
8   0.304242    0.524756  False  <- np.any(0.304242  < np.array([0.291229]))
9   0.431945    0.291229  UNDEFINED <- Ignore this

The above should be possible with a for loop but what is the pandas/numpy way to do that?

I was trying for an approach where I apply a lambda function to a but l couldn't find a way to get the index of the respective a value to do the np.any comparison as shown above. (I have later discovered that apply is just syntactic sugar for a for loop, though)

df['c'] = df['a'].apply(lambda x: np.any(x < df['b'].values[:])) # Where  is the respective index value of x; which I didn't know how to find

Body:
The trick would be to go from bottom up on b and look for accumulated maximum values and compare those against the corresponding values in a.

Hence, the implementation would be -

a = df.a.values
b = df.b.values
out = a[:-1] < np.maximum.accumulate(b[::-1])[::-1][1:]

Porting over to pandas, the counterpart would be df.cummax for np.maximum.accumulate.

Sample run -

In [45]: df
Out[45]:
          a         b
0  0.374540  0.950714
1  0.731994  0.598658
2  0.156019  0.155995
3  0.058084  0.866176
4  0.601115  0.708073
5  0.020584  0.969910
6  0.832443  0.212339
7  0.181825  0.183405
8  0.304242  0.524756
9  0.431945  0.291229

In [46]: out
Out[46]: array([ True,  True,  True,  True,  True,  True, False,  True, False], dtype=bool)


问:
Is there a way to read the exact values on a colormap "image"?
So I have a *.jpg image and it basically represents a 2D colormap with a colorbar beside it that shows the range of values on the map (just imagine you make a filled 2-D contour plot with MATLAB and take a screenshot from it; something like that!). I was wondering if there is a way to read the exact values (or at least values that are closed to the exact values) from this colormap, based on the numbers on its colorbar? I have also attached the image that I'm talking about:

答:
Yes. You just do the same as a human would do. Take the colour and see which value belongs to it.

Of course you are limited to the resolution of your colour map.


问:
Showing data from pickerview
I have designed a tableview cell with a textfield for pickerview. AndI have loaded 2 of those cells in my tableview. In order to show data from the pickerview this is what I did in cellForRowAt...

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell: sellTableViewCell = tableView.dequeueReusableCell(withIdentifier: "sellProductIdentifier") as! sellTableViewCell
        cell.delegate = self

        let pickerView = UIPickerView()
        pickerView.delegate = self
        cell.pickerField.inputView = pickerView
        cell.pickerField.text = myData[0]//myData is an array with values from 1-10

        myCell = cell //The issue seems to be here.

        return cell
    }
</code>```

And the picker view methods I have given like this...

```<code>func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return myData.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return myData[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    myCell.pickerField.text = myData[row]
}
</code>```

The issue is if I click on the 2nd pickerview the value I select is assigned to the textfield. But when I select a value from the 1st field that value is shown in the 2nd field instead of 1st.

EDIT: This is my code in cellForRowAt...

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: sellTableViewCell = tableView.dequeueReusableCell(withIdentifier: "sellProductIdentifier") as! sellTableViewCell
    cell.delegate = self

    let pickerView = MyPickerView()
    pickerView.cell = cell
    pickerView.delegate = self
    cell.qtyPickerField.inputView = pickerView

    return cell
}
</code>```

This is the picker view methods...

```<code>        func numberOfComponents(in pickerView: UIPickerView) -> Int {
            return 1
        }

        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return myData.count
        }

        func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            return myData[row]
        }

        func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

            if pickerView is MyPickerView {

                if let cell = (pickerView as! MyPickerView).cell {
                    let indexpath = self.tableview.indexPath(for: cell)
                    if let index = indexpath {
                        (pickerView as! MyPickerView).cell?.qtyPickerField?.text = myData[index.row]

    }
    }
    }

}
</code>```

EDIT 2 . code of pickerview didSelectRow

```<code>func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

if pickerView is MyPickerView {

        if let cell = (pickerView as! MyPickerView).cell {

            cell.qtyPickerField.text = myData[row]
            let indexPath = self.tableview.indexPath(for: cell)
            if let index = indexPath {
                (pickerView as! MyPickerView).cell?.qtyPickerField?.text = myData[index.row]
            }
        }

    }
}
</code>```

答:
You need to Implement Picker view delegates in your custom cell class sellTableViewCell

you should implement picker delegate in custom cell so you don't have to take refrence of cell and update text in textfield of that cell. if you have these delegate methods implemented in cell then you have to update text in textfield of that instance of cell. so there will not be mixing of text in different cell. At the same time you have to update this value in your data model object for that indexPath in array so the value can be retained while you scroll. See my answer on this link to know how to implement.

Title: Showing data from pickerview

Body:
I have designed a tableview cell with a textfield for pickerview. AndI have loaded 2 of those cells in my tableview. In order to show data from the pickerview this is what I did in cellForRowAt...

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell: sellTableViewCell = tableView.dequeueReusableCell(withIdentifier: "sellProductIdentifier") as! sellTableViewCell
        cell.delegate = self

        let pickerView = UIPickerView()
        pickerView.delegate = self
        cell.pickerField.inputView = pickerView
        cell.pickerField.text = myData[0]//myData is an array with values from 1-10

        myCell = cell //The issue seems to be here.

        return cell
    }

And the picker view methods I have given like this...

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return myData.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return myData[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    myCell.pickerField.text = myData[row]
}

The issue is if I click on the 2nd pickerview the value I select is assigned to the textfield. But when I select a value from the 1st field that value is shown in the 2nd field instead of 1st.

EDIT: This is my code in cellForRowAt...

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: sellTableViewCell = tableView.dequeueReusableCell(withIdentifier: "sellProductIdentifier") as! sellTableViewCell
    cell.delegate = self

    let pickerView = MyPickerView()
    pickerView.cell = cell
    pickerView.delegate = self
    cell.qtyPickerField.inputView = pickerView

    return cell
}

This is the picker view methods...

        func numberOfComponents(in pickerView: UIPickerView) -> Int {
            return 1
        }

        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return myData.count
        }

        func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            return myData[row]
        }

        func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

            if pickerView is MyPickerView {

                if let cell = (pickerView as! MyPickerView).cell {
                    let indexpath = self.tableview.indexPath(for: cell)
                    if let index = indexpath {
                        (pickerView as! MyPickerView).cell?.qtyPickerField?.text = myData[index.row]

    }
    }
    }

}

EDIT 2 . code of pickerview didSelectRow

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

if pickerView is MyPickerView {

        if let cell = (pickerView as! MyPickerView).cell {

            cell.qtyPickerField.text = myData[row]
            let indexPath = self.tableview.indexPath(for: cell)
            if let index = indexPath {
                (pickerView as! MyPickerView).cell?.qtyPickerField?.text = myData[index.row]
            }
        }

    }
}


问:
how to set the primary key when writing a pandas dataframe to a sqlite database table using df.to_sql
I have created a sqlite database using pandas df.to_sql however accessing it seems considerably slower than just reading in the 500mb csv file.

I need to:

set the primary key for each table using the df.to_sql method

tell the sqlite database what datatype each of the columns in my
3.dataframe are? - can I pass a list like [integer,integer,text,text]

code.... (format code button not working)

```<code>if ext == ".csv":
df = pd.read_csv("/Users/data/" +filename)
columns = df.columns columns = [i.replace(' ', '_') for i in columns]

df.columns = columns
df.to_sql(name,con,flavor='sqlite',schema=None,if_exists='replace',index=True,index_label=None, chunksize=None, dtype=None)
</code>```

答:
Building on Chris Guarino's answer, here's some functions that provide a more general solution.  See the example at the bottom for how to use them.

```<code>import re

def get_create_table_string(tablename, connection):
    sql = """
    select * from sqlite_master where name = "{}" and type = "table"
    """.format(tablename)
    result = connection.execute(sql)

    create_table_string = result.fetchmany()[0][4]
    return create_table_string

def add_pk_to_create_table_string(create_table_string, colname):
    regex = "(\n.+{}[^,]+)(,)".format(colname)
    return re.sub(regex, "\\1 PRIMARY KEY,",  create_table_string, count=1)

def add_pk_to_sqlite_table(tablename, index_column, connection):
    cts = get_create_table_string(tablename, connection)
    cts = add_pk_to_create_table_string(cts, index_column)
    template = """
    BEGIN TRANSACTION;
        ALTER TABLE {tablename} RENAME TO {tablename}_old_;

        {cts};

        INSERT INTO {tablename} SELECT * FROM {tablename}_old_;

        DROP TABLE {tablename}_old_;

    COMMIT TRANSACTION;
    """

    create_and_drop_sql = template.format(tablename = tablename, cts = cts)
    connection.executescript(create_and_drop_sql)

# Example:

# import pandas as pd
# import sqlite3

# df = pd.DataFrame({"a": [1,2,3], "b": [2,3,4]})
# con = sqlite3.connect("deleteme.db")
# df.to_sql("df", con, if_exists="replace")

# add_pk_to_sqlite_table("df", "index", con)
# r = con.execute("select sql from sqlite_master where name = 'df' and type = 'table'")
# print(r.fetchone()[0])
</code>```

There is a gist of this code here

Body:
I have created a sqlite database using pandas df.to_sql however accessing it seems considerably slower than just reading in the 500mb csv file.

I need to:

set the primary key for each table using the df.to_sql method

tell the sqlite database what datatype each of the columns in my
3.dataframe are? - can I pass a list like [integer,integer,text,text]

code.... (format code button not working)

if ext == ".csv":
df = pd.read_csv("/Users/data/" +filename)
columns = df.columns columns = [i.replace(' ', '_') for i in columns]

df.columns = columns
df.to_sql(name,con,flavor='sqlite',schema=None,if_exists='replace',index=True,index_label=None, chunksize=None, dtype=None)

Body:
Building on Chris Guarino's answer, here's some functions that provide a more general solution.  See the example at the bottom for how to use them.

import re

def get_create_table_string(tablename, connection):
    sql = """
    select * from sqlite_master where name = "{}" and type = "table"
    """.format(tablename)
    result = connection.execute(sql)

    create_table_string = result.fetchmany()[0][4]
    return create_table_string

def add_pk_to_create_table_string(create_table_string, colname):
    regex = "(\n.+{}[^,]+)(,)".format(colname)
    return re.sub(regex, "\\1 PRIMARY KEY,",  create_table_string, count=1)

def add_pk_to_sqlite_table(tablename, index_column, connection):
    cts = get_create_table_string(tablename, connection)
    cts = add_pk_to_create_table_string(cts, index_column)
    template = """
    BEGIN TRANSACTION;
        ALTER TABLE {tablename} RENAME TO {tablename}_old_;

        {cts};

        INSERT INTO {tablename} SELECT * FROM {tablename}_old_;

        DROP TABLE {tablename}_old_;

    COMMIT TRANSACTION;
    """

    create_and_drop_sql = template.format(tablename = tablename, cts = cts)
    connection.executescript(create_and_drop_sql)

# Example:

# import pandas as pd
# import sqlite3

# df = pd.DataFrame({"a": [1,2,3], "b": [2,3,4]})
# con = sqlite3.connect("deleteme.db")
# df.to_sql("df", con, if_exists="replace")

# add_pk_to_sqlite_table("df", "index", con)
# r = con.execute("select sql from sqlite_master where name = 'df' and type = 'table'")
# print(r.fetchone()[0])

There is a gist of this code here


问:
Why does scipys stats.bernoulli.rvs yields an array with dtype int32?
I am wondering why scipys random variable class stats.bernoulli yields ndarrays with dtype int32 as samples:

```<code> > stats.bernoulli.rvs(0.3, size=10)
 array([0, 1, 0, 1, 0, 1, 0, 0, 0, 1]
 > stats.bernoulli.rvs(0.3, size=10).dtype
 dtype('int32')
</code>```

Using 32-Bit-Integer values for binary results seems to be extremely inefficient. I would have expected a dtype of np.bool or np.int8.

Does anyone know the reason for the decision to generate int32 arrays as samples?

Remark: I am working with big (10^8) samples. Strangely, a conversion to int8 does not give me a any better performance, neither with creating the array nor with calculating function over the array. Maybe because my CPU can just handly 32-bit / 64-bit chunks...

答:
On my system it's int64, so yeah, it's just a default integer size. Why not bool you say. In the source code it uses scipy.hypergeom which returns integers.
The only way I can think of is to pre-initialize your output arrays with dtype=np.bool, if you can. Then although you will still waste some memory on generation of stats.bernoulli.rvs, you can clear it up right after.

Body:
I am wondering why scipys random variable class stats.bernoulli yields ndarrays with dtype int32 as samples:

 > stats.bernoulli.rvs(0.3, size=10)
 array([0, 1, 0, 1, 0, 1, 0, 0, 0, 1]
 > stats.bernoulli.rvs(0.3, size=10).dtype
 dtype('int32')

Using 32-Bit-Integer values for binary results seems to be extremely inefficient. I would have expected a dtype of np.bool or np.int8.

Does anyone know the reason for the decision to generate int32 arrays as samples?

Remark: I am working with big (10^8) samples. Strangely, a conversion to int8 does not give me a any better performance, neither with creating the array nor with calculating function over the array. Maybe because my CPU can just handly 32-bit / 64-bit chunks...


问:
SQL Data warehouse: Incorrect syntax near 'OFFSET'
I am trying out few functionalities in SQL data warehouse. I was trying out OFFSET with sample dataset provided with SQL data warehouse. I got error: Incorrect syntax near 'OFFSET'.

I have checked the database compatibility version and it is 130(SQL Server 2016). Following is the query I am trying:

```<code>SELECT [SalesQuotaKey]
      ,[EmployeeKey]
      ,[DateKey]
      ,[CalendarYear]
      ,[CalendarQuarter]
      ,[SalesAmountQuota]
  FROM [dbo].[FactSalesQuota]
  order by [SalesAmountQuota] desc
  OFFSET 0 ROWS
    FETCH NEXT 10 ROWS ONLY;
</code>```

Is there anything I am missing in query or do I need to do any settings change to enable using OFFSET?

答:
As per docs Offset Fetch is not supported in AzureDW

-- Syntax for Azure SQL Data Warehouse and Parallel Data Warehouse

[ ORDER BY

      {

      order_by_expression

      [ ASC | DESC ]

      } [ ,...n ]

  ]

You can simulate OFFSET Fetch in DW using RowNumber like below

```<code>select * from
(
SELECT [SalesQuotaKey]
      ,[EmployeeKey]
      ,[DateKey]
      ,[CalendarYear]
      ,[CalendarQuarter]
      ,[SalesAmountQuota],
Row_number() over (order by salesamount desc) as rownum
  FROM [dbo].[FactSalesQuota]

)tbl
where rownum between 1 and 10
</code>```

Body:
I am trying out few functionalities in SQL data warehouse. I was trying out OFFSET with sample dataset provided with SQL data warehouse. I got error: Incorrect syntax near 'OFFSET'.

I have checked the database compatibility version and it is 130(SQL Server 2016). Following is the query I am trying:

SELECT [SalesQuotaKey]
      ,[EmployeeKey]
      ,[DateKey]
      ,[CalendarYear]
      ,[CalendarQuarter]
      ,[SalesAmountQuota]
  FROM [dbo].[FactSalesQuota]
  order by [SalesAmountQuota] desc
  OFFSET 0 ROWS
    FETCH NEXT 10 ROWS ONLY;

Is there anything I am missing in query or do I need to do any settings change to enable using OFFSET?

Body:
As per docs Offset Fetch is not supported in AzureDW

-- Syntax for Azure SQL Data Warehouse and Parallel Data Warehouse

[ ORDER BY

      {

      order_by_expression

      [ ASC | DESC ]

      } [ ,...n ]

  ]

You can simulate OFFSET Fetch in DW using RowNumber like below

select * from
(
SELECT [SalesQuotaKey]
      ,[EmployeeKey]
      ,[DateKey]
      ,[CalendarYear]
      ,[CalendarQuarter]
      ,[SalesAmountQuota],
Row_number() over (order by salesamount desc) as rownum
  FROM [dbo].[FactSalesQuota]

)tbl
where rownum between 1 and 10

ContentLicense: CC BY-SA 4.0


问:
is it possible to get data like Heart rate , calories etc from Nordic UART service?
I am wandering to know how to get blood pressure, calories burnt, cycling etc. data from a band which has Nordic UART service. Please help me out i didn't find any relevant answers anywhere.</p>

答: Yes, why not. It depends how data is encoded in order to receive good values. You can check this repository for examples or you can search other on Google.</p>


问:
volatile in single core cpu java
(In case of single CPU ) for understanding volatile -I know volatile forces thread to use main memory and will not keep copy in its local memory.

In one of the StackOverFlow post I see that java threads uses CPU cache and using volatile it will force to use main memory

Thread Caching and Java Memory model.

If this is the case then there should not be issue with memory visibility, since one thread can see values written by other thread (assuming on single CORE CPU we will have single cache). so volatile is usefule for single CPU?

答:
First, volatile does not force threads to use main memory. It forces threads to behave as if they were forced to use main memory. This is important because actually using main memory would slow things down to a crawl on a modern system. Fortunately that definitely doesn't actually happen.

Second, it doesn't matter how many actual cores the CPU has. A single core CPU can perfectly emulate a dual core CPU, and a JVM implementation is free to do that if it wants to. The requirement to do some form of synchronization is a Java language requirement and is independent of the hardware -- one of the whole points of Java is that you don't have to worry about that.

Title: volatile in single core cpu java


问:
How many arguments takes the foldr function of Haskell?
I am new to Haskell and I am reading the book  "Real World Haskell". In the Chapter 4 of the book the author asks as an exercise to rewrite the groupBy function using fold. One of the readers of the book (Octavian Voicu ) gave the following solution:

```<code>
theCoolGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]
theCoolGroupBy eq xs = tail $ foldr step (\_ -> [[]]) xs $ (\_ -> False)
                       where step x acc = \p -> if p x then rest p else []:rest (eq x)
                                          where rest q = let y:ys = acc q in (x:y):ys
</code>```

My question is simple: I know that foldr takes 3 arguments: a function, an initial value and a list. But in the second line of the code foldr takes 4 arguments. Why this happens?
Thank you.

答:
Scott's answer is correct, the result of the foldr is a function, so this is why it seems that foldr takes 4 arguments. The foldr functions does take 3 arguments (function, base, list):

```<code>*Main> :type foldr
foldr :: (a -> b -> b) -> b -> [a] -> b
</code>```

I'll just give here an example that is less complex:

```<code>inc :: Int -> (Int -> Int)
inc v = \x -> x + v

test = inc 2 40  -- output of test is 42
</code>```

In the above code, inc takes one argument, v, and returns a function that increments its argument by v.

As we can see below, the return type of inc 2 is a function, so its argument can simply be added at the end:

```<code>*Main> :type inc
inc :: Int -> Int -> Int
*Main> :type inc 2
inc 2 :: Int -> Int
*Main> :type inc 2 40
inc 2 40 :: Int
</code>```

Parentheses could be used to emphasize that the return value is a function, but functionally it is identical to the above code:

```<code>*Main> (inc 2) 40
42
</code>```

PS: I'm the author of the original comment :)

Body:
I am new to Haskell and I am reading the book  "Real World Haskell". In the Chapter 4 of the book the author asks as an exercise to rewrite the groupBy function using fold. One of the readers of the book (Octavian Voicu ) gave the following solution:

theCoolGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]
theCoolGroupBy eq xs = tail $ foldr step (\_ -> [[]]) xs $ (\_ -> False)
                       where step x acc = \p -> if p x then rest p else []:rest (eq x)
                                          where rest q = let y:ys = acc q in (x:y):ys

My question is simple: I know that foldr takes 3 arguments: a function, an initial value and a list. But in the second line of the code foldr takes 4 arguments. Why this happens?
Thank you.

Body:
Scott's answer is correct, the result of the foldr is a function, so this is why it seems that foldr takes 4 arguments. The foldr functions does take 3 arguments (function, base, list):

*Main> :type foldr
foldr :: (a -> b -> b) -> b -> [a] -> b

I'll just give here an example that is less complex:

inc :: Int -> (Int -> Int)
inc v = \x -> x + v

test = inc 2 40  -- output of test is 42

In the above code, inc takes one argument, v, and returns a function that increments its argument by v.

As we can see below, the return type of inc 2 is a function, so its argument can simply be added at the end:

*Main> :type inc
inc :: Int -> Int -> Int
*Main> :type inc 2
inc 2 :: Int -> Int
*Main> :type inc 2 40
inc 2 40 :: Int

Parentheses could be used to emphasize that the return value is a function, but functionally it is identical to the above code:

*Main> (inc 2) 40
42

PS: I'm the author of the original comment :)


问:
Nesting Excel formulas to extract e-mail address top-level domain
I want to extract the top-level domain from e-mail addresses using Excel formulas.

I tried it first with concatenating RIGHT(..) Formulas and splitting for the dot. Sadly I do not know how to do this recursively with excel formulas, so I swapped to deleting all characters except the last 4. Now the problem is, when I split my formulas into single cells it works perfectly fine. If I try to use them together, I get only the output of the first inner Formula. How do I fix this?

```<code>=RIGHT(B8; LEN(B8)-(LEN(B8)-4))
=RIGHT(BF8;LEN(BF8)-FIND(".";BF8))
</code>```

These are the formulas split into single cells. And here both together

```<code>=RIGHT(RIGHT(B8; LEN(B8)-(LEN(B8)-4));LEN(B8)-FIND(".";B8))
</code>```

I get the same return value as in the first row from this formula

```<code>=RIGHT(B8; LEN(B8)-(LEN(B8)-4))
</code>```

答:
This =RIGHT(B8; LEN(B8)-(LEN(B8)-4)) is just a uselessly complicated version of =RIGHT(B8; 4).

Substituting this for BF8 in

```<code>=RIGHT(BF8;LEN(BF8)-FIND(".";BF8))
</code>```

yields this

```<code>=RIGHT(RIGHT(B8; 4);LEN(RIGHT(B8; 4))-FIND(".";RIGHT(B8; 4)))
</code>```

which can be simplified as

```<code>=RIGHT(RIGHT(B8; 4);4-FIND(".";RIGHT(B8; 4)))
</code>```

So that's the answer to your question.

But note that this will fail when parsing e-mail addresses whose top-level domain name has more than 3 characters! So it won't work for e.g. test@test.info. Note that top-level domains can be up to 63 characters long!

In this earlier answer, I give a more general solution to this problem, not limited to searching a predetermined number of characters from the right.

```<code>=MID(B8;FIND(CHAR(1);SUBSTITUTE(B8;".";CHAR(1);LEN(B8)-LEN(SUBSTITUTE(B8;".";""))))+1;LEN(B8))
</code>```

returns everything after the last . in the string.

Body:
I want to extract the top-level domain from e-mail addresses using Excel formulas.

I tried it first with concatenating RIGHT(..) Formulas and splitting for the dot. Sadly I do not know how to do this recursively with excel formulas, so I swapped to deleting all characters except the last 4. Now the problem is, when I split my formulas into single cells it works perfectly fine. If I try to use them together, I get only the output of the first inner Formula. How do I fix this?

=RIGHT(B8; LEN(B8)-(LEN(B8)-4))
=RIGHT(BF8;LEN(BF8)-FIND(".";BF8))

These are the formulas split into single cells. And here both together

=RIGHT(RIGHT(B8; LEN(B8)-(LEN(B8)-4));LEN(B8)-FIND(".";B8))

I get the same return value as in the first row from this formula

=RIGHT(B8; LEN(B8)-(LEN(B8)-4))

Body:
This =RIGHT(B8; LEN(B8)-(LEN(B8)-4)) is just a uselessly complicated version of =RIGHT(B8; 4).

Substituting this for BF8 in

=RIGHT(BF8;LEN(BF8)-FIND(".";BF8))

yields this

=RIGHT(RIGHT(B8; 4);LEN(RIGHT(B8; 4))-FIND(".";RIGHT(B8; 4)))

which can be simplified as

=RIGHT(RIGHT(B8; 4);4-FIND(".";RIGHT(B8; 4)))

So that's the answer to your question.

But note that this will fail when parsing e-mail addresses whose top-level domain name has more than 3 characters! So it won't work for e.g. test@test.info. Note that top-level domains can be up to 63 characters long!

In this earlier answer, I give a more general solution to this problem, not limited to searching a predetermined number of characters from the right.

=MID(B8;FIND(CHAR(1);SUBSTITUTE(B8;".";CHAR(1);LEN(B8)-LEN(SUBSTITUTE(B8;".";""))))+1;LEN(B8))

returns everything after the last . in the string.


问:
Collections to insert record at zero position
Which collection is better to insert records at first position. I know LinkedList is better, but it takes more memory than list. I have grid in which I have to insert around 200,000+ records in descending order. It's real time grid in which trades is being inserted. FYI. I am using DevExpress grid and my application is in WPF.

答:
I'm not sure I completely understand your question but it seems as if you would like a data structure that you can iterate in LIFO (last in first out) order.

Assuming this is the case a stack data structure has LIFO behavior.

```<code>public class Model
{
    readonly Stack<object> _stack = new Stack<object>();

    public void InsertRecord(object record)
    {
        _stack.Push(record);
    }

    public IEnumerable<object> Enumerate()
    {
        return _stack.AsEnumerable();
    }
}
</code>```

Body:
I'm not sure I completely understand your question but it seems as if you would like a data structure that you can iterate in LIFO (last in first out) order.

Assuming this is the case a stack data structure has LIFO behavior.

public class Model
{
    readonly Stack<object> _stack = new Stack<object>();

    public void InsertRecord(object record)
    {
        _stack.Push(record);
    }

    public IEnumerable<object> Enumerate()
    {
        return _stack.AsEnumerable();
    }
}


问:
JavaFX Spinner - this same keyevent to more spinner
I have a little problem. I want to use this code for two spinner and I can not handle it. Thank you for your help</p>

```<code>        spinner1.getEditor().setOnKeyPressed(event -> {
        switch (event.getCode()) {
            case UP:
                spinner1.increment(1);
                break;
            case DOWN:
                spinner1.decrement(1);
                break;
            default:
        }
    });
        spinner2.getEditor().setOnKeyPressed(event -> {
        switch (event.getCode()) {
            case UP:
                spinner2.increment(1);
                break;
            case DOWN:
                spinner2.decrement(1);
                break;
            default:
        }
    });
</code>```

答:
Use single EventHandler instance ,

```<code> EventHandler eh = (EventHandler<KeyEvent>) event -> {
      Spinner sp = (Spinner) event.getSource();
      switch (event.getCode()) {
          case UP:
              sp.increment(1);
              break;
          case DOWN:
              sp.decrement(1);
              break;
          default:
      }
  };

 spinner1.getEditor().setOnKeyPressed(eh);
 spinner2.getEditor().setOnKeyPressed(eh);
</code>```

Body:
I have a little problem. I want to use this code for two spinner and I can not handle it. Thank you for your help

        spinner1.getEditor().setOnKeyPressed(event -> {
        switch (event.getCode()) {
            case UP:
                spinner1.increment(1);
                break;
            case DOWN:
                spinner1.decrement(1);
                break;
            default:
        }
    });
        spinner2.getEditor().setOnKeyPressed(event -> {
        switch (event.getCode()) {
            case UP:
                spinner2.increment(1);
                break;
            case DOWN:
                spinner2.decrement(1);
                break;
            default:
        }
    });

Body:
Use single EventHandler instance ,

 EventHandler eh = (EventHandler<KeyEvent>) event -> {
      Spinner sp = (Spinner) event.getSource();
      switch (event.getCode()) {
          case UP:
              sp.increment(1);
              break;
          case DOWN:
              sp.decrement(1);
              break;
          default:
      }
  };

 spinner1.getEditor().setOnKeyPressed(eh);
 spinner2.getEditor().setOnKeyPressed(eh);


问:
Multiple values in one entry
I am having a problem while setting my database.

The context: I have a company table that can have 0, 1 or multiples jobs. Jobs have its own table. I will need to join both table.

How can I "say" that a company has this, this and this job?

The only way I found is by creating a "job" value in the meta_key entry (of the company table) and declared the jobs in the meta_value entry but it seams not good (and will create difficulty to retrieve the jobs while joining).

答:
You are describing a many to many relation. It works like this</p>

```<code>company table
-------------
id
name
other columns

jobs table
----------
id
name
other columns

company_jobs table
------------------
company_id
job_id
</code>```

Title: Multiple values in one entry

Body:
You are describing a many to many relation. It works like this

company table
-------------
id
name
other columns

jobs table
----------
id
name
other columns

company_jobs table
------------------
company_id
job_id


问:
curl with openssl instead of nss
I'm having a client with an old shop software that has a Paypal plugin which doesn't seem to work with curl with nss. So I need to change it to openssl.

How can I tell curl to use openssl?

It's a virtual server with:

CentOS 6.7
Plesk 12.5
Quad-Core AMD Opteron(tm) Processor 2352 (4 core(s))

答:
I have an old client with server with PHP 5.3.3 using curl with SSL Version NSS/3.12.7.0. We are having trouble sending data to PayWay. They are reporting that the data is sent thru TLS1.0.

I have checked the server using

php -r '$ch = curl_init("https://www.howsmyssl.com/a/check"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $data = curl_exec($ch); curl_close($ch); $json = json_decode($data); echo $json->tls_version;'

And it's returning TLS1.0.

All solutions were to rebuild curl and php. Im on the process of rebuilding the curl. Got some errors and I have to update ca certificates first.

Did yum update ca-certificates

While updating, I see that nss is being updated.

After the ca-certificates update, I checked the tls version again, and it is now using TLS1.2!

Title: curl with openssl instead of nss


问:
PHP Coding Style Function vs Passing Variables
A bit new to the whole PHP thing.

Just wanna ask, which is better in regards to performance and security. I know both has its pros and cons, but just cant seem to come to a conclusion on which could be better for overall performance and security.

Use a PHP file with loads of functions. So every page I have will "include" the function php file, thus functions can be called in any given page.

OR

Have a PHP file that accept parameter input(not sure if that is what you call it). For example function.PHP?id=100

Any comments?

Thanks everyone :)

答:
It took me a while to try to work out what you could possibly mean by this question.

Have a PHP file that accept parameter input(not sure if that is what you call it). For example function.PHP?id=100

I guess you mean that you want to be able to include only the relevant parts of PHP code using your own user-defined function.

Unless you're very VERY good at programming, this approach is the wrong way to solve the problem. Have a google for self-modifying code for some discussion on the topic. It opens up huge code injection vulnerabilities and makes debugging the code very hard.

Even if there were no security issues, and no maintenance issues, and you are a guru programmer, the only way to pass parameters into a PHP script is via an HTTP request or by running a program - both have a huge overhead compared with reading the code directly from the local filesystem - so this approach is wrong from the performance point of view.

PHP does have functionality which appears, en face, to be very similar to what you are proposing - the autoloader. However there are some very important differences.

Most of the perfromance related stuff which you can control within PHP (i.e. not the HTTP stuff, not the DB stuff) is the amount of code the interpreter has to parse. So your first approach is flawed from a performance point of view.

The right way to solve the problem is to break down the functionality into related chunks - and keeps these in seperate files, then only include the ones you need for a particular task.


问:
Why are the scalar variables undeclared inside cursor?
I wrote a code snippet that is supposed to read a mapping table (BcwmWDConfig) and insert/update values of an outdated table (Items) in an old database (BCWM99) to a newer table in another database (WebDET99.dbo.Items).

I am getting errors that my supposedly declared (at least I thought so) variables are not declared.

```<code>DECLARE @v_bcwm_id INT = 0,
        @v_wd_guid VARCHAR = '';

DECLARE bcwm_config_read_cursor CURSOR FOR
    SELECT c.id, c.guid
    FROM BcwmWDConfig c
    WHERE c.guid IS NOT NULL;

PRINT '----READING CONFIG----';

OPEN bcwm_config_read_cursor

FETCH NEXT FROM bcwm_config_read_cursor INTO @v_bcwm_id, @v_wd_guid

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT '----READ CONFIG FOR ID: '+@v_bcwm_id+' AS GUID '+@v_wd_guid+'----'
    PRINT '----INSERTING ITEMS WITH PARENT GUID: '+@v_wd_guid+'----'

    INSERT INTO WebDET99.dbo.Items
        SELECT
            i.Id, i.Text,
            CAST(@v_wd_guid AS VARCHAR(50)),
            CAST(i.Linked_Feld AS VARCHAR(50)),
            i.Linked_Item, i.Order
        FROM
            BCWM99.dbo.Items i
        WHERE
            i.Parent_Feld = @v_bcwm_id

    PRINT '----INSERTED ITEMS WITH PARENT GUID: '+@v_wd_guid+'-----'

    FETCH NEXT FROM bcwm_config_read_cursor INTO @v_bcwm_id, @v_wd_guid
END

CLOSE bcwm_config_read_cursor;
DEALLOCATE bcwm_config_read_cursor;

SET @v_bcwm_id = 0, @v_wd_guid = '';

OPEN bcwm_config_read_cursor
FETCH NEXT FROM bcwm_config_read_cursor
INTO @v_bcwm_id, @v_wd_guid

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT '----READ CONFIG FOR ID: '+@v_bcwm_id+' AS GUID '+@v_wd_guid+'----'
    PRINT '----UPDATING ITEMS WITH LINKED FIELD: '+@v_wd_guid+'----'
    UPDATE WebDET99.dbo.Items i
        SET i.Linked_Feld = @v_wd_guid
        WHERE i.Parent_Feld = CAST(@v_bcwm_id AS VARCHAR(50))
    PRINT '----UPDATED ITEMS WITH LINKED FIELD: '+@v_wd_guid+'-----'
    FETCH NEXT FROM bcwm_config_read_cursor
    INTO @v_bcwm_id, @v_wd_guid
END
CLOSE bcwm_config_read_cursor;
DEALLOCATE bcwm_config_read_cursor;

SET     @v_bcwm_id = 0,
        @v_wd_guid = '';
</code>```

Why are they undeclared inside the cursors? Also I am pretty sure I have some smaller syntax errors in my code, I am not used to SQL Server, maybe someone finds some other issues with this procedure.

答:
Your code is sysntactically incorrect.

The first error: you cannot use Order (reserved word) without square brackets:

```<code>SELECT
    i.Id, i.Text,
    CAST(@v_wd_guid AS VARCHAR(50)),
    CAST(i.Linked_Feld AS VARCHAR(50)),
    i.Linked_Item, i.[Order] -----------------------------square brackets!
</code>```

Second error:

```<code>SET @v_bcwm_id = 0, @v_wd_guid = '';
</code>```

Should be:

```<code>SET @v_bcwm_id = 0; set @v_wd_guid = ''; ------------the same in the last row
</code>```

The last error: get rid of "i":

```<code>UPDATE WebDET99.dbo.Items
SET Linked_Feld = @v_wd_guid
WHERE Parent_Feld = CAST(@v_bcwm_id AS VARCHAR(50))
</code>```

Only then your code can be compiled.

Body:
I wrote a code snippet that is supposed to read a mapping table (BcwmWDConfig) and insert/update values of an outdated table (Items) in an old database (BCWM99) to a newer table in another database (WebDET99.dbo.Items).

I am getting errors that my supposedly declared (at least I thought so) variables are not declared.

DECLARE @v_bcwm_id INT = 0,
        @v_wd_guid VARCHAR = '';

DECLARE bcwm_config_read_cursor CURSOR FOR
    SELECT c.id, c.guid
    FROM BcwmWDConfig c
    WHERE c.guid IS NOT NULL;

PRINT '----READING CONFIG----';

OPEN bcwm_config_read_cursor

FETCH NEXT FROM bcwm_config_read_cursor INTO @v_bcwm_id, @v_wd_guid

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT '----READ CONFIG FOR ID: '+@v_bcwm_id+' AS GUID '+@v_wd_guid+'----'
    PRINT '----INSERTING ITEMS WITH PARENT GUID: '+@v_wd_guid+'----'

    INSERT INTO WebDET99.dbo.Items
        SELECT
            i.Id, i.Text,
            CAST(@v_wd_guid AS VARCHAR(50)),
            CAST(i.Linked_Feld AS VARCHAR(50)),
            i.Linked_Item, i.Order
        FROM
            BCWM99.dbo.Items i
        WHERE
            i.Parent_Feld = @v_bcwm_id

    PRINT '----INSERTED ITEMS WITH PARENT GUID: '+@v_wd_guid+'-----'

    FETCH NEXT FROM bcwm_config_read_cursor INTO @v_bcwm_id, @v_wd_guid
END

CLOSE bcwm_config_read_cursor;
DEALLOCATE bcwm_config_read_cursor;

SET @v_bcwm_id = 0, @v_wd_guid = '';

OPEN bcwm_config_read_cursor
FETCH NEXT FROM bcwm_config_read_cursor
INTO @v_bcwm_id, @v_wd_guid

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT '----READ CONFIG FOR ID: '+@v_bcwm_id+' AS GUID '+@v_wd_guid+'----'
    PRINT '----UPDATING ITEMS WITH LINKED FIELD: '+@v_wd_guid+'----'
    UPDATE WebDET99.dbo.Items i
        SET i.Linked_Feld = @v_wd_guid
        WHERE i.Parent_Feld = CAST(@v_bcwm_id AS VARCHAR(50))
    PRINT '----UPDATED ITEMS WITH LINKED FIELD: '+@v_wd_guid+'-----'
    FETCH NEXT FROM bcwm_config_read_cursor
    INTO @v_bcwm_id, @v_wd_guid
END
CLOSE bcwm_config_read_cursor;
DEALLOCATE bcwm_config_read_cursor;

SET     @v_bcwm_id = 0,
        @v_wd_guid = '';

Why are they undeclared inside the cursors? Also I am pretty sure I have some smaller syntax errors in my code, I am not used to SQL Server, maybe someone finds some other issues with this procedure.

Body:
Your code is sysntactically incorrect.

The first error: you cannot use Order (reserved word) without square brackets:

SELECT
    i.Id, i.Text,
    CAST(@v_wd_guid AS VARCHAR(50)),
    CAST(i.Linked_Feld AS VARCHAR(50)),
    i.Linked_Item, i.[Order] -----------------------------square brackets!

Second error:

SET @v_bcwm_id = 0, @v_wd_guid = '';

Should be:

SET @v_bcwm_id = 0; set @v_wd_guid = ''; ------------the same in the last row

The last error: get rid of "i":

UPDATE WebDET99.dbo.Items
SET Linked_Feld = @v_wd_guid
WHERE Parent_Feld = CAST(@v_bcwm_id AS VARCHAR(50))

Only then your code can be compiled.


问:
How do we change AppPool idle timeout in Plesk WebAdmin (Shared Hosting)?
I have a website that is hosted on Plesk in Shared Hosting. The session keeps on timing out because the app pool recycles after 5 minutes (even though session timeout is set to 30 min). The effect of session timeout is exaggerated because current user activity is quite low and for users testing the app, the session keeps on timing out every 5 minutes.

On plesk web hosting panel, I can see the AppPool settings but they are disabled. Is there a way to change this setting?

答: If you can't change IIS settings, you can use an external uptime monitor service to continuously query your website with GET requests, which will also keep it alive. Most uptime monitors don't send actual requests, however the Availability feature in Application Insights does and works perfectly for this.


问:
Calling a class based on the selected item in a listview in javafx
I have a ListView and every time the selection is changed, I want to call a class with that name. For example, if the item is called "Text String" then the class TextString should be called. The code that I currently have is giving me an error saying The method insert(ArrayList<Element>) is undefined for the type Object ... Eclipse gives me a suggestion to cast the object as Element, but that doesn't do anything.  The Element class is a superclass and TextString would implement that class.

Here is the code I have so far:

```<code>   elementList.itemsProperty().bind(listProperty);
        listProperty.set(FXCollections.observableArrayList(elementListItems));
        elementList.setOnMouseClicked(new EventHandler<MouseEvent>() {

            public String selectedElement = "Text String";
            @Override
            public void handle(MouseEvent event) {
                selectedElement  = (String)elementList.getSelectionModel().getSelectedItem();
                selectedElement = selectedElement.replace(" ", "");
                Class<?> clazz;
                try {
                    clazz = Class.forName("elements."+selectedElement);
                    Constructor<?> ctor = clazz.getConstructor();
                    Object object = ctor.newInstance();
                    Method meth = clazz.getClass().getMethod("insert", new Class<?>[] { Canvas.class, ArrayList.class, GraphicsContext.class });
                    meth.invoke(object, canvas, objects, gc);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        });
</code>```

Element.java

```<code>   public abstract class Element {
    public String name;
    public String description;
    public Canvas canvas;
    public ArrayList<Element> objects;
    public GraphicsContext gc;

    void remove(){

    }
    void toggle(){

    }
    void setBounds(int x, int y, int w, int h){

    }
    public abstract void insert(Canvas canvas, ArrayList<Element> objects, GraphicsContext gc);
}
</code>```

TextString.java

```<code>   public class TextString extends Element {
    private GraphicsContext gc;

    TextString() {
        super();
        this.name = "Text String";
        this.description = "A literal readable string of text.";
    }
    @Override
    public void insert(Canvas canvas, ArrayList<Element> objects, GraphicsContext gc) {
        this.gc = gc;
        this.canvas = canvas;
        this.objects = objects;
        System.out.println("Text string created.");
    }

}
</code>```

How can I cast the object to whatever object is being selected by the listview?

答:
There is another way you can handle this, use a HashMap to store all the implementations as follows (this can be done when your application is started, the performance will be better).

```<code>Map<String, Element> objects = new HashMap<>();
objects.put("Text String", new TextString());
</code>```

And the handle method becomes..

```<code>@Override
public void handle(MouseEvent event) {
    selectedElement = (String) elementList.getSelectionModel().getSelectedItem();
//      selectedElement = selectedElement.replace(" ", "");

    objects.get(selectedElement).insert(Canvas.class, ArrayList.class, GraphicsContext.class);

}
</code>```

This will be more readable and clean since we are not using Reflections.

Body:
I have a ListView and every time the selection is changed, I want to call a class with that name. For example, if the item is called "Text String" then the class TextString should be called. The code that I currently have is giving me an error saying The method insert(ArrayList<Element>) is undefined for the type Object ... Eclipse gives me a suggestion to cast the object as Element, but that doesn't do anything.  The Element class is a superclass and TextString would implement that class.

Here is the code I have so far:

   elementList.itemsProperty().bind(listProperty);
        listProperty.set(FXCollections.observableArrayList(elementListItems));
        elementList.setOnMouseClicked(new EventHandler<MouseEvent>() {

            public String selectedElement = "Text String";
            @Override
            public void handle(MouseEvent event) {
                selectedElement  = (String)elementList.getSelectionModel().getSelectedItem();
                selectedElement = selectedElement.replace(" ", "");
                Class<?> clazz;
                try {
                    clazz = Class.forName("elements."+selectedElement);
                    Constructor<?> ctor = clazz.getConstructor();
                    Object object = ctor.newInstance();
                    Method meth = clazz.getClass().getMethod("insert", new Class<?>[] { Canvas.class, ArrayList.class, GraphicsContext.class });
                    meth.invoke(object, canvas, objects, gc);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        });

Element.java

   public abstract class Element {
    public String name;
    public String description;
    public Canvas canvas;
    public ArrayList<Element> objects;
    public GraphicsContext gc;

    void remove(){

    }
    void toggle(){

    }
    void setBounds(int x, int y, int w, int h){

    }
    public abstract void insert(Canvas canvas, ArrayList<Element> objects, GraphicsContext gc);
}

TextString.java

   public class TextString extends Element {
    private GraphicsContext gc;

    TextString() {
        super();
        this.name = "Text String";
        this.description = "A literal readable string of text.";
    }
    @Override
    public void insert(Canvas canvas, ArrayList<Element> objects, GraphicsContext gc) {
        this.gc = gc;
        this.canvas = canvas;
        this.objects = objects;
        System.out.println("Text string created.");
    }

}

How can I cast the object to whatever object is being selected by the listview?

Body:
There is another way you can handle this, use a HashMap to store all the implementations as follows (this can be done when your application is started, the performance will be better).

Map<String, Element> objects = new HashMap<>();
objects.put("Text String", new TextString());

And the handle method becomes..

@Override
public void handle(MouseEvent event) {
    selectedElement = (String) elementList.getSelectionModel().getSelectedItem();
//      selectedElement = selectedElement.replace(" ", "");

    objects.get(selectedElement).insert(Canvas.class, ArrayList.class, GraphicsContext.class);

}

This will be more readable and clean since we are not using Reflections.


问:
Angular 2 access JSON file
I am struggling to access a local JSON file in my component file via JavaScript. In Angular 1, I would just make a service and inject it into my controller, but am lost with Angular 2.  </p>

答:
If you want to get data from local JSON file. First You need to get json data into varible using HttpClient

Angular 2 HttpClient Official Docs

then JSON data available to print Data

if your name data in jsonDATA variable then

```<code><ul>
<li *ngFor="let newData of jsonData">
{{newData.name}}
</li>
</ul>
</code>```

If you get any error after this, then please ask with your sample error code

Thanks

Title: Angular 2 access JSON file

Body:
If you want to get data from local JSON file. First You need to get json data into varible using HttpClient

Angular 2 HttpClient Official Docs

then JSON data available to print Data

if your name data in jsonDATA variable then

<ul>
<li *ngFor="let newData of jsonData">
{{newData.name}}
</li>
</ul>

If you get any error after this, then please ask with your sample error code

Thanks


问:
HTML Canvas draws all the objects with the same color, though their color attributes are different
//set up

var a_canvas = document.getElementById("a");
var context = a_canvas.getContext("2d");

//draw the graph

```<code>    function drawGraph(){
    for(i in data.nodes)
    {
            console.log(data.nodes[i].color);

            context.fillStyle = data.nodes[i].color;
            context.rect(data.nodes[i].x,data.nodes[i].y,data.nodes[i].size,data.nodes[i].size);
            context.fill();

    }
}
</code>```

The console log:

yellow
yellow
blue

But all rectanges are drawed with blue color.

What should I do, to draw fill all rectangles with its given color.

答:
Calling context.fill fills whatever was drawn in the current path. And you never reset, so you will always fill all rects with the last color in your list.

Use context.beginPath() before you set fillStyle, and subsequent fills will only affect the current path.

Fiddle

Body:
//set up

var a_canvas = document.getElementById("a");
var context = a_canvas.getContext("2d");

//draw the graph

    function drawGraph(){
    for(i in data.nodes)
    {
            console.log(data.nodes[i].color);

            context.fillStyle = data.nodes[i].color;
            context.rect(data.nodes[i].x,data.nodes[i].y,data.nodes[i].size,data.nodes[i].size);
            context.fill();

    }
}

The console log:

yellow
yellow
blue

But all rectanges are drawed with blue color.

What should I do, to draw fill all rectangles with its given color.


问:
Hidden Features of Java
After reading Hidden Features of C# I wondered, What are some of the hidden features of Java?</p>

答:
final for instance variables:

Really useful for multi-threading code and it makes it a lot easier to argue about the instance state and correctness. Haven't seen it a lot in industry context and often not thought in java classes.

static {something;}:

Used to initialize static members (also I prefer a static method to do it (because it has a name). Not thought.

OwnerDisplayName: grom

Title: Hidden Features of Java

LastEditorDisplayName: jelovirt

OwnerDisplayName: dmeister


问:
Java current machine name and logged in user?
Is it possible to get the name of the currently logged in user (Windows/Unix) and the hostname of the machine?

I assume it's just a property of some static environment class.

I've found this for the user name

```<code>com.sun.security.auth.module.NTSystem NTSystem = new
        com.sun.security.auth.module.NTSystem();
System.out.println(NTSystem.getName());
</code>```

and this for the machine name:

```<code>import java.net.InetAddress;
...
String computerName;
...
try {
    computerName = InetAddress.getLocalHost().getHostName();
}

catch(Exception ex) {
    ...
}
</code>```

Is the first one just for Windows?

And what will the second one do, if you don't have a hostname set?

答:
To get the currently logged in user:

```<code>System.getProperty("user.name"); //platform independent
</code>```

and the hostname of the machine:

```<code>java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
System.out.println("Hostname of local machine: " + localMachine.getHostName());
</code>```

OwnerDisplayName: Omar Kooheji

Body:
Is it possible to get the name of the currently logged in user (Windows/Unix) and the hostname of the machine?

I assume it's just a property of some static environment class.

I've found this for the user name

com.sun.security.auth.module.NTSystem NTSystem = new
        com.sun.security.auth.module.NTSystem();
System.out.println(NTSystem.getName());

and this for the machine name:

import java.net.InetAddress;
...
String computerName;
...
try {
    computerName = InetAddress.getLocalHost().getHostName();
}

catch(Exception ex) {
    ...
}

Is the first one just for Windows?

And what will the second one do, if you don't have a hostname set?

LastEditorDisplayName: Omar Kooheji

Body:
To get the currently logged in user:

System.getProperty("user.name"); //platform independent

and the hostname of the machine:

java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
System.out.println("Hostname of local machine: " + localMachine.getHostName());


问:
How to constraint type?
I am defining the interface for a hash:

```<code>export interface Hash<ValType> {
    [key: string | number]: ValType;
}
</code>```

This errors:

```<code>An index signature parameter type must be 'string' or 'number'. (parameter) key: string | number
</code>```

Then I tried:

```<code>export interface Hash<KeyType extends number | string, ValType> {
    [key: KeyType]: ValType;
}
</code>```

Same error.

How can I achieve this?

答:
It isn't possible to use a generic for the key on an indexer. Instead, you need to create an interface for each key type:

```<code>export interface StringHash<T> {
    [key: string]: T;
}

export interface NumberHash<T> {
    [key: number]: T;
}

const x: StringHash<Example> = {};
const y: NumberHash<Example> = {};
</code>```

Hopefully you can see that if the generic key worked, it wouldn't save you any effort non-working example to demonstrate:

```<code>export interface Hash<TKey, T> {
    [key: TKey]: T;
}

const x: Hash<string, Example> = {};
const y: Hash<number, Example> = {};
</code>```

If this were possible, all you'd be achieving is moving where the word string and number appears in the expression each time you reference the Hash. (i.e. it moves from NumberHash to Hash<number,).

This was discussed in issue #6641.

Title: How to constraint type?

Body:
I am defining the interface for a hash:

export interface Hash<ValType> {
    [key: string | number]: ValType;
}

This errors:

An index signature parameter type must be 'string' or 'number'. (parameter) key: string | number

Then I tried:

export interface Hash<KeyType extends number | string, ValType> {
    [key: KeyType]: ValType;
}

Same error.

How can I achieve this?

Body:
It isn't possible to use a generic for the key on an indexer. Instead, you need to create an interface for each key type:

export interface StringHash<T> {
    [key: string]: T;
}

export interface NumberHash<T> {
    [key: number]: T;
}

const x: StringHash<Example> = {};
const y: NumberHash<Example> = {};

Hopefully you can see that if the generic key worked, it wouldn't save you any effort non-working example to demonstrate:

export interface Hash<TKey, T> {
    [key: TKey]: T;
}

const x: Hash<string, Example> = {};
const y: Hash<number, Example> = {};

If this were possible, all you'd be achieving is moving where the word string and number appears in the expression each time you reference the Hash. (i.e. it moves from NumberHash to Hash<number,).

This was discussed in issue #6641.


问:
Can't get the array inside hashtable obj
I have an array of type Guid inside an HashTable
I get the values like the following but I can't get the array inside

```<code>    IDictionaryEnumerator enumObj = moreTable.GetEnumerator();

                while (enumObj.MoveNext())
                {
 foreach (var obj in enumObj.Value)
                    {
                        _guidList.Add(new Guid(obj.ToString()));
                    }
}
</code>```

but this doesn't working with me any one know how to extract an array stored inside Hash table

答:
You should use a type safe Dictionary and a generic List of Guid's instead:

```<code>Dictionary<Int32, Guid> guids = new Dictionary<Int32, Guid>();
guids.Add(1, new Guid("{25892e17-80f6-415f-9c65-7395632f0223}"));
guids.Add(2, new Guid("{e33898de-6302-4756-8f0c-5f6c5218e02e}"));
guids.Add(3, new Guid("{3a768eea-cbda-4926-a82d-831cb89092aa}"));
guids.Add(4, new Guid("{cd171f7c-560d-4a62-8d65-16b87419a58c}"));
guids.Add(5, new Guid("{17084b40-08f5-4bcd-a739-c0d08c176bad}"));
List<Guid> allGuids = new List<Guid>(guids.Values);
</code>```

Assuming that your key is an integer, but that doesn't matter for the answer.

If you insist upon using a HashTable instead:

```<code>Hashtable guids = new Hashtable();
//fill Hashtable like above
ArrayList allGuids = new ArrayList(guids.Values);
foreach (Guid guid in allGuids) {
    //do something with the GUID...'
}
</code>```

[ all converted from VB.Net ]

Body:
I have an array of type Guid inside an HashTable
I get the values like the following but I can't get the array inside

    IDictionaryEnumerator enumObj = moreTable.GetEnumerator();

                while (enumObj.MoveNext())
                {
 foreach (var obj in enumObj.Value)
                    {
                        _guidList.Add(new Guid(obj.ToString()));
                    }
}

but this doesn't working with me any one know how to extract an array stored inside Hash table

Body:
You should use a type safe Dictionary and a generic List of Guid's instead:

Dictionary<Int32, Guid> guids = new Dictionary<Int32, Guid>();
guids.Add(1, new Guid("{25892e17-80f6-415f-9c65-7395632f0223}"));
guids.Add(2, new Guid("{e33898de-6302-4756-8f0c-5f6c5218e02e}"));
guids.Add(3, new Guid("{3a768eea-cbda-4926-a82d-831cb89092aa}"));
guids.Add(4, new Guid("{cd171f7c-560d-4a62-8d65-16b87419a58c}"));
guids.Add(5, new Guid("{17084b40-08f5-4bcd-a739-c0d08c176bad}"));
List<Guid> allGuids = new List<Guid>(guids.Values);

Assuming that your key is an integer, but that doesn't matter for the answer.

If you insist upon using a HashTable instead:

Hashtable guids = new Hashtable();
//fill Hashtable like above
ArrayList allGuids = new ArrayList(guids.Values);
foreach (Guid guid in allGuids) {
    //do something with the GUID...'
}

[ all converted from VB.Net ]


问:
Feign Exception 403 after updating to Spring Boot 1.5.8 and Finchley/Edgware Spring Cloud
I'm relatively new to microservices and I've been trying to use this proof-of-concept application that uses Spring Boot and Spring Cloud.

The problem is that, while the app runs fine on Spring Boot 1.3.5 and Spring Cloud Brixton.RELEASE, it breaks when upgrading either one of them.

The error occurs when registering a new account, and it gives the following error:

```<code>status 403 reading AuthServiceClient#createUser(User); content:↵{"timestamp":1510753211255,"status":403,"error":"Forbidden","message":"Access Denied","path":"/uaa/users"}
</code>```

And the stack trace:

```<code>2017-11-15 15:40:11.284 ERROR 9072 --- [nio-6000-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [/accounts] threw exception [Request processing failed; nested exception is feign.FeignException: status 403 reading AuthServiceClient#createUser(User); content: {"timestamp":1510753211255,"status":403,"error":"Forbidden","message":"Access Denied","path":"/uaa/users"}] with root cause
</code>```

As this seems to be a Feign error, and AuthServiceClient.java seems to be the culprit, I've included it here:

```<code>@FeignClient(name = "auth-service")
public interface AuthServiceClient {

@RequestMapping(method = RequestMethod.POST, value = "/uaa/users", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
void createUser(User user);

}
</code>```

As there have been no changes to the code whatsoever, I don't understand what the cause could be and what to do to fix this error.

答:
Apparently there was this magic property that made it work again:

```<code>security.oauth2.resource.filter-order: 3
</code>```

in auth-service.properties

Further reading here:
SpringBoot 1.5.x + Security + OAuth2

Body:
I'm relatively new to microservices and I've been trying to use this proof-of-concept application that uses Spring Boot and Spring Cloud.

The problem is that, while the app runs fine on Spring Boot 1.3.5 and Spring Cloud Brixton.RELEASE, it breaks when upgrading either one of them.

The error occurs when registering a new account, and it gives the following error:

status 403 reading AuthServiceClient#createUser(User); content:↵{"timestamp":1510753211255,"status":403,"error":"Forbidden","message":"Access Denied","path":"/uaa/users"}

And the stack trace:

2017-11-15 15:40:11.284 ERROR 9072 --- [nio-6000-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [/accounts] threw exception [Request processing failed; nested exception is feign.FeignException: status 403 reading AuthServiceClient#createUser(User); content: {"timestamp":1510753211255,"status":403,"error":"Forbidden","message":"Access Denied","path":"/uaa/users"}] with root cause

As this seems to be a Feign error, and AuthServiceClient.java seems to be the culprit, I've included it here:

@FeignClient(name = "auth-service")
public interface AuthServiceClient {

@RequestMapping(method = RequestMethod.POST, value = "/uaa/users", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
void createUser(User user);

}

As there have been no changes to the code whatsoever, I don't understand what the cause could be and what to do to fix this error.

Body:
Apparently there was this magic property that made it work again:

security.oauth2.resource.filter-order: 3

in auth-service.properties

Further reading here:
SpringBoot 1.5.x + Security + OAuth2